output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
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 ... | Can you write a function in Python 3 where it
prints out the given value. | You are a Python code generator, capable of creating scripts from specifications. |
Prints out magic variables available in config files
alongside with their values and descriptions. | 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 + ' = ' + va... | As a Python code composer, you craft elegant and concise scripts. |
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.
... | Write a Python 3 function for
setting plugin - related parameters. | As a Python code composer, you craft elegant and concise scripts. |
Sets a fallback configuration for section. | 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 | You are a Python code architect, reviewing and designing scalable and efficient code |
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:
:... | Can you implement a function in Python 3 that
sets a placeholder for the current locale. | You are a Python code analyst, evaluating scripts for potential improvements. |
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. | 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 ... | You are a Python code generator, capable of creating scripts from specifications. |
Includes target contents into config. | 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 | You are a Python code generator, capable of creating scripts from specifications. |
Create a new section based on the given section. | 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 | You are a Python code architect, reviewing and designing scalable and efficient code |
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
... | Write a Python 3 script to
validate sections types and uniqueness. | As a Python code analyst, you investigate and solve complex coding mysteries |
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
... | Can you create a Python 3 function that
applies formatting to configuration. | You are a Python code generator, capable of creating scripts from specifications. |
Saves the current configuration into a file and returns its path. | 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)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
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.... | How would you implement a function in Python 3 that
sets the name of the object. | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | Write a Python 3 function for
setting sys. argv for python apps. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you create a Python 3 function that
sets the wsgi related parameters. | As a Python code composer, you craft elegant and concise scripts. |
Sets autoreload related parameters. | 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 | As a python code expert, you are capable of creating scripts from specifications. |
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 af... | Write a Python 3 function that can
add an alias for a module. | As a Python code composer, you craft elegant and concise scripts. |
Imports a python module. | 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... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the server related params for the subscription server. | 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.
:p... | As a python code expert, you are capable of creating scripts from specifications. |
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|uni... | Write a Python 3 script for
setting peer verification params for subscription server. | As a python code expert, you are capable of creating scripts from specifications. |
Sets the client related params. | 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 b... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Registers a new subscription intent. | How would you explain what the following Python 3 function does
def subscribe(
self, server=None, key=None, address=None, address_vassal=None,
balancing_weight=None, balancing_algo=None, modifier=None, signing=None, check_file=None, protocol=None,
sni_cert=None, sni_key=None, sni_cli... | You are a Python code generator, capable of creating scripts from specifications. |
Runs up the stack to find the location of manage. py
which will be considered a project base path. | How would you explain what the following Python 3 function does
def find_project_dir():
frame = inspect.currentframe()
while True:
frame = frame.f_back
fname = frame.f_globals['__file__']
if os.path.basename(fname) == 'manage.py':
break
return os.path.dirname(fname) | You are a Python code analyst, evaluating scripts for potential improvements. |
def run_uwsgi(config_section, compile_only=False):
"""Runs uWSGI using the given section configuration.
:param Section config_section:
:param bool compile_only: Do not run, only compile and output configuration file for run.
"""
config = config_section.as_configuration()
if compile_only:
... | Implement a Python 3 function for
running uWSGI using the given section configuration. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Loads config section from existing configuration file | Given the following Python 3 function, write the documentation
def _get_section_existing(self, name_module, name_project):
from importlib import import_module
from uwsgiconf.settings import CONFIGS_MODULE_ATTR
config = getattr(
import_module(os.path.splitext(name_module)[0], packag... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_section_new(cls, dir_base):
"""Creates a new section with default settings.
:param str|unicode dir_base:
:rtype: Section
"""
from uwsgiconf.presets.nice import PythonSection
from django.conf import settings
wsgi_app = settings.WSGI_APPLICATION
... | Create a Python 3 function for
creating a new section with default settings. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Contributes static and media file serving settings to an existing section. | How would you explain what the following Python 3 function does
def contribute_static(self):
options = self.options
if options['compile'] or not options['use_static_handler']:
return
from django.core.management import call_command
settings = self.settings
statics =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def contribute_error_pages(self):
"""Contributes generic static error massage pages to an existing section."""
static_dir = self.settings.STATIC_ROOT
if not static_dir:
# Source static directory is not configured. Use temporary.
import tempfile
static_dir = ... | Write a Python 3 script for
contributing generic static error massage pages to an existing section. | You are a Python code generator, capable of creating scripts from specifications. |
def register_file_monitor(filename, target=None):
"""Maps a specific file/directory modification event to a signal.
:param str|unicode filename: File or a directory to watch for its modification.
:param int|Signal|str|unicode target: Existing signal to raise
or Signal Target to register signal imp... | Implement a Python 3 function for
mapping a specific file or directory modification event to a signal. | As a Python code composer, you craft elegant and concise scripts. |
Sets the value of the current metric. | How would you explain what the following Python 3 function does
def set(self, value, mode=None):
if mode == 'max':
func = uwsgi.metric_set_max
elif mode == 'min':
func = uwsgi.metric_set_min
else:
func = uwsgi.metric_set
return func(self.name, value... | As a Python code analyst, you investigate and solve complex coding mysteries |
Block until a mule message is received and return it. | Given the following Python 3 function, write the documentation
def get_message(cls, signals=True, farms=False, buffer_size=65536, timeout=-1):
return decode(uwsgi.mule_get_msg(signals, farms, buffer_size, timeout)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def regenerate(session):
"""Regenerates header files for cmark under ./generated."""
if platform.system() == 'Windows':
output_dir = '../generated/windows'
else:
output_dir = '../generated/unix'
session.run(shutil.rmtree, 'build', ignore_errors=True)
session.run(os.makedirs,... | Can you implement a function in Python 3 that
regenerates header files for cmark under. generated. | As a Python code composer, you craft elegant and concise scripts. |
Filters a dictionary produced by locals. | Explain what the following Python 3 code does
def filter_locals(locals_dict, drop=None, include=None):
drop = drop or []
drop.extend([
'self',
'__class__', # py3
])
include = include or locals_dict.keys()
relevant_keys = [key for key in include if key not in drop]
locals_dict... | As a python code expert, you are capable of creating scripts from specifications. |
def get_output(cmd, args):
"""Runs a command and returns its output (stdout + stderr).
:param str|unicode cmd:
:param str|unicode|list[str|unicode] args:
:rtype: str|unicode
"""
from subprocess import Popen, STDOUT, PIPE
command = [cmd]
command.extend(listify(args))
process = Po... | Write a Python 3 function for
running a command and returns its output. | As a Python code composer, you craft elegant and concise scripts. |
Parses uWSGI
and returns object containing lists of embedded plugin names. | Given the following Python 3 function, write the documentation
def parse_command_plugins_output(out):
out = out.split('--- end of plugins list ---')[0]
out = out.partition('plugins ***')[2]
out = out.splitlines()
current_slot = 0
plugins = EmbeddedPlugins([], [])
for line in out:
line... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns attributes difference two elements tuple between uwsgi module and uwsgi stub module. | Can you generate the documentation for the following Python 3 function
def get_uwsgi_stub_attrs_diff():
try:
import uwsgi
except ImportError:
from uwsgiconf.exceptions import UwsgiconfException
raise UwsgiconfException(
'`uwsgi` module is unavailable. Calling `get_attrs_di... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Spawns uWSGI processes which will use configuration from the module. | Explain what the following Python 3 code does
def spawn_uwsgi(self, only=None):
spawned = []
configs = self.configurations
if len(configs) == 1:
alias = configs[0].alias
UwsgiRunner().spawn(self.fpath, alias, replace=True)
spawned.append((alias, os.getpid())... | You are a Python code generator, capable of creating scripts from specifications. |
def load(cls, fpath):
"""Loads a module and returns its object.
:param str|unicode fpath:
:rtype: module
"""
module_name = os.path.splitext(os.path.basename(fpath))[0]
sys.path.insert(0, os.path.dirname(fpath))
try:
module = import_module(module_name... | How would you code a function in Python 3 to
load a module and returns its object. | As a Python code analyst, you investigate and solve complex coding mysteries |
Allows managing of uWSGI log related stuff. | Make a summary of the following Python 3 code
def cmd_log(self, reopen=False, rotate=False):
cmd = b''
if reopen:
cmd += b'l'
if rotate:
cmd += b'L'
return self.send_command(cmd) | As a Python code composer, you craft elegant and concise scripts. |
def cmd_reload(self, force=False, workers_only=False, workers_chain=False):
"""Reloads uWSGI master process, workers.
:param bool force: Use forced (brutal) reload instead of a graceful one.
:param bool workers_only: Reload only workers.
:param bool workers_chain: Run chained workers re... | Implement a Python 3 function for
reloading uWSGI master process. | You are a Python code analyst, evaluating scripts for potential improvements. |
def send_command(self, cmd):
"""Sends a generic command into FIFO.
:param bytes cmd: Command chars to send into FIFO.
"""
if not cmd:
return
with open(self.fifo, 'wb') as f:
f.write(cmd) | Write a Python 3 script for
sending a generic command into the FIFO. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the PATH environment variable updated to run uwsgiconf in
| How would you explain what the following Python 3 function does
def get_env_path(cls):
return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH'] | You are a Python code analyst, evaluating scripts for potential improvements. |
Prepares current environment and returns Python binary name. | How would you explain what the following Python 3 function does
def prepare_env(cls):
os.environ['PATH'] = cls.get_env_path()
return os.path.basename(Finder.python()) | You are a Python code analyst, evaluating scripts for potential improvements. |
Spawns uWSGI using the given configuration module. | How would you explain what the following Python 3 function does
def spawn(self, filepath, configuration_alias, replace=False):
# Pass --conf as an argument to have a chance to use
# touch reloading form .py configuration file change.
args = ['uwsgi', '--ini', 'exec://%s %s --conf %s' % (self.bin... | As a python code expert, you are capable of creating scripts from specifications. |
def get(self, key, default=None, as_int=False, setter=None):
"""Gets a value from the cache.
:param str|unicode key: The cache key to get value for.
:param default: Value to return if none found in cache.
:param bool as_int: Return 64bit number instead of str.
:param callable... | How would you implement a function in Python 3 that
gets a value from the cache. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the specified key value. | Make a summary of the following Python 3 code
def set(self, key, value):
return uwsgi.cache_set(key, value, self.timeout, self.name) | You are a Python code analyst, evaluating scripts for potential improvements. |
def incr(self, key, delta=1):
"""Increments the specified key value by the specified value.
:param str|unicode key:
:param int delta:
:rtype: bool
"""
return uwsgi.cache_inc(key, delta, self.timeout, self.name) | Create a Python 3 function for
incrementing the specified key value by the specified value. | As a python code expert, you are capable of creating scripts from specifications. |
Multiplies the specified key value by the specified value. | Explain what the following Python 3 code does
def mul(self, key, value=2):
return uwsgi.cache_mul(key, value, self.timeout, self.name) | You are a Python code generator, capable of creating scripts from specifications. |
def div(self, key, value=2):
"""Divides the specified key value by the specified value.
:param str|unicode key:
:param int value:
:rtype: bool
"""
return uwsgi.cache_mul(key, value, self.timeout, self.name) | Write a Python 3 function for
dividing the specified key value by the specified value. | You are a Python code generator, capable of creating scripts from specifications. |
def recv(request_context=None, non_blocking=False):
"""Receives data from websocket.
:param request_context:
:param bool non_blocking:
:rtype: bytes|str
:raises IOError: If unable to receive a message.
"""
if non_blocking:
result = uwsgi.websocket_recv_nb(request_context)
e... | How would you implement a function in Python 3 that
receives data from the websocket. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sends a message to the current websocket. | Explain what the following Python 3 code does
def send(message, request_context=None, binary=False):
if binary:
return uwsgi.websocket_send_binary(message, request_context)
return uwsgi.websocket_send(message, request_context) | As a python code expert, you are capable of creating scripts from specifications. |
Render the given text to HTML. | Make a summary of the following Python 3 code
def markdown_to_html(text, options=0):
encoded_text = text.encode('utf-8')
raw_result = _cmark.lib.cmark_markdown_to_html(
encoded_text, len(encoded_text), options)
return _cmark.ffi.string(raw_result).decode('utf-8') | As a python code expert, you are capable of creating scripts from specifications. |
def markdown_to_html_with_extensions(text, options=0, extensions=None):
"""Render the given text to Markdown, using extensions.
This is a high-level wrapper over the various functions needed to enable
extensions, attach them to a parser, and render html.
Args:
text (str): The text to re... | Implement a function in Python 3 to
render the given text to HTML using the given extensions. | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse_document(text, options=0):
"""Parse a document and return the root node.
Args:
text (str): The text to parse.
options (int): The cmark options.
Returns:
Any: Opaque reference to the root node of the parsed syntax tree.
"""
encoded_text = text.encode('utf... | How would you code a function in Python 3 to
parse a text string and return the root node of the parsed syntax tree. | As a Python code composer, you craft elegant and concise scripts. |
def parser_feed(parser, text):
"""Direct wrapper over cmark_parser_feed."""
encoded_text = text.encode('utf-8')
return _cmark.lib.cmark_parser_feed(
parser, encoded_text, len(encoded_text)) | Write a Python 3 script to
direct wrapper over cmark_parser_feed. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Render a given syntax tree as HTML. | Can you generate the documentation for the following Python 3 function
def render_html(root, options=0, extensions=None):
if extensions is None:
extensions = _cmark.ffi.NULL
raw_result = _cmark.lib.cmark_render_html(
root, options, extensions)
return _cmark.ffi.string(raw_result).de... | As a Python code analyst, you investigate and solve complex coding mysteries |
def find_syntax_extension(name):
"""Direct wrapper over cmark_find_syntax_extension."""
encoded_name = name.encode('utf-8')
extension = _cmark.lib.cmark_find_syntax_extension(encoded_name)
if extension == _cmark.ffi.NULL:
return None
else:
return extension | Can you create a Python 3 function that
directs wrapper over cmark_find_syntax_extension. | As a Python code composer, you craft elegant and concise scripts. |
def set_basic_params(self, no_expire=None, expire_scan_interval=None, report_freed=None):
"""
:param bool no_expire: Disable auto sweep of expired items.
Since uWSGI 1.2, cache item expiration is managed by a thread in the master process,
to reduce the risk of deadlock. This thre... | Create a Python 3 function to
set basic parameters for the cache item expiration command. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_item(self, key, value, cache_name=None):
"""Add an item into the given cache.
This is a commodity option (mainly useful for testing) allowing you
to store an item in a uWSGI cache during startup.
:param str|unicode key:
:param value:
:param str|unicode cache_n... | Create a Python 3 function to
add an item into the given cache. | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a static file to the cache. | Can you tell what is the following Python 3 function doing
def add_file(self, filepath, gzip=False, cache_name=None):
command = 'load-file-in-cache'
if gzip:
command += '-gzip'
cache_name = cache_name or ''
value = '%s %s' % (cache_name, filepath)
self._set(command... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_cache(
self, name, max_items, expires=None, store=None, store_sync_interval=None, store_delete=None,
hash_algo=None, hash_size=None, key_size=None, udp_clients=None, udp_servers=None,
block_size=None, block_count=None, sync_from=None, mode_bitmap=None, use_lastmod=None,
... | Can you write a function in Python 3 where it
creates a new cache. | As a Python code composer, you craft elegant and concise scripts. |
Register a timer that will repeat the current time period seconds. | Make a summary of the following Python 3 code
def register_timer(period, target=None):
return _automate_signal(target, func=lambda sig: uwsgi.add_timer(int(sig), period)) | As a python code expert, you are capable of creating scripts from specifications. |
def register_timer_rb(period, repeat=None, target=None):
"""Add a red-black timer (based on black-red tree).
.. code-block:: python
@register_timer_rb(3)
def repeat():
do()
:param int period: The interval (seconds) at which the signal is raised.
:param int... | Can you create a Python 3 function that
registers a red - black timer based on black - red tree. | As a Python code analyst, you investigate and solve complex coding mysteries |
Register a cron for the current locale. | Make a summary of the following Python 3 code
def register_cron(weekday=None, month=None, day=None, hour=None, minute=None, target=None):
task_args_initial = {name: val for name, val in locals().items() if val is not None and name != 'target'}
task_args_casted = {}
def skip_task(check_funcs):
now =... | You are a Python code architect, reviewing and designing scalable and efficient code |
def truncate_ellipsis(line, length=30):
"""Truncate a line to the specified length followed by ``...`` unless its shorter than length already."""
l = len(line)
return line if l < length else line[:length - 3] + "..." | Can you implement a function in Python 3 that
truncates a line to the specified length followed by... unless it s shorter than length already. | You are a Python code generator, capable of creating scripts from specifications. |
The main method of pyle. | Explain what the following Python 3 code does
def pyle_evaluate(expressions=None, modules=(), inplace=False, files=None, print_traceback=False):
eval_globals = {}
eval_globals.update(STANDARD_MODULES)
for module_arg in modules or ():
for module in module_arg.strip().split(","):
module... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pyle(argv=None):
"""Execute pyle with the specified arguments, or sys.argv if no arguments specified."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-m", "--modules", dest="modules", action='append',
help="import MODULE before evaluation. May be specified more th... | Implement a function in Python 3 to
execute pyle with the specified arguments or sys. argv if no arguments specified. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def convert_to_international_phonetic_alphabet(self, arpabet):
'''
转换成国际音标
:param arpabet:
:return:
'''
word = self._convert_to_word(arpabet=arpabet)
if not word:
return None
return word.translate_to_international_phonetic_alphabet() | Write a Python 3 function that can
convert the arpabet to the international phonetic alphabet. | As a python code expert, you are capable of creating scripts from specifications. |
Convert the arpabet to a list of american phonetic alphabets. | Here you have a function in Python 3, explain what it does
def convert_to_american_phonetic_alphabet(self, arpabet):
'''
转换成美音
:param arpabet:
:return:
'''
word = self._convert_to_word(arpabet=arpabet)
if not word:
return None
return word.tr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert the arpabet to a non - English alphabet. | Here you have a function in Python 3, explain what it does
def convert_to_english_phonetic_alphabet(self, arpabet):
'''
转换成英音
:param arpabet:
:return:
'''
word = self._convert_to_word(arpabet=arpabet)
if not word:
return None
return word.tra... | You are a Python code architect, reviewing and designing scalable and efficient code |
Translate the list of phonemes to the ARPabet. | Explain what the following Python 3 code does
def translate_to_arpabet(self):
'''
转换成arpabet
:return:
'''
translations = []
for phoneme in self._phoneme_list:
if phoneme.is_vowel:
translations.append(phoneme.arpabet + self.stress.mark_arpabet... | You are a Python code analyst, evaluating scripts for potential improvements. |
def translate_to_american_phonetic_alphabet(self, hide_stress_mark=False):
'''
转换成美音音。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return:
'''
translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""
for phoneme in self._phonem... | Create a Python 3 function to
translate the list of phonemes to a list of AMerican letters. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Translate the list of phonemes to their English alphabet. | Explain what the following Python 3 code does
def translate_to_english_phonetic_alphabet(self, hide_stress_mark=False):
'''
转换成英音。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return:
'''
translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel e... | You are a Python code architect, reviewing and designing scalable and efficient code |
def translate_to_international_phonetic_alphabet(self, hide_stress_mark=False):
'''
转换成国际音标。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return:
'''
translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""
for phoneme in self._p... | Can you create a Python 3 function that
translates to international phonetic alphabet. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_login_form_component(self):
"""Initializes and returns the login form component
@rtype: LoginForm
@return: Initialized component
"""
self.dw.wait_until(
lambda: self.dw.is_present(LoginForm.locators.form),
failure_message='login form was never pre... | Can you create a Python 3 function that
initializes and returns the login form component | As a Python code composer, you craft elegant and concise scripts. |
Converts a dictionary into a named tuple | Here you have a function in Python 3, explain what it does
def objectify(dictionary, name='Object'):
o = namedtuple(name, dictionary.keys())(*dictionary.values())
return o | As a Python code composer, you craft elegant and concise scripts. |
Creates a directory if it does not exist. | Given the following Python 3 function, write the documentation
def create_directory(directory):
try:
os.makedirs(directory)
except OSError, e:
if e.errno == errno.EEXIST and os.path.isdir(directory):
pass
return directory | As a python code expert, you are capable of creating scripts from specifications. |
Adds a comment line to the query to be executed containing the line number of the calling
function. | Make a summary of the following Python 3 code
def __add_query_comment(sql):
# Inspect the call stack for the originating call
file_name = ''
line_number = ''
caller_frames = inspect.getouterframes(inspect.currentframe())
for frame in caller_frames:
if "ShapewaysDb" no... | As a python code expert, you are capable of creating scripts from specifications. |
def get_single_instance(sql, class_type, *args, **kwargs):
"""Returns an instance of class_type populated with attributes from the DB record; throws an error if no
records are found
@param sql: Sql statement to execute
@param class_type: The type of class to instantiate and populate wit... | Can you implement a function in Python 3 that
returns an instance of class_type populated with attributes from the DB record ; throws an error if no records are found | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of instances of class_type populated with attributes from the DB record
| Can you generate a brief explanation for the following Python 3 code
def get_all_instances(sql, class_type, *args, **kwargs):
records = CoyoteDb.get_all_records(sql, *args, **kwargs)
instances = [CoyoteDb.get_object_from_dictionary_representation(
dictionary=record, class_type=class_type) fo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
"""Escape dictionary values with keys as column names and values column values
@type dictionary: dict
@param dictionary: Key-values
"""
for k, v in dictionary.iteritems():
if isinstance(v, dateti... | Implement a function in Python 3 to
escape dictionary values with keys as column names and values column names and values column values | As a Python code composer, you craft elegant and concise scripts. |
Formats a dictionary to strings of fields and values for insert statements
| Can you tell what is the following Python 3 function doing
def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True):
if db_escape:
CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format)
fields = get_delimited_string_from_li... | As a python code expert, you are capable of creating scripts from specifications. |
This method should be used in query functions where user can query on any number of fields
>>> | Here you have a function in Python 3, explain what it does
def get_kwargs(**kwargs):
d = dict()
for k, v in kwargs.iteritems():
if v is not NOTSET:
d[k] = v
return d | You are a Python code generator, capable of creating scripts from specifications. |
Builds an update values clause based on the dictionary representation of an an
instance | Explain what the following Python 3 code does
def get_update_clause_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
items = []
CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format)
for k,v in dictionary.iteritems():
item = '{k} = {v}'.format(k=k, v=v)
... | As a Python code composer, you craft elegant and concise scripts. |
def get_where_clause_from_dict(dictionary, join_operator='AND'):
"""Builds a where clause from a dictionary
"""
CoyoteDb.escape_dictionary(dictionary)
clause = join_operator.join(
(' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v) # IS should be... | Can you write a function in Python 3 where it
builds a where clause from a dictionary | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a dictionary of the object s attributes ignoring methods
| How would you explain what the following Python 3 function does
def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False):
obj_dictionary = obj.__dict__
obj_dictionary_temp = obj_dictionary.copy()
for k, v in obj_dictionary.iteritems():
if omit_null_fields:... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Instantiates a new class that takes a dictionary representation and populates its attributes with a dictionary
| Make a summary of the following Python 3 code
def get_object_from_dictionary_representation(dictionary, class_type):
assert inspect.isclass(class_type), 'Cannot instantiate an object that is not a class'
instance = class_type()
CoyoteDb.update_object_from_dictionary_representation(dictionary, ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def build_where_clause(mappings, operator='AND'):
"""Constructs the where clause based on a dictionary of values
>>> build_where_clause({'id': 456, 'name': 'myrecord'}, operator='OR')
>>> 'WHERE id = 456 OR name = "myrecord" '
"""
where_clause_mappings = {}
where_clause... | Can you write a function in Python 3 where it
constructs the where clause based on a dictionary of mappings | You are a Python code architect, reviewing and designing scalable and efficient code |
def execute(*args, **kwargs):
"""Executes the sql statement, but does not commit. Returns the cursor to commit
@return: DB and cursor instance following sql execution
"""
# Inspect the call stack for the originating call
args = CoyoteDb.__add_query_comment(args[0])
db =... | Can you create a Python 3 function that
executes the sql statement but does not commit. Returns the cursor to commit | As a Python code analyst, you investigate and solve complex coding mysteries |
def execute_read_only(*args, **kwargs):
# TODO: consolidate with execute
"""Executes the sql statement, but does not commit. Returns the cursor to commit
@return: DB and cursor instance following sql execution
"""
# Inspect the call stack for the originating call
args =... | Write a Python 3 function that can
execute the sql statement but does not commit. Returns the cursor to commit | As a Python code analyst, you investigate and solve complex coding mysteries |
def execute_and_commit(*args, **kwargs):
"""Executes and commits the sql statement
@return: None
"""
db, cursor = CoyoteDb.execute(*args, **kwargs)
db.commit()
return cursor | Implement a function in Python 3 to
execute the sql statement and commits the sql statement | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update(sql, *args, **kwargs):
"""Updates and commits with an insert sql statement, returns the record, but with a small chance of a race
condition
@param sql: sql to execute
@return: The last row inserted
"""
assert "update" in sql.lower(), 'This function requires an... | Write a Python 3 function that can
update and commits with an insert sql statement returns the record | You are a Python code analyst, evaluating scripts for potential improvements. |
def delete(sql, *args, **kwargs):
"""Deletes and commits with an insert sql statement"""
assert "delete" in sql.lower(), 'This function requires a delete statement, provided: {}'.format(sql)
CoyoteDb.execute_and_commit(sql, *args, **kwargs) | Implement a Python 3 function for
deleting and commits with an insert sql statement | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_object_from_dictionary_representation(dictionary, instance):
"""Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and
values. Assumes dictionary does not have any keys for which object does not have attributes
@type dictionary: d... | Create a Python 3 function to
give a dictionary and an object instance will set all object attributes equal to the dictionary s keys and values. | As a python code expert, you are capable of creating scripts from specifications. |
def format_time(time):
"""Formats a time to be Shapeways database-compatible
@param time: Datetime or string object to format
@rtype: str
@return: Time formatted as a string
"""
# Handle time typing
try:
time = time.isoformat()
except Attribut... | Implement a function in Python 3 to
format a time to be Shapeways database - compatible with the spec. | You are a Python code architect, reviewing and designing scalable and efficient code |
def format_date(date):
"""Formats a date to be Shapeways database-compatible
@param date: Datetime or string object to format
@rtype: str
@return: Date formatted as a string
"""
# Handle time typing
try:
date = date.isoformat()
except Attribut... | Implement a function in Python 3 to
format a date to be Shapeways database - compatible with the spec. | You are a Python code generator, capable of creating scripts from specifications. |
Tests if an alert is present
| Make a summary of the following Python 3 code
def is_alert_present(self):
current_frame = None
try:
current_frame = self.driver.current_window_handle
a = self.driver.switch_to_alert()
a.text
except NoAlertPresentException:
# No alert
re... | You are a Python code architect, reviewing and designing scalable and efficient code |
Find an element by the given locator | Make a summary of the following Python 3 code
def find(self, locator, find_all=False, search_object=None, force_find=False, exclude_invisible=False):
search_object = self.driver if search_object is None else search_object
attempts = 0
while attempts < self.find_attempts + 1:
if bool... | As a python code expert, you are capable of creating scripts from specifications. |
def _find_immediately(self, locator, search_object=None):
'''
Attempts to immediately find elements on the page without waiting
@type locator: webdriverwrapper.support.locator.Locator
@param locator: Locator object describing
@type search_object: webdriverwra... | Write a Python 3 function for
attempting to find elements on the page without waiting . | As a Python code translator, you convert algorithms and pseudocode into Python. |
Find all elements matching locator | Here you have a function in Python 3, explain what it does
def find_all(self, locator, search_object=None, force_find=False):
'''
Find all elements matching locator
@type locator: webdriverwrapper.support.locator.Locator
@param locator: Locator object describing
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Find with dynamic locator. | Explain what the following Python 3 code does
def find_by_dynamic_locator(self, template_locator, variables, find_all=False, search_object=None):
'''
Find with dynamic locator
@type template_locator: webdriverwrapper.support.locator.Locator
@param template_locator: Templa... | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.