output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Lists the jobs on the server. | Explain what the following Python 3 code does
def list(self):
queue = self._get_queue()
if queue is None:
raise QueueDoesntExist
output = self.check_output('%s' %
shell_escape(queue / 'commands/list'))
job_id, info = None, None
for... | As a python code expert, you are capable of creating scripts from specifications. |
def multi_substitution(*substitutions):
"""
Take a sequence of pairs specifying substitutions, and create
a function that performs those substitutions.
>>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo')
'baz'
"""
substitutions = itertools.starmap(substitution, substitutions)
# compose function appli... | Can you implement a function in Python 3 that
creates a function that applies multiple substitutions to a single object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Remove HTML from the string s. | How would you explain what the following Python 3 function does
def simple_html_strip(s):
html_stripper = re.compile('(<!--.*?-->)|(<[^>]*>)|([^<]+)', re.DOTALL)
texts = (
match.group(3) or ''
for match
in html_stripper.finditer(s)
)
return ''.join(texts) | You are a Python code analyst, evaluating scripts for potential improvements. |
def remove_prefix(text, prefix):
"""
Remove the prefix from the text if it exists.
>>> remove_prefix('underwhelming performance', 'underwhelming ')
'performance'
>>> remove_prefix('something special', 'sample')
'something special'
"""
null, prefix, rest = text.rpartition(prefix)
return rest | Implement a function in Python 3 to
remove the prefix from the text. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove the suffix from the text. | Can you generate the documentation for the following Python 3 function
def remove_suffix(text, suffix):
rest, suffix, null = text.partition(suffix)
return rest | As a python code expert, you are capable of creating scripts from specifications. |
def common_prefix(s1, s2):
"""
Return the common prefix of two lines.
"""
index = min(len(s1), len(s2))
while s1[:index] != s2[:index]:
index -= 1
return s1[:index] | Can you implement a function in Python 3 that
returns the common prefix of two lines. | As a Python code composer, you craft elegant and concise scripts. |
Run a graph and render the tag contents for each output | Here you have a function in Python 3, explain what it does
def _get_graph(self, ctx, bundle, extensions, caller=None):
request = ctx.get('request')
if request is None:
request = get_current_request()
if ':' in bundle:
config_name, bundle = bundle.split(':')
else:
... | As a Python code composer, you craft elegant and concise scripts. |
def activate(lancet, method, project):
"""Switch to this project."""
with taskstatus("Looking up project") as ts:
if method == "key":
func = get_project_keys
elif method == "dir":
func = get_project_keys
for key, project_path in func(lancet):
if key.l... | Create a Python 3 function for
switching to this project. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This command creates a new branch and checks out the branch and environment. | Given the following Python 3 function, write the documentation
def workon(ctx, issue_id, new, base_branch):
lancet = ctx.obj
if not issue_id and not new:
raise click.UsageError("Provide either an issue ID or the --new flag.")
elif issue_id and new:
raise click.UsageError(
"Provi... | You are a Python code analyst, evaluating scripts for potential improvements. |
Start an harvest timer for the given issue. | Can you generate a brief explanation for the following Python 3 code
def time(lancet, issue):
issue = get_issue(lancet, issue)
with taskstatus("Starting harvest timer") as ts:
lancet.timer.start(issue)
ts.ok("Started harvest timer") | You are a Python code architect, reviewing and designing scalable and efficient code |
Pause work on the current issue. | Can you generate a brief explanation for the following Python 3 code
def pause(ctx):
lancet = ctx.obj
paused_status = lancet.config.get("tracker", "paused_status")
# Get the issue
issue = get_issue(lancet)
# Make sure the issue is in a correct status
transition = get_transition(ctx, lancet, is... | You are a Python code analyst, evaluating scripts for potential improvements. |
Resume work on the currently active issue. | Can you tell what is the following Python 3 function doing
def resume(ctx):
lancet = ctx.obj
username = lancet.tracker.whoami()
active_status = lancet.config.get("tracker", "active_status")
# Get the issue
issue = get_issue(lancet)
# Make sure the issue is in a correct status
transition =... | You are a Python code analyst, evaluating scripts for potential improvements. |
SSH into the given environment | Explain what the following Python 3 code does
def ssh(lancet, print_cmd, environment):
namespace = {}
with open(lancet.config.get('dploi', 'deployment_spec')) as fh:
code = compile(fh.read(), 'deployment.py', 'exec')
exec(code, {}, namespace)
config = namespace['settings'][environment]
... | You are a Python code generator, capable of creating scripts from specifications. |
def _setup_helper():
"""Print the shell integration code."""
base = os.path.abspath(os.path.dirname(__file__))
helper = os.path.join(base, "helper.sh")
with open(helper) as fh:
click.echo(fh.read()) | Create a Python 3 function to
print the shell integration code. | You are a Python code analyst, evaluating scripts for potential improvements. |
Prints a list of commands for shell completion hooks. | Given the following Python 3 function, write the documentation
def _commands(ctx):
ctx = ctx.parent
ctx.show_hidden_subcommands = False
main = ctx.command
for subcommand in main.list_commands(ctx):
cmd = main.get_command(ctx, subcommand)
if cmd is None:
continue
help... | As a python code expert, you are capable of creating scripts from specifications. |
Prints a list of arguments for shell completion hooks. | Given the following Python 3 function, write the documentation
def _arguments(ctx, command_name=None):
ctx = ctx.parent
main = ctx.command
if command_name:
command = main.get_command(ctx, command_name)
if not command:
return
else:
command = main
types = ["option"... | As a python code expert, you are capable of creating scripts from specifications. |
def _autocomplete(ctx, shell):
"""Print the shell autocompletion code."""
if not shell:
shell = os.environ.get("SHELL", "")
shell = os.path.basename(shell).lower()
if not shell:
click.secho(
"Your shell could not be detected, please pass its name "
"as the arg... | Write a Python 3 script for
printing the shell autocompletion code. | As a python code expert, you are capable of creating scripts from specifications. |
def raisefrom(exc_type, message, exc):
# type: (Any, str, BaseException) -> None
"""Call Python 3 raise from or emulate it for Python 2
Args:
exc_type (Any): Type of Exception
message (str): Error message to display
exc (BaseException): original exception
Returns:
None
... | Write a Python 3 script to
call Python 3 raise from or emulate it for Python 2 | As a Python code translator, you convert algorithms and pseudocode into Python. |
initialise the runner object | Explain what the following Python 3 code does
def init_runner(self, parser, tracers, projinfo):
''' initial some instances for preparing to run test case
@note: should not override
@param parser: instance of TestCaseParser
@param tracers: dict type for the instance of Tracer. Such a... | As a python code expert, you are capable of creating scripts from specifications. |
def _run_grid_multiprocess(self, func, iterables):
''' running case with mutil process to support selenium grid-mode(multiple web) and appium grid-mode(multiple devices).
@param func: function object
@param iterables: iterable objects
'''
multiprocessing.freeze_support()
... | Can you create a Python 3 function that
runs case with mutil process to support selenium grid - mode multiple web and appium grid - mode multiple devices. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _run_grid_multithread(self, func, iterables):
''' running case with mutil process to support selenium grid-mode(multiple web) and appium grid-mode(multiple devices).
@param func: function object
@param iterables: iterable objects
'''
f = lambda x: threading.... | Implement a function in Python 3 to
run case with mutil process to support selenium grid - mode multiple web and appium grid - mode multiple devices. | You are a Python code architect, reviewing and designing scalable and efficient code |
Initialize the environment for pyrunner | How would you explain what the following Python 3 function does
def init_project_env(subject='Automation', proj_path = None, sysencoding = "utf-8", debug = False):
''' Set the environment for pyrunner '''
# if sysencoding:
# set_sys_encode(sysencoding)
if not proj_path:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def seqfy(strs):
''' 序列化 字符串--->实际效果是,为字符串,添加行号,返回字符串
Sampe usage:
strs = ["", None, u"First-line\nSecond-line\nThird-line", u"没有换行符"]
for s in strs:
print "---"
result = seqfy(s)
print result
print unseqfy(result)
'''
if no... | Can you create a Python 3 function that
returns a string with the first N elements of the list. | You are a Python code analyst, evaluating scripts for potential improvements. |
def stepfy(strs):
''' 步骤化 字符串 --->实际效果是, 依据 序列化的字符串,转换为 Step_%s_info 的字典, 返回字典
Sample usage:
test_strs = [
"",
None,
u"First-line\nSecond-line\nThird-line",
u'1.First-line\n2.Second-line\n3.Third-line\n',
u'3.没有换行符',
u'3.有换行符\n',
"asdfasd... | Implement a Python 3 function for
finding all the stepfy strings in a string. | You are a Python code architect, reviewing and designing scalable and efficient code |
Map function to list of items and actions. | Can you tell what is the following Python 3 function doing
def map_function(func_str, fw_action_addtion=None,bw_action_addtion=None, alias_func=None):
''' Sample usage:
print map_function('set',alias_func = "ini_items");# -> ini_items
print map_function('set',fw_action_addtion="action_steps_",bw_... | You are a Python code architect, reviewing and designing scalable and efficient code |
A wrapper for subprocess. Popen that returns a list of the items in the listcmd. | Can you tell what is the following Python 3 function doing
def until_cmd(listcmd, end_expects=None, save2logfile=None, coding = encoding):
''' 执行系统命令,并等待执行完
@param listcmd: 执行的命令,列表格式
@param end_expects: 命令执行结束,在输出的最后一行,正则搜素期望值,并设置 结果标志
@param save2logfile: 设置执行过程,保存的日志
... | As a Python code composer, you craft elegant and concise scripts. |
def until(method, timeout = 30, message=''):
"""Calls the method until the return value is not False."""
end_time = time.time() + timeout
while True:
try:
value = method()
if value:
return value
except:
... | Create a Python 3 function for
calling the method until the return value is not False. | As a python code expert, you are capable of creating scripts from specifications. |
def _check_format(file_path, content):
""" check testcase format if valid
"""
if not content:
# testcase file content is empty
err_msg = u"Testcase file content is empty: {}".format(file_path)
raise p_exception.FileFormatError(err_msg)
elif no... | Can you implement a function in Python 3 that
checks testcase file format | As a Python code analyst, you investigate and solve complex coding mysteries |
def _load_yaml_file(yaml_file):
""" load yaml file and check file content format
"""
with io.open(yaml_file, 'r', encoding='utf-8') as stream:
yaml_content = yaml.load(stream)
FileUtils._check_format(yaml_file, yaml_content)
return yaml_content | Can you create a Python 3 function that
loads yaml file and check file content format | As a python code expert, you are capable of creating scripts from specifications. |
load json file and check file content format
| Given the following Python 3 function, write the documentation
def _load_json_file(json_file):
with io.open(json_file, encoding='utf-8') as data_file:
try:
json_content = json.load(data_file)
except p_exception.JSONDecodeError:
err_msg = u"JSONDecodeE... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _load_csv_file(csv_file):
""" load csv file and check file content format
@param
csv_file: csv file path
e.g. csv file content:
username,password
test1,111111
test2,222222
test3,333333
@return
... | Create a Python 3 function to
load csv file and check file content format | As a Python code composer, you craft elegant and concise scripts. |
def force_delete_file(file_path):
''' force delete a file '''
if os.path.isfile(file_path):
try:
os.remove(file_path)
return file_path
except:
return FileSystemUtils.add_unique_postfix(file_path)
else:
... | How would you code a function in Python 3 to
force delete a file | You are a Python code architect, reviewing and designing scalable and efficient code |
def mkzip(source_dir, output_filename):
'''Usage:
p = r'D:\auto\env\ttest\ins\build\lib\rock4\softtest\support'
mkzip(os.path.join(p, "appiumroot"),os.path.join(p, "appiumroot.zip"))
unzip(os.path.join(p, "appiumroot.zip"),os.path.join(p, "appiumroot2"))
'''
... | Write a Python 3 script for
creating a zip file with all the files in source_dir. | You are a Python code generator, capable of creating scripts from specifications. |
def get_imported_module_from_file(file_path):
""" import module from python file path and return imported module
"""
if p_compat.is_py3:
imported_module = importlib.machinery.SourceFileLoader('module_name', file_path).load_module()
elif p_compat.is_py2:
impo... | Write a Python 3 function that can
import module from python file path and return imported module | As a python code expert, you are capable of creating scripts from specifications. |
def filter_module(module, filter_type):
""" filter functions or variables from import module
@params
module: imported module
filter_type: "function" or "variable"
"""
filter_type = ModuleUtils.is_function if filter_type == "function" else ModuleUtils.is_vari... | Can you write a function in Python 3 where it
filters functions or variables from import module | As a python code expert, you are capable of creating scripts from specifications. |
def search_conf_item(start_path, item_type, item_name):
""" search expected function or variable recursive upward
@param
start_path: search start path
item_type: "function" or "variable"
item_name: function name or variable name
e.g.
search_... | Create a Python 3 function to
search expected function or variable recursive upward | As a python code expert, you are capable of creating scripts from specifications. |
Locates the specified data - files and returns the matches ; | Given the following Python 3 function, write the documentation
def find_data_files(source,target,patterns,isiter=False):
if glob.has_magic(source) or glob.has_magic(target):
raise ValueError("Magic not allowed in src, target")
ret = {}
for pattern in patterns:
patter... | You are a Python code generator, capable of creating scripts from specifications. |
def convert_to_order_dict(map_list):
""" convert mapping in list to ordered dict
@param (list) map_list
[
{"a": 1},
{"b": 2}
]
@return (OrderDict)
OrderDict({
"a": 1,
"b": 2
... | Create a Python 3 function to
convert mapping in list to ordered dict | You are a Python code generator, capable of creating scripts from specifications. |
initial the configuration with file that you specify
| Explain what the following Python 3 code does
def get_value_from_cfg(cfg_file):
''' initial the configuration with file that you specify
Sample usage:
config = get_value_from_cfg()
return:
return a dict -->config[sectio... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the exception info | Explain what the following Python 3 code does
def get_exception_error():
''' Get the exception info
Sample usage:
try:
raise Exception("asdfsdfsdf")
except:
print common.get_exception_error()
Return:
return the exception... | As a Python code analyst, you investigate and solve complex coding mysteries |
def echo(transferred, toBeTransferred, suffix=''):
''' usage:
for i in range(101):
ProgressBarUtils.echo(i,100)
'''
bar_len = 60
rate = transferred/float(toBeTransferred)
filled_len = int(round(bar_len * rate))
... | Can you create a Python 3 function that
echoes the amount of transferred and toBeTransferred | As a python code expert, you are capable of creating scripts from specifications. |
Print the size of the current object. | Explain what the following Python 3 code does
def echo_size(self, transferred=1, status=None):
'''Sample usage:
f=lambda x,y:x+y
ldata = range(10)
toBeTransferred = reduce(f,range(10))
progress = ProgressBarUtils("refresh", toBeTra... | As a Python code composer, you craft elegant and concise scripts. |
Print a progress bar for each of the available items. | Can you generate the documentation for the following Python 3 function
def echo_percent(self,transferred=1, status=None):
'''Sample usage:
f=lambda x,y:x+y
ldata = range(10)
toBeTransferred = reduce(f,range(10))
import time
progress... | As a Python code composer, you craft elegant and concise scripts. |
def start_service(addr, n):
""" Start a service """
s = Service(addr)
s.register('add', lambda x, y: x + y)
started = time.time()
for _ in range(n):
s.process()
duration = time.time() - started
time.sleep(0.1)
print('Service stats:')
util.print_stats(n, duration)
return | Can you implement a function in Python 3 that
starts a service n times | As a python code expert, you are capable of creating scripts from specifications. |
def start_service(addr, n):
""" Start a service """
s = Subscriber(addr)
s.socket.set_string_option(nanomsg.SUB, nanomsg.SUB_SUBSCRIBE, 'test')
started = time.time()
for _ in range(n):
msg = s.socket.recv()
s.socket.close()
duration = time.time() - started
print('Raw SUB servi... | Implement a Python 3 function for
starting a service with the given address n times. | As a python code expert, you are capable of creating scripts from specifications. |
def projects(lancet, query):
"""List Harvest projects, optionally filtered with a regexp."""
projects = lancet.timer.projects()
if query:
regexp = re.compile(query, flags=re.IGNORECASE)
def match(project):
match = regexp.search(project['name'])
if match is None:
... | How would you code a function in Python 3 to
list Harvest projects optionally filtered with a regexp. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def tasks(lancet, project_id):
"""List Harvest tasks for the given project ID."""
for task in lancet.timer.tasks(project_id):
click.echo('{:>9d} {} {}'.format(
task['id'], click.style('‣', fg='yellow'), task['name'])) | Write a Python 3 script for
listing Harvest tasks for the given project ID. | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve the long description from DESCRIPTION. rst | Here you have a function in Python 3, explain what it does
def get_long_description():
here = os.path.abspath(os.path.dirname(__file__))
with copen(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as description:
return description.read() | As a python code expert, you are capable of creating scripts from specifications. |
Flattens a list ignore all the lambdas. | Can you tell what is the following Python 3 function doing
def flatten(nested_list: list) -> list:
return list(sorted(filter(lambda y: y is not None,
list(map(lambda x: (nested_list.extend(x) # noqa: T484
if isinstance(x, list) else x)... | You are a Python code generator, capable of creating scripts from specifications. |
Get all. py files. | Explain what the following Python 3 code does
def get_py_files(dir_name: str) -> list:
return flatten([
x for x in
[["{0}/{1}".format(path, f) for f in files if f.endswith(".py")]
for path, _, files in os.walk(dir_name)
if not path.startswith("./build")] if x
]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def exit(self) -> None:
"""Raise SystemExit with correct status code and output logs."""
total = sum(len(logs) for logs in self.logs.values())
if self.json:
self.logs['total'] = total
print(json.dumps(self.logs, indent=self.indent))
else:
for name, lo... | Can you create a Python 3 function that
raises SystemExit with correct status code and output logs. | As a python code expert, you are capable of creating scripts from specifications. |
def run_linter(self, linter) -> None:
"""Run a checker class"""
self.current = linter.name
if (linter.name not in self.parser["all"].as_list("linters")
or linter.base_pyversion > sys.version_info): # noqa: W503
return
if any(x not in self.installed for x in... | Write a Python 3 function that can
run a checker class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_rcfile():
"""
Try to read a rcfile from a list of paths
"""
files = [
'{}/.millipederc'.format(os.environ.get('HOME')),
'/usr/local/etc/millipederc',
'/etc/millipederc',
]
for filepath in files:
if os.path.isfile(filepath):
with open(filepath)... | Can you write a function in Python 3 where it
tries to read a rcfile from a list of paths | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse_rcfile(rcfile):
"""
Parses rcfile
Invalid lines are ignored with a warning
"""
def parse_bool(value):
"""Parse boolean string"""
value = value.lower()
if value in ['yes', 'true']:
return True
elif value in ['no', 'false']:
return Fal... | Write a Python 3 function for
parsing the rcfile into a dict of key - value pairs. | You are a Python code architect, reviewing and designing scalable and efficient code |
Compute the settings from the arguments and rc_settings. | How would you explain what the following Python 3 function does
def compute_settings(args, rc_settings):
settings = {}
for key, value in args.items():
if key in ['reverse', 'opposite']:
settings[key] = value ^ rc_settings.get(key, False)
else:
settings[key] = value or rc_... | You are a Python code architect, reviewing and designing scalable and efficient code |
def millipede(size, comment=None, reverse=False, template='default', position=0, opposite=False):
"""
Output the millipede
"""
padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3]
padding_suite_length = len(padding_offsets)
head_padding_extra_offset = 2
if opposite:
padding_offsets.reverse... | Write a Python 3 function that can
output the millipede of the given size. | As a python code expert, you are capable of creating scripts from specifications. |
Send message as name to url. | Can you generate the documentation for the following Python 3 function
def api_post(message, url, name, http_data=None, auth=None):
try:
import requests
except ImportError:
print('requests is required to do api post.', file=sys.stderr)
sys.exit(1)
data = {name : message}
if http... | You are a Python code analyst, evaluating scripts for potential improvements. |
def read_long_description(readme_file):
""" Read package long description from README file """
try:
import pypandoc
except (ImportError, OSError) as exception:
print('No pypandoc or pandoc: %s' % (exception,))
if sys.version_info.major == 3:
handle = open(readme_file, enc... | How would you code a function in Python 3 to
read package long description from README file | You are a Python code generator, capable of creating scripts from specifications. |
def content_from_path(path, encoding='utf-8'):
"""Return the content of the specified file as a string.
This function also supports loading resources from packages.
"""
if not os.path.isabs(path) and ':' in path:
package, path = path.split(':', 1)
content = resource_string(package, path... | Can you implement a function in Python 3 that
returns the content of the specified file as a string. | As a Python code analyst, you investigate and solve complex coding mysteries |
def execute(self, method, args, ref):
""" Execute the method with args """
response = {'result': None, 'error': None, 'ref': ref}
fun = self.methods.get(method)
if not fun:
response['error'] = 'Method `{}` not found'.format(method)
else:
try:
... | How would you implement a function in Python 3 that
executes the method with args | As a Python code composer, you craft elegant and concise scripts. |
def register(self, name, fun, description=None):
""" Register function on this service """
self.methods[name] = fun
self.descriptions[name] = description | Write a Python 3 function for
registering a function on this service | As a Python code composer, you craft elegant and concise scripts. |
def parse(cls, payload):
""" Parse client request """
try:
method, args, ref = payload
except Exception as exception:
raise RequestParseError(exception)
else:
return method, args, ref | Create a Python 3 function for
parsing a client request. | You are a Python code architect, reviewing and designing scalable and efficient code |
Receive data from socket and process request | Can you generate a brief explanation for the following Python 3 code
def process(self):
response = None
try:
payload = self.receive()
method, args, ref = self.parse(payload)
response = self.execute(method, args, ref)
except AuthenticateError as exception:
... | As a python code expert, you are capable of creating scripts from specifications. |
def build_payload(cls, method, args):
""" Build the payload to be sent to a `Responder` """
ref = str(uuid.uuid4())
return (method, args, ref) | Write a Python 3 script for
building the payload to be sent to a Responder | You are a Python code analyst, evaluating scripts for potential improvements. |
def call(self, method, *args):
""" Make a call to a `Responder` and return the result """
payload = self.build_payload(method, args)
logging.debug('* Client will send payload: {}'.format(payload))
self.send(payload)
res = self.receive()
assert payload[2] == res['ref']
... | Can you create a Python 3 function that
makes a call to a Responder and return the result | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(filepath=None, filecontent=None):
""" Read the json file located at `filepath`
If `filecontent` is specified, its content will be json decoded
and loaded instead.
Usage:
config.load(filepath=None, filecontent=None):
Provide either a filepath or a json string
"""
conf =... | How would you code a function in Python 3 to
read the json file located at filepath and return a DotDict containing the configuration items. | You are a Python code generator, capable of creating scripts from specifications. |
def run_main(args: argparse.Namespace, do_exit=True) -> None:
"""Runs the checks and exits.
To extend this tool, use this function and set do_exit to False
to get returned the status code.
"""
if args.init:
generate()
return None # exit after generate instead of starting to lint
... | Create a Python 3 function to
run the checks and exits. | As a Python code analyst, you investigate and solve complex coding mysteries |
Connects to the server and logs in to the server. | Can you tell what is the following Python 3 function doing
def connect(self):
# type: () -> None
"""
Connect to server
Returns:
None
"""
if self.connection_type.lower() == 'ssl':
self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, loca... | As a Python code composer, you craft elegant and concise scripts. |
Sends an email to the specified recipients. | Make a summary of the following Python 3 code
def send(self, recipients, subject, text_body, html_body=None, sender=None, **kwargs):
# type: (List[str], str, str, Optional[str], Optional[str], Any) -> None
"""
Send email
Args:
recipients (List[str]): Email recipient
... | As a python code expert, you are capable of creating scripts from specifications. |
Gets SQLAlchemy session given url. | Make a summary of the following Python 3 code
def get_session(db_url):
# type: (str) -> Session
"""Gets SQLAlchemy session given url. Your tables must inherit
from Base in hdx.utilities.database.
Args:
db_url (str): SQLAlchemy url
Returns:
sqlalchemy.orm... | You are a Python code generator, capable of creating scripts from specifications. |
def get_params_from_sqlalchemy_url(db_url):
# type: (str) -> Dict[str,Any]
"""Gets PostgreSQL database connection parameters from SQLAlchemy url
Args:
db_url (str): SQLAlchemy url
Returns:
Dict[str,Any]: Dictionary of database connection parameters
"""
... | Write a Python 3 function for
getting PostgreSQL database connection parameters from SQLAlchemy url | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_sqlalchemy_url(database=None, host=None, port=None, username=None, password=None, driver='postgres'):
# type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str], str) -> str
"""Gets SQLAlchemy url from database connection parameters
Args:
data... | Implement a Python 3 function for
getting SQLAlchemy url from database connection parameters. | You are a Python code analyst, evaluating scripts for potential improvements. |
def wait_for_postgres(database, host, port, username, password):
# type: (Optional[str], Optional[str], Union[int, str, None], Optional[str], Optional[str]) -> None
"""Waits for PostgreSQL database to be up
Args:
database (Optional[str]): Database name
host (Optional[str... | Write a Python 3 function for
waiting for PostgreSQL database to be up | As a Python code composer, you craft elegant and concise scripts. |
def get_unset_cache(self):
"""return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint])
"""
caches = []
if self._cached_api_global_response is None:
caches.append('global')
if self._cached_api_ticker_response is None:
caches.append... | How would you code a function in Python 3 to
return : returns a tuple num_of_not_None_caches list of unset caches endpoint | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_path_for_url(url, folder=None, filename=None, overwrite=False):
# type: (str, Optional[str], Optional[str], bool) -> str
"""Get filename from url and join to provided folder or temporary folder if no folder supplied, ensuring uniqueness
Args:
url (str): URL to download
... | Create a Python 3 function for
getting filename from url and join to provided folder or temporary folder if no folder supplied. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get full url including any additional parameters | Given the following Python 3 function, write the documentation
def get_full_url(self, url):
# type: (str) -> str
"""Get full url including any additional parameters
Args:
url (str): URL for which to get full url
Returns:
str: Full url including any additional pa... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_url_for_get(url, parameters=None):
# type: (str, Optional[Dict]) -> str
"""Get full url for GET request including parameters
Args:
url (str): URL to download
parameters (Optional[Dict]): Parameters to pass. Defaults to None.
Returns:
str: Ful... | Write a Python 3 script for
getting full url for GET request including parameters | You are a Python code analyst, evaluating scripts for potential improvements. |
Get full url and all parameters including any in the url
| Can you generate the documentation for the following Python 3 function
def get_url_params_for_post(url, parameters=None):
# type: (str, Optional[Dict]) -> Tuple[str, Dict]
"""Get full url for POST request and all parameters including any in the url
Args:
url (str): URL to download
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Stream file from url and hash it using MD5. | Can you generate a brief explanation for the following Python 3 code
def hash_stream(self, url):
# type: (str) -> str
"""Stream file from url and hash it using MD5. Must call setup method first.
Args:
url (str): URL to download
Returns:
str: MD5 hash of file
... | You are a Python code generator, capable of creating scripts from specifications. |
Stream file from url and store in provided folder or temporary folder if no folder supplied. | How would you explain what the following Python 3 function does
def stream_file(self, url, folder=None, filename=None, overwrite=False):
# type: (str, Optional[str], Optional[str], bool) -> str
"""Stream file from url and store in provided folder or temporary folder if no folder supplied.
Must c... | As a Python code composer, you craft elegant and concise scripts. |
Download file from url and store in provided folder or temporary folder if no folder supplied | Can you tell what is the following Python 3 function doing
def download_file(self, url, folder=None, filename=None, overwrite=False,
post=False, parameters=None, timeout=None):
# type: (str, Optional[str], Optional[str], bool, bool, Optional[Dict], Optional[float]) -> str
"""Downlo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Download the object from the specified URL. | Given the following Python 3 function, write the documentation
def download(self, url, post=False, parameters=None, timeout=None):
# type: (str, bool, Optional[Dict], Optional[float]) -> requests.Response
"""Download url
Args:
url (str): URL to download
post (bool): Whet... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_tabular_stream(self, url, **kwargs):
# type: (str, Any) -> tabulator.Stream
"""Get Tabulator stream.
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int], List[str]]): Number of row(s) containing headers or list of headers
... | Can you write a function in Python 3 where it
gets a tabular stream of the naculiaci. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get iterator for reading rows from tabular data. | Can you generate a brief explanation for the following Python 3 code
def get_tabular_rows(self, url, dict_rows=False, **kwargs):
# type: (str, bool, Any) -> Iterator[Dict]
"""Get iterator for reading rows from tabular data. Each row is returned as a dictionary.
Args:
url (str): URL ... | You are a Python code generator, capable of creating scripts from specifications. |
def download_tabular_key_value(self, url, **kwargs):
# type: (str, Any) -> Dict
"""Download 2 column csv from url and return a dictionary of keys (first column) and values (second column)
Args:
url (str): URL to download
**kwargs:
headers (Union[int, List[int... | Implement a Python 3 function for
downloading 2 column csv from url and return a dictionary of keys and values | You are a Python code analyst, evaluating scripts for potential improvements. |
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs):
# type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict]
"""Download multicolumn csv from url and return dictionary where keys are first column and values are
dictionaries with keys from column header... | Write a Python 3 script for
downloading multicolumn csv from url and return dictionary where keys are first column and values are dictionaries with keys from column beneath headers and values from columns beneath . | You are a Python code generator, capable of creating scripts from specifications. |
Wizard to create a project - level configuration file. | Can you tell what is the following Python 3 function doing
def init(ctx, force):
if os.path.exists(PROJECT_CONFIG) and not force:
click.secho(
'An existing configuration file was found at "{}".\n'
.format(PROJECT_CONFIG),
fg='red', bold=True
)
click.secho(... | As a Python code composer, you craft elegant and concise scripts. |
Forget saved passwords for the web services. | Can you generate the documentation for the following Python 3 function
def logout(lancet, service):
if service:
services = [service]
else:
services = ['tracker', 'harvest']
for service in services:
url = lancet.config.get(service, 'url')
key = 'lancet+{}'.format(url)
... | You are a Python code generator, capable of creating scripts from specifications. |
def _services(lancet):
"""List all currently configured services."""
def get_services(config):
for s in config.sections():
if config.has_option(s, 'url'):
if config.has_option(s, 'username'):
yield s
for s in get_services(lancet.config):
click... | Implement a Python 3 function for
listing all currently configured services. | You are a Python code generator, capable of creating scripts from specifications. |
def send_request(self, endpoint='ticker', coin_name=None, **kwargs):
""": param string 'ticker', it's 'ticker' if we want info about coins,
'global' for global market's info.
: param string 'coin_name', specify the name of the coin, if None,
we'll retrieve info about all avai... | Implement a Python 3 function for
sending a request to the specified endpoint. | As a Python code composer, you craft elegant and concise scripts. |
return json response from API converted into python list
| Make a summary of the following Python 3 code
def get_response(self, data_type=None):
if not data_type:
return self.cache.get_response(r_type='ticker') or self.cache.get_response(r_type='global')
elif data_type == 'ticker':
return self.cache.get_response(r_type='ticker')
... | You are a Python code generator, capable of creating scripts from specifications. |
Convert a given language identifier into an ISO 639 Part 2 code such that it can be used as an ISO 639 Part 2 code such as eng deu or en. | Explain what the following Python 3 code does
def iso_639_alpha3(code):
code = normalize_code(code)
code = ISO3_MAP.get(code, code)
if code in ISO3_ALL:
return code | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse all the language codes in a given list into ISO 639 Part 2 codes
and optionally expand synonyms. | Given the following Python 3 function, write the documentation
def list_to_alpha3(languages, synonyms=True):
codes = set([])
for language in ensure_list(languages):
code = iso_639_alpha3(language)
if code is None:
continue
codes.add(code)
if synonyms:
code... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pull_request(ctx, base_branch, open_pr, stop_timer):
"""Create a new pull request for this issue."""
lancet = ctx.obj
review_status = lancet.config.get("tracker", "review_status")
remote_name = lancet.config.get("repository", "remote_name")
if not base_branch:
base_branch = lancet.conf... | Create a Python 3 function to
create a new pull request for this issue. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_soup(url, downloader=None, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs):
# type: (str, Download, Optional[str], Optional[str], Optional[str], Any) -> BeautifulSoup
"""
Get BeautifulSoup object for a url. Requires either global user agent to be set or appropriate us... | Can you create a Python 3 function that
gets a BeautifulSoup object for a given url. | As a Python code composer, you craft elegant and concise scripts. |
def extract_table(tabletag):
# type: (Tag) -> List[Dict]
"""
Extract HTML table as list of dictionaries
Args:
tabletag (Tag): BeautifulSoup tag
Returns:
str: Text of tag stripped of leading and trailing whitespace and newlines and with   replaced with space
"""
theadta... | Write a Python 3 function that can
extract HTML table as list of dictionaries | As a Python code analyst, you investigate and solve complex coding mysteries |
def wrap_callable(cls, uri, methods, callable_obj):
"""Wraps function-based callable_obj into a `Route` instance, else
proxies a `bottle_neck.handlers.BaseHandler` subclass instance.
Args:
uri (str): The uri relative path.
methods (tuple): A tuple of valid method string... | Create a Python 3 function to
wrap function - based callable_obj into a Route instance. | As a python code expert, you are capable of creating scripts from specifications. |
Register the route object to a bottle. Bottle app instance. | Can you generate a brief explanation for the following Python 3 code
def register_app(self, app):
app.route(self.uri, methods=self.methods)(self.callable_obj)
return self | As a Python code analyst, you investigate and solve complex coding mysteries |
def register_handler(self, callable_obj, entrypoint, methods=('GET',)):
"""Register a handler callable to a specific route.
Args:
entrypoint (str): The uri relative path.
methods (tuple): A tuple of valid method strings.
callable_obj (callable): The callable object.
... | Can you implement a function in Python 3 that
registers a handler callable to a specific route. | You are a Python code analyst, evaluating scripts for potential improvements. |
def mount(self, app=None):
"""Mounts all registered routes to a bottle.py application instance.
Args:
app (instance): A `bottle.Bottle()` application instance.
Returns:
The Router instance (for chaining purposes).
"""
for endpoint in self._routes:
... | Can you create a Python 3 function that
mounts all registered routes to a bottle. py application instance. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.