text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unique_names():
"""Generates unique sequences of bytes. """ |
characters = ("abcdefghijklmnopqrstuvwxyz"
"0123456789")
characters = [characters[i:i + 1] for i in irange(len(characters))]
rng = random.Random()
while True:
letters = [rng.choice(characters) for i in irange(10)]
yield ''.join(letters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_ssh_destination(destination):
"""Parses the SSH destination argument. """ |
match = _re_ssh.match(destination)
if not match:
raise InvalidDestination("Invalid destination: %s" % destination)
user, password, host, port = match.groups()
info = {}
if user:
info['username'] = user
else:
info['username'] = getpass.getuser()
if password:
info['password'] = password
if port:
info['port'] = int(port)
info['hostname'] = host
return info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ssh_client(self):
"""Gets an SSH client to connect with. """ |
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
return ssh |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connects via SSH. """ |
ssh = self._ssh_client()
logger.debug("Connecting with %s",
', '.join('%s=%r' % (k, v if k != "password" else "***")
for k, v in iteritems(self.destination)))
ssh.connect(**self.destination)
logger.debug("Connected to %s", self.destination['hostname'])
self._ssh = ssh |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_client(self):
"""Gets the SSH client. This will check that the connection is still alive first, and reconnect if necessary. """ |
if self._ssh is None:
self._connect()
return self._ssh
else:
try:
chan = self._ssh.get_transport().open_session()
except (socket.error, paramiko.SSHException):
logger.warning("Lost connection, reconnecting...")
self._ssh.close()
self._connect()
else:
chan.close()
return self._ssh |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call(self, cmd, get_output):
"""Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned. """ |
server_err = self.server_logger()
chan = self.get_client().get_transport().open_session()
try:
logger.debug("Invoking %r%s",
cmd, " (stdout)" if get_output else "")
chan.exec_command('/bin/sh -c %s' % shell_escape(cmd))
output = b''
while True:
r, w, e = select.select([chan], [], [])
if chan not in r:
continue # pragma: no cover
recvd = False
while chan.recv_stderr_ready():
data = chan.recv_stderr(1024)
server_err.append(data)
recvd = True
while chan.recv_ready():
data = chan.recv(1024)
if get_output:
output += data
recvd = True
if not recvd and chan.exit_status_ready():
break
output = output.rstrip(b'\r\n')
return chan.recv_exit_status(), output
finally:
server_err.done()
chan.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_call(self, cmd):
"""Calls a command through SSH. """ |
ret, _ = self._call(cmd, False)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_output(self, cmd):
"""Calls a command through SSH and returns its output. """ |
ret, output = self._call(cmd, True)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret)
logger.debug("Output: %r", output)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_queue(self, queue, depth=0, links=None):
"""Finds the location of tej's queue directory on the server. The `queue` set when constructing this `RemoteQueue` might be relative to the home directory and might contain ``~user`` placeholders. Also, each queue may in fact be a link to another path (a file containing the string ``tejdir:``, a space, and a new pathname, relative to this link's location). """ |
if depth == 0:
logger.debug("resolve_queue(%s)", queue)
answer = self.check_output(
'if [ -d %(queue)s ]; then '
' cd %(queue)s; echo "dir"; cat version; pwd; '
'elif [ -f %(queue)s ]; then '
' cat %(queue)s; '
'else '
' echo no; '
'fi' % {
'queue': escape_queue(queue)})
if answer == b'no':
if depth > 0:
logger.debug("Broken link at depth=%d", depth)
else:
logger.debug("Path doesn't exist")
return None, depth
elif answer.startswith(b'dir\n'):
version, runtime, path = answer[4:].split(b'\n', 2)
try:
version = tuple(int(e)
for e in version.decode('ascii', 'ignore')
.split('.'))
except ValueError:
version = 0, 0
if version[:2] != self.PROTOCOL_VERSION:
raise QueueExists(
msg="Queue exists and is using incompatible protocol "
"version %s" % '.'.join('%s' % e for e in version))
path = PosixPath(path)
runtime = runtime.decode('ascii', 'replace')
if self.need_runtime is not None:
if (self.need_runtime is not None and
runtime not in self.need_runtime):
raise QueueExists(
msg="Queue exists and is using explicitely disallowed "
"runtime %s" % runtime)
logger.debug("Found directory at %s, depth=%d, runtime=%s",
path, depth, runtime)
return path, depth
elif answer.startswith(b'tejdir: '):
new = queue.parent / answer[8:]
logger.debug("Found link to %s, recursing", new)
if links is not None:
links.append(queue)
return self._resolve_queue(new, depth + 1)
else: # pragma: no cover
logger.debug("Server returned %r", answer)
raise RemoteCommandFailure(msg="Queue resolution command failed "
"in unexpected way") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_queue(self):
"""Gets the actual location of the queue, or None. """ |
if self._queue is None:
self._links = []
queue, depth = self._resolve_queue(self.queue, links=self._links)
if queue is None and depth > 0:
raise QueueLinkBroken
self._queue = queue
return self._queue |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self, links=None, force=False, only_links=False):
"""Installs the runtime at the target location. This will not replace an existing installation, unless `force` is True. After installation, creates links to this installation at the specified locations. """ |
if not links:
links = []
if only_links:
logger.info("Only creating links")
for link in links:
self.check_call('echo "tejdir:" %(queue)s > %(link)s' % {
'queue': escape_queue(self.queue),
'link': escape_queue(link)})
return
queue, depth = self._resolve_queue(self.queue)
if queue is not None or depth > 0:
if force:
if queue is None:
logger.info("Replacing broken link")
elif depth > 0:
logger.info("Replacing link to %s...", queue)
else:
logger.info("Replacing existing queue...")
self.check_call('rm -Rf %s' % escape_queue(self.queue))
else:
if queue is not None and depth > 0:
raise QueueExists("Queue already exists (links to %s)\n"
"Use --force to replace" % queue)
elif depth > 0:
raise QueueExists("Broken link exists\n"
"Use --force to replace")
else:
raise QueueExists("Queue already exists\n"
"Use --force to replace")
queue = self._setup()
for link in links:
self.check_call('echo "tejdir:" %(queue)s > %(link)s' % {
'queue': escape_queue(queue),
'link': escape_queue(link)}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup(self):
"""Actually installs the runtime. """ |
# Expands ~user in queue
if self.queue.path[0:1] == b'/':
queue = self.queue
else:
if self.queue.path[0:1] == b'~':
output = self.check_output('echo %s' %
escape_queue(self.queue))
queue = PosixPath(output.rstrip(b'\r\n'))
else:
output = self.check_output('pwd')
queue = PosixPath(output.rstrip(b'\r\n')) / self.queue
logger.debug("Resolved to %s", queue)
# Select runtime
if not self.setup_runtime:
# Autoselect
if self._call('which qsub', False)[0] == 0:
logger.debug("qsub is available, using runtime 'pbs'")
runtime = 'pbs'
else:
logger.debug("qsub not found, using runtime 'default'")
runtime = 'default'
else:
runtime = self.setup_runtime
if self.need_runtime is not None and runtime not in self.need_runtime:
raise ValueError("About to setup runtime %s but that wouldn't "
"match explicitely allowed runtimes" % runtime)
logger.info("Installing runtime %s%s at %s",
runtime,
"" if self.setup_runtime else " (auto)",
self.queue)
# Uploads runtime
scp_client = self.get_scp_client()
filename = pkg_resources.resource_filename('tej',
'remotes/%s' % runtime)
scp_client.put(filename, str(queue), recursive=True)
logger.debug("Files uploaded")
# Runs post-setup script
self.check_call('/bin/sh %s' % shell_escape(queue / 'commands/setup'))
logger.debug("Post-setup script done")
self._queue = queue
return queue |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit(self, job_id, directory, script=None):
"""Submits a job to the queue. If the runtime is not there, it will be installed. If it is a broken chain of links, error. """ |
if job_id is None:
job_id = '%s_%s_%s' % (Path(directory).unicodename,
self.destination['username'],
make_unique_name())
else:
check_jobid(job_id)
queue = self._get_queue()
if queue is None:
queue = self._setup()
if script is None:
script = 'start.sh'
# Create directory
ret, target = self._call('%s %s' % (
shell_escape(queue / 'commands/new_job'),
job_id),
True)
if ret == 4:
raise JobAlreadyExists
elif ret != 0:
raise JobNotFound("Couldn't create job")
target = PosixPath(target)
logger.debug("Server created directory %s", target)
# Upload to directory
try:
scp_client = self.get_scp_client()
scp_client.put(str(Path(directory)),
str(target),
recursive=True)
except BaseException as e:
try:
self.delete(job_id)
except BaseException:
raise e
raise
logger.debug("Files uploaded")
# Submit job
self.check_call('%s %s %s %s' % (
shell_escape(queue / 'commands/submit'),
job_id, shell_escape(target),
shell_escape(script)))
logger.info("Submitted job %s", job_id)
return job_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self, job_id):
"""Gets the status of a previously-submitted job. """ |
check_jobid(job_id)
queue = self._get_queue()
if queue is None:
raise QueueDoesntExist
ret, output = self._call('%s %s' % (
shell_escape(queue / 'commands/status'),
job_id),
True)
if ret == 0:
directory, result = output.splitlines()
result = result.decode('utf-8')
return RemoteQueue.JOB_DONE, PosixPath(directory), result
elif ret == 2:
directory = output.splitlines()[0]
return RemoteQueue.JOB_RUNNING, PosixPath(directory), None
elif ret == 3:
raise JobNotFound
else:
raise RemoteCommandFailure(command="commands/status",
ret=ret) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, job_id, files, **kwargs):
"""Downloads files from server. """ |
check_jobid(job_id)
if not files:
return
if isinstance(files, string_types):
files = [files]
directory = False
recursive = kwargs.pop('recursive', True)
if 'destination' in kwargs and 'directory' in kwargs:
raise TypeError("Only use one of 'destination' or 'directory'")
elif 'destination' in kwargs:
destination = Path(kwargs.pop('destination'))
if len(files) != 1:
raise ValueError("'destination' specified but multiple files "
"given; did you mean to use 'directory'?")
elif 'directory' in kwargs:
destination = Path(kwargs.pop('directory'))
directory = True
if kwargs:
raise TypeError("Got unexpected keyword arguments")
# Might raise JobNotFound
status, target, result = self.status(job_id)
scp_client = self.get_scp_client()
for filename in files:
logger.info("Downloading %s", target / filename)
if directory:
scp_client.get(str(target / filename),
str(destination / filename),
recursive=recursive)
else:
scp_client.get(str(target / filename),
str(destination),
recursive=recursive) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(self, job_id):
"""Kills a job on the server. """ |
check_jobid(job_id)
queue = self._get_queue()
if queue is None:
raise QueueDoesntExist
ret, output = self._call('%s %s' % (
shell_escape(queue / 'commands/kill'),
job_id),
False)
if ret == 3:
raise JobNotFound
elif ret != 0:
raise RemoteCommandFailure(command='commands/kill',
ret=ret) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self):
"""Lists the jobs on the server. """ |
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 line in output.splitlines():
line = line.decode('utf-8')
if line.startswith(' '):
key, value = line[4:].split(': ', 1)
info[key] = value
else:
if job_id is not None:
yield job_id, info
job_id = line
info = {}
if job_id is not None:
yield job_id, info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_substitution(*substitutions):
""" Take a sequence of pairs specifying substitutions, and create a function that performs those substitutions. 'baz' """ |
substitutions = itertools.starmap(substitution, substitutions)
# compose function applies last function first, so reverse the
# substitutions to get the expected order.
substitutions = reversed(tuple(substitutions))
return compose(*substitutions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_html_strip(s):
r""" Remove HTML from the string `s`. '' A stormy day in paradise Somebody tell the truth. What about multiple lines? """ |
html_stripper = re.compile('(<!--.*?-->)|(<[^>]*>)|([^<]+)', re.DOTALL)
texts = (
match.group(3) or ''
for match
in html_stripper.finditer(s)
)
return ''.join(texts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_prefix(text, prefix):
""" Remove the prefix from the text if it exists. 'performance' 'something special' """ |
null, prefix, rest = text.rpartition(prefix)
return rest |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_suffix(text, suffix):
""" Remove the suffix from the text if it exists. 'name' 'something special' """ |
rest, suffix, null = text.partition(suffix)
return rest |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_graph(self, ctx, bundle, extensions, caller=None):
""" Run a graph and render the tag contents for each output """ |
request = ctx.get('request')
if request is None:
request = get_current_request()
if ':' in bundle:
config_name, bundle = bundle.split(':')
else:
config_name = 'DEFAULT'
webpack = request.webpack(config_name)
assets = (caller(a) for a in webpack.get_bundle(bundle, extensions))
return ''.join(assets) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.lower() == project.lower():
break
else:
ts.abort(
'Project "{}" not found (using {}-based lookup)',
project,
method,
)
# Load the configuration
config = load_config(os.path.join(project_path, LOCAL_CONFIG))
# cd to the project directory
lancet.defer_to_shell("cd", project_path)
# Activate virtualenv
venv = config.get("lancet", "virtualenv", fallback=None)
if venv:
venv_path = os.path.join(project_path, os.path.expanduser(venv))
activate_script = os.path.join(venv_path, "bin", "activate")
lancet.defer_to_shell("source", activate_script)
else:
if "VIRTUAL_ENV" in os.environ:
lancet.defer_to_shell("deactivate") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def workon(ctx, issue_id, new, base_branch):
""" Start work on a given issue. This command retrieves the issue from the issue tracker, creates and checks out a new aptly-named branch, puts the issue in the configured active, status, assigns it to you and starts a correctly linked Harvest timer. If a branch with the same name as the one to be created already exists, it is checked out instead. Variations in the branch name occuring after the issue ID are accounted for and the branch renamed to match the new issue summary. If the `default_project` directive is correctly configured, it is enough to give the issue ID (instead of the full project prefix + issue ID). """ |
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(
"Provide either an issue ID or the --new flag, but not both."
)
if new:
# Create a new issue
summary = click.prompt("Issue summary")
issue = create_issue(
lancet, summary=summary, add_to_active_sprint=True
)
else:
issue = get_issue(lancet, issue_id)
username = lancet.tracker.whoami()
active_status = lancet.config.get("tracker", "active_status")
if not base_branch:
base_branch = lancet.config.get("repository", "base_branch")
# Get the working branch
branch = get_branch(lancet, issue, base_branch)
# Make sure the issue is in a correct status
transition = get_transition(ctx, lancet, issue, active_status)
# Make sure the issue is assigned to us
assign_issue(lancet, issue, username, active_status)
# Activate environment
set_issue_status(lancet, issue, active_status, transition)
with taskstatus("Checking out working branch") as ts:
lancet.repo.checkout(branch.name)
ts.ok('Checked out working branch based on "{}"'.format(base_branch))
with taskstatus("Starting harvest timer") as ts:
lancet.timer.start(issue)
ts.ok("Started harvest timer") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time(lancet, issue):
""" Start an Harvest timer for the given issue. This command takes care of linking the timer with the issue tracker page for the given issue. If the issue is not passed to command it's taken from currently active branch. """ |
issue = get_issue(lancet, issue)
with taskstatus("Starting harvest timer") as ts:
lancet.timer.start(issue)
ts.ok("Started harvest timer") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(ctx):
""" Pause work on the current issue. This command puts the issue in the configured paused status and stops the current Harvest timer. """ |
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, issue, paused_status)
# Activate environment
set_issue_status(lancet, issue, paused_status, transition)
with taskstatus("Pausing harvest timer") as ts:
lancet.timer.pause()
ts.ok("Harvest timer paused") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resume(ctx):
""" Resume work on the currently active issue. The issue is retrieved from the currently active branch name. """ |
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 = get_transition(ctx, lancet, issue, active_status)
# Make sure the issue is assigned to us
assign_issue(lancet, issue, username, active_status)
# Activate environment
set_issue_status(lancet, issue, active_status, transition)
with taskstatus("Resuming harvest timer") as ts:
lancet.timer.start(issue)
ts.ok("Resumed harvest timer") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh(lancet, print_cmd, environment):
""" SSH into the given environment, based on the dploi configuration. """ |
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]
host = '{}@{}'.format(config['user'], config['hosts'][0])
cmd = ['ssh', '-p', str(config.get('port', 22)), host]
if print_cmd:
click.echo(' '.join(quote(s) for s in cmd))
else:
lancet.defer_to_shell(*cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _commands(ctx):
"""Prints a list of commands for shell completion hooks.""" |
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 = cmd.short_help or ""
click.echo("{}:{}".format(subcommand, help)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _arguments(ctx, command_name=None):
"""Prints a list of arguments for shell completion hooks. If a command name is given, returns the arguments for that subcommand. The command name has to refer to a command; aliases are not supported. """ |
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", "argument"]
all_params = sorted(
command.get_params(ctx), key=lambda p: types.index(p.param_type_name)
)
def get_name(param):
return max(param.opts, key=len)
for param in all_params:
if param.param_type_name == "option":
option = get_name(param)
same_dest = [
get_name(p) for p in all_params if p.name == param.name
]
if same_dest:
option = "({})".format(" ".join(same_dest)) + option
if param.help:
option += "[{}]".format(param.help or "")
if not param.is_flag:
option += "=:( )"
click.echo(option)
elif param.param_type_name == "argument":
option = get_name(param)
click.echo(":{}".format(option)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 argument.",
fg="red",
)
ctx.exit(-1)
base = os.path.abspath(os.path.dirname(__file__))
autocomplete = os.path.join(base, "autocomplete", "{}.sh".format(shell))
if not os.path.exists(autocomplete):
click.secho(
"Autocompletion for your shell ({}) is currently not "
"supported.",
fg="red",
)
ctx.exit(-1)
with open(autocomplete) as fh:
click.echo(fh.read()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
if sys.version_info[:2] >= (3, 2):
six.raise_from(exc_type(message), exc)
else:
six.reraise(exc_type, '%s - %s' % (message, exc), sys.exc_info()[2]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 as {"":tracer_obj} or {"192.168.0.1:5555":tracer_obj1, "192.168.0.2:5555":tracer_obj2}
@param proj_info: dict type of test case. use like: self.proj_info["module"], self.proj_info["name"]
yaml case like:
- project:
name: xxx
module: xxxx
dict case like:
{"project": {"name": xxx, "module": xxxx}}
'''
self.parser = parser
self.tracers = tracers
self.proj_info = projinfo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
try:
executable_file_path = os.path.dirname(os.path.abspath(inspect.stack()[-1][1]))
except:
executable_file_path = os.path.dirname(sys.path[0])
finally:
proj_path = executable_file_path
p = os.path.join(proj_path,subject)
proj_conf = {
"sys_coding" : sysencoding,
"debug" : debug,
"module_name" : os.path.splitext(os.path.basename(subject))[0],
"cfg_file" : os.path.join(p,"config.ini"),
"path" : {"root" : p,
"case" : os.path.join(p,"testcase"),
"data" : os.path.join(p,"data"),
"buffer" : os.path.join(p,"buffer"),
"resource" : os.path.join(p,"resource"),
"tools" : os.path.join(p,"tools"),
"rst" : os.path.join(p,"result"),
"rst_log" : os.path.join(p,"result","testcase"),
"rst_shot" : os.path.join(p,"result","screenshots"),
},
}
[FileSystemUtils.mkdirs(v) for v in proj_conf["path"].values()]
sys.path.append(p) if os.path.isdir(p) else ""
return proj_conf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
pass
time.sleep(1)
if time.time() > end_time:
break
raise Exception(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
return file_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
imported_module = imp.load_source('module_name', file_path)
else:
raise RuntimeError("Neither Python 3 nor Python 2.")
return imported_module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_variable
module_functions_dict = dict(filter(filter_type, vars(module).items()))
return module_functions_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_conf_item('C:/Users/RockFeng/Desktop/s/preference.py','function','test_func')
""" |
dir_path = os.path.dirname(os.path.abspath(start_path))
target_file = os.path.join(dir_path, "preference.py")
if os.path.isfile(target_file):
imported_module = ModuleUtils.get_imported_module_from_file(target_file)
items_dict = ModuleUtils.filter_module(imported_module, item_type)
if item_name in items_dict:
return items_dict[item_name]
else:
return ModuleUtils.search_conf_item(dir_path, item_type, item_name)
if dir_path == start_path:
# system root path
err_msg = "'{}' not found in recursive upward path!".format(item_name)
if item_type == "function":
raise p_exception.FunctionNotFound(err_msg)
else:
raise p_exception.VariableNotFound(err_msg)
return ModuleUtils.search_conf_item(dir_path, item_type, item_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
})
""" |
ordered_dict = OrderedDict()
for map_dict in map_list:
ordered_dict.update(map_dict)
return ordered_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell_escape(s):
r"""Given bl"a, returns "bl\\"a". """ |
if isinstance(s, PosixPath):
s = unicode_(s)
elif isinstance(s, bytes):
s = s.decode('utf-8')
if not s or any(c not in safe_shell_chars for c in s):
return '"%s"' % (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('`', '\\`')
.replace('$', '\\$'))
else:
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_long_description():
""" Retrieve the long description from DESCRIPTION.rst """ |
here = os.path.abspath(os.path.dirname(__file__))
with copen(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as description:
return description.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(nested_list: list) -> list: """Flattens a list, ignore all the lambdas.""" |
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),
nested_list))))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_py_files(dir_name: str) -> list: """Get all .py files.""" |
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
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, log in self.logs.items():
if not log or self.parser[name].as_bool("quiet"):
continue
print("[[{0}]]".format(name))
getattr(snekchek.format, name + "_format")(log)
print("\n")
print("-" * 30)
print("Total:", total)
sys.exit(self.status_code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 linter.requires_install):
raise ModuleNotInstalled(linter.requires_install)
linter.add_output_hook(self.out_func)
linter.set_config(self.fn, self.parser[linter.name])
linter.run(self.files)
self.status_code = self.status_code or linter.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) as rcfile:
return parse_rcfile(rcfile)
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_settings(args, rc_settings):
""" Merge arguments and 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_settings.get(key)
if not settings['size']:
settings['size'] = DEFAULT_SIZE
return settings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_post(message, url, name, http_data=None, auth=None):
""" Send `message` as `name` to `url`. You can specify extra variables in `http_data` """ |
try:
import requests
except ImportError:
print('requests is required to do api post.', file=sys.stderr)
sys.exit(1)
data = {name : message}
if http_data:
for var in http_data:
key, value = var.split('=')
data[key] = value
response = requests.post(
url,
data=data,
auth=auth
)
if response.status_code != 200:
raise RuntimeError('Unable to post data') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
else:
path = os.path.expanduser(path)
with open(path, 'rb') as fh:
content = fh.read()
return content.decode(encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
response['result'] = fun(*args)
except Exception as exception:
logging.error(exception, exc_info=1)
response['error'] = str(exception)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, name, fun, description=None):
""" Register function on this service """ |
self.methods[name] = fun
self.descriptions[name] = description |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(cls, payload):
""" Parse client request """ |
try:
method, args, ref = payload
except Exception as exception:
raise RequestParseError(exception)
else:
return method, args, ref |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self):
""" Receive data from socket and process request """ |
response = None
try:
payload = self.receive()
method, args, ref = self.parse(payload)
response = self.execute(method, args, ref)
except AuthenticateError as exception:
logging.error(
'Service error while authenticating request: {}'
.format(exception), exc_info=1)
except AuthenticatorInvalidSignature as exception:
logging.error(
'Service error while authenticating request: {}'
.format(exception), exc_info=1)
except DecodeError as exception:
logging.error(
'Service error while decoding request: {}'
.format(exception), exc_info=1)
except RequestParseError as exception:
logging.error(
'Service error while parsing request: {}'
.format(exception), exc_info=1)
else:
logging.debug('Service received payload: {}'.format(payload))
if response:
self.send(response)
else:
self.send('') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_payload(cls, method, args):
""" Build the payload to be sent to a `Responder` """ |
ref = str(uuid.uuid4())
return (method, args, ref) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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']
return res['result'], res['error'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = DotDict()
assert filepath or filecontent
if not filecontent:
with io.FileIO(filepath) as handle:
filecontent = handle.read().decode('utf-8')
configs = json.loads(filecontent)
conf.update(configs.items())
return conf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
handler = CheckHandler(
file=args.config_file, out_json=args.json, files=args.files)
for style in get_stylers():
handler.run_linter(style())
for linter in get_linters():
handler.run_linter(linter())
for security in get_security():
handler.run_linter(security())
for tool in get_tools():
tool = tool()
# Only run pypi if everything else passed
if tool.name == "pypi" and handler.status_code != 0:
continue
handler.run_linter(tool)
if do_exit:
handler.exit()
return handler.status_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main() -> None: """Main entry point for console commands.""" |
parser = argparse.ArgumentParser()
parser.add_argument(
"--json",
help="output in JSON format",
action="store_true",
default=False)
parser.add_argument(
"--config-file", help="Select config file to use", default=".snekrc")
parser.add_argument(
'files',
metavar='file',
nargs='*',
default=[],
help='Files to run checks against')
parser.add_argument(
"--init", help="generate snekrc", action="store_true", default=False)
args = parser.parse_args()
run_main(args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, local_hostname=self.local_hostname,
timeout=self.timeout, source_address=self.source_address)
elif self.connection_type.lower() == 'lmtp':
self.server = smtplib.LMTP(host=self.host, port=self.port, local_hostname=self.local_hostname,
source_address=self.source_address)
else:
self.server = smtplib.SMTP(host=self.host, port=self.port, local_hostname=self.local_hostname,
timeout=self.timeout, source_address=self.source_address)
self.server.login(self.username, self.password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.session.Session: SQLAlchemy session """ |
engine = create_engine(db_url, poolclass=NullPool, echo=False)
Session = sessionmaker(bind=engine)
Base.metadata.create_all(engine)
return Session() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
result = urlsplit(db_url)
return {'database': result.path[1:], 'host': result.hostname, 'port': result.port,
'username': result.username, 'password': result.password, 'driver': result.scheme} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: database (Optional[str]):
Database name host (Optional[str]):
Host where database is located port (Union[int, str, None]):
Database port username (Optional[str]):
Username to log into database password (Optional[str]):
Password to log into database driver (str):
Database driver. Defaults to 'postgres'. Returns: db_url (str):
SQLAlchemy url """ |
strings = ['%s://' % driver]
if username:
strings.append(username)
if password:
strings.append(':%s@' % password)
else:
strings.append('@')
if host:
strings.append(host)
if port is not None:
strings.append(':%d' % int(port))
if database:
strings.append('/%s' % database)
return ''.join(strings) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]):
Host where database is located port (Union[int, str, None]):
Database port username (Optional[str]):
Username to log into database password (Optional[str]):
Password to log into database Returns: None """ |
connecting_string = 'Checking for PostgreSQL...'
if port is not None:
port = int(port)
while True:
try:
logger.info(connecting_string)
connection = psycopg2.connect(
database=database,
host=host,
port=port,
user=username,
password=password,
connect_timeout=3
)
connection.close()
logger.info('PostgreSQL is running!')
break
except psycopg2.OperationalError:
time.sleep(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dicts_filter(dicts_object, field_to_filter, value_of_filter):
"""This function gets as arguments an array of dicts through the dicts_objects parameter, then it'll return the dicts that have a value value_of_filter of the key field_to_filter. """ |
lambda_query = lambda value: value[field_to_filter] == value_of_filter
filtered_coin = filter(lambda_query, dicts_object)
selected_coins = list(filtered_coin)
#if not selected_coin: #Empty list, no coin found
# raise AttributeError('attribute %s not found' % attr)
return selected_coins |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 folder (Optional[str]):
Folder to download it to. Defaults to None (temporary folder). filename (Optional[str]):
Filename to use for downloaded file. Defaults to None (derive from the url). overwrite (bool):
Whether to overwrite existing file. Defaults to False. Returns: str: Path of downloaded file """ |
if not filename:
urlpath = urlsplit(url).path
filename = basename(urlpath)
filename, extension = splitext(filename)
if not folder:
folder = get_temp_dir()
path = join(folder, '%s%s' % (filename, extension))
if overwrite:
try:
remove(path)
except OSError:
pass
else:
count = 0
while exists(path):
count += 1
path = join(folder, '%s%d%s' % (filename, count, extension))
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 parameters """ |
request = Request('GET', url)
preparedrequest = self.session.prepare_request(request)
return preparedrequest.url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: Full url """ |
spliturl = urlsplit(url)
getparams = OrderedDict(parse_qsl(spliturl.query))
if parameters is not None:
getparams.update(parameters)
spliturl = spliturl._replace(query=urlencode(getparams))
return urlunsplit(spliturl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 parameters (Optional[Dict]):
Parameters to pass. Defaults to None. Returns: Tuple[str, Dict]: (Full url, parameters) """ |
spliturl = urlsplit(url)
getparams = OrderedDict(parse_qsl(spliturl.query))
if parameters is not None:
getparams.update(parameters)
spliturl = spliturl._replace(query='')
full_url = urlunsplit(spliturl)
return full_url, getparams |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self, url, stream=True, post=False, parameters=None, timeout=None):
# type: (str, bool, bool, Optional[Dict], Optional[float]) -> requests.Response """Setup download from provided url returning the response Args: url (str):
URL to download stream (bool):
Whether to stream download. Defaults to True. post (bool):
Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]):
Parameters to pass. Defaults to None. timeout (Optional[float]):
Timeout for connecting to URL. Defaults to None (no timeout). Returns: requests.Response: requests.Response object """ |
self.close_response()
self.response = None
try:
if post:
full_url, parameters = self.get_url_params_for_post(url, parameters)
self.response = self.session.post(full_url, data=parameters, stream=stream, timeout=timeout)
else:
self.response = self.session.get(self.get_url_for_get(url, parameters), stream=stream, timeout=timeout)
self.response.raise_for_status()
except Exception as e:
raisefrom(DownloadError, 'Setup of Streaming Download of %s failed!' % url, e)
return self.response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
md5hash = hashlib.md5()
try:
for chunk in self.response.iter_content(chunk_size=10240):
if chunk: # filter out keep-alive new chunks
md5hash.update(chunk)
return md5hash.hexdigest()
except Exception as e:
raisefrom(DownloadError, 'Download of %s failed in retrieval of stream!' % url, e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 call setup method first. Args: url (str):
URL to download filename (Optional[str]):
Filename to use for downloaded file. Defaults to None (derive from the url). folder (Optional[str]):
Folder to download it to. Defaults to None (temporary folder). overwrite (bool):
Whether to overwrite existing file. Defaults to False. Returns: str: Path of downloaded file """ |
path = self.get_path_for_url(url, folder, filename, overwrite)
f = None
try:
f = open(path, 'wb')
for chunk in self.response.iter_content(chunk_size=10240):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
return f.name
except Exception as e:
raisefrom(DownloadError, 'Download of %s failed in retrieval of stream!' % url, e)
finally:
if f:
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """Download file from url and store in provided folder or temporary folder if no folder supplied Args: url (str):
URL to download folder (Optional[str]):
Folder to download it to. Defaults to None. filename (Optional[str]):
Filename to use for downloaded file. Defaults to None (derive from the url). overwrite (bool):
Whether to overwrite existing file. Defaults to False. post (bool):
Whether to use POST instead of GET. Defaults to False. parameters (Optional[Dict]):
Parameters to pass. Defaults to None. timeout (Optional[float]):
Timeout for connecting to URL. Defaults to None (no timeout). Returns: str: Path of downloaded file """ |
self.setup(url, stream=True, post=post, parameters=parameters, timeout=timeout)
return self.stream_file(url, folder, filename, overwrite) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 file_type (Optional[str]):
Type of file. Defaults to inferring. delimiter (Optional[str]):
Delimiter used for values in each row. Defaults to inferring. Returns: tabulator.Stream: Tabulator Stream object """ |
self.close_response()
file_type = kwargs.get('file_type')
if file_type is not None:
kwargs['format'] = file_type
del kwargs['file_type']
try:
self.response = tabulator.Stream(url, **kwargs)
self.response.open()
return self.response
except TabulatorException as e:
raisefrom(DownloadError, 'Getting tabular stream for %s failed!' % url, e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 to download dict_rows (bool):
Return dict (requires headers parameter) or list for each row. Defaults to False (list). **kwargs: headers (Union[int, List[int], List[str]]):
Number of row(s) containing headers or list of headers file_type (Optional[str]):
Type of file. Defaults to inferring. delimiter (Optional[str]):
Delimiter used for values in each row. Defaults to inferring. Returns: Iterator[Union[List,Dict]]: Iterator where each row is returned as a list or dictionary. """ |
return self.get_tabular_stream(url, **kwargs).iter(keyed=dict_rows) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 headers and values from columns beneath Args: url (str):
URL to download headers (Union[int, List[int], List[str]]):
Number of row(s) containing headers or list of headers. Defaults to 1. keycolumn (int):
Number of column to be used for key. Defaults to 1. **kwargs: file_type (Optional[str]):
Type of file. Defaults to inferring. delimiter (Optional[str]):
Delimiter used for values in each row. Defaults to inferring. Returns: Dict[Dict]: Dictionary where keys are first column and values are dictionaries with keys from column headers and values from columns beneath """ |
kwargs['headers'] = headers
stream = self.get_tabular_stream(url, **kwargs)
output_dict = dict()
headers = stream.headers
key_header = headers[keycolumn - 1]
for row in stream.iter(keyed=True):
first_val = row[key_header]
output_dict[first_val] = dict()
for header in row:
if header == key_header:
continue
else:
output_dict[first_val][header] = row[header]
return output_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(ctx, force):
"""Wizard to create the user-level configuration file.""" |
if os.path.exists(USER_CONFIG) and not force:
click.secho(
'An existing configuration file was found at "{}".\n'
.format(USER_CONFIG),
fg='red', bold=True
)
click.secho(
'Please remove it before in order to run the setup wizard or use\n'
'the --force flag to overwrite it.'
)
ctx.exit(1)
click.echo('Address of the issue tracker (your JIRA instance). \n'
'Normally in the form https://<company>.atlassian.net.')
tracker_url = click.prompt('URL')
tracker_user = click.prompt('Username for {}'.format(tracker_url))
click.echo()
click.echo('Address of the time tracker (your Harvest instance). \n'
'Normally in the form https://<company>.harvestapp.com.')
timer_url = click.prompt('URL')
timer_user = click.prompt('Username for {}'.format(timer_url))
click.echo()
config = configparser.ConfigParser()
config.add_section('tracker')
config.set('tracker', 'url', tracker_url)
config.set('tracker', 'username', tracker_user)
config.add_section('harvest')
config.set('harvest', 'url', timer_url)
config.set('harvest', 'username', timer_user)
with open(USER_CONFIG, 'w') as fh:
config.write(fh)
click.secho('Configuration correctly written to "{}".'
.format(USER_CONFIG), fg='green') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(ctx, force):
"""Wizard to create a project-level configuration file.""" |
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(
'Please remove it before in order to run the setup wizard or use\n'
'the --force flag to overwrite it.'
)
ctx.exit(1)
project_key = click.prompt('Project key on the issue tracker')
base_branch = click.prompt('Integration branch', default='master')
virtualenvs = ('.venv', '.env', 'venv', 'env')
for p in virtualenvs:
if os.path.exists(os.path.join(p, 'bin', 'activate')):
venv = p
break
else:
venv = ''
venv_path = click.prompt('Path to virtual environment', default=venv)
project_id = click.prompt('Project ID on Harvest', type=int)
task_id = click.prompt('Task id on Harvest', type=int)
config = configparser.ConfigParser()
config.add_section('lancet')
config.set('lancet', 'virtualenv', venv_path)
config.add_section('tracker')
config.set('tracker', 'default_project', project_key)
config.add_section('harvest')
config.set('harvest', 'project_id', str(project_id))
config.set('harvest', 'task_id', str(task_id))
config.add_section('repository')
config.set('repository', 'base_branch', base_branch)
with open(PROJECT_CONFIG, 'w') as fh:
config.write(fh)
click.secho('\nConfiguration correctly written to "{}".'
.format(PROJECT_CONFIG), fg='green') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logout(lancet, service):
"""Forget saved passwords for the web services.""" |
if service:
services = [service]
else:
services = ['tracker', 'harvest']
for service in services:
url = lancet.config.get(service, 'url')
key = 'lancet+{}'.format(url)
username = lancet.config.get(service, 'username')
with taskstatus('Logging out from {}', url) as ts:
if keyring.get_password(key, username):
keyring.delete_password(key, username)
ts.ok('Logged out from {}', url)
else:
ts.ok('Already logged out from {}', url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.echo('{}[Logout from {}]'.format(s, lancet.config.get(s, 'url'))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iso_639_alpha3(code):
"""Convert a given language identifier into an ISO 639 Part 2 code, such as "eng" or "deu". This will accept language codes in the two- or three- letter format, and some language names. If the given string cannot be converted, ``None`` will be returned. """ |
code = normalize_code(code)
code = ISO3_MAP.get(code, code)
if code in ISO3_ALL:
return code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.config.get("repository", "base_branch")
# Get the issue
issue = get_issue(lancet)
transition = get_transition(ctx, lancet, issue, review_status)
# Get the working branch
branch = get_branch(lancet, issue, create=False)
with taskstatus("Checking pre-requisites") as ts:
if not branch:
ts.abort("No working branch found")
if lancet.tracker.whoami() not in issue.assignees:
ts.abort("Issue currently not assigned to you")
# TODO: Check mergeability
# TODO: Check remote status (PR does not already exist)
# Push to remote
with taskstatus('Pushing to "{}"', remote_name) as ts:
remote = lancet.repo.lookup_remote(remote_name)
if not remote:
ts.abort('Remote "{}" not found', remote_name)
from ..git import CredentialsCallbacks
remote.push([branch.name], callbacks=CredentialsCallbacks())
ts.ok('Pushed latest changes to "{}"', remote_name)
# Create pull request
with taskstatus("Creating pull request") as ts:
template_path = lancet.config.get("repository", "pr_template")
message = edit_template(template_path, issue=issue)
if not message:
ts.abort("You didn't provide a title for the pull request")
title, body = message.split("\n", 1)
title = title.strip()
if not title:
ts.abort("You didn't provide a title for the pull request")
try:
pr = lancet.scm_manager.create_pull_request(
branch.branch_name, base_branch, title, body.strip("\n")
)
except PullRequestAlreadyExists as e:
pr = e.pull_request
ts.ok("Pull request does already exist at {}", pr.link)
else:
ts.ok("Pull request created at {}", pr.link)
# Update issue
set_issue_status(lancet, issue, review_status, transition)
# TODO: Post to activity stream on JIRA?
# TODO: Post to Slack?
# Stop harvest timer
if stop_timer:
with taskstatus("Pausing harvest timer") as ts:
lancet.timer.pause()
ts.ok("Harvest timer paused")
# Open the pull request page in the browser if requested
if open_pr:
click.launch(pr.link) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkout(lancet, force, issue):
""" Checkout the branch for the given issue. It is an error if the branch does no exist yet. """ |
issue = get_issue(lancet, issue)
# Get the working branch
branch = get_branch(lancet, issue, create=force)
with taskstatus("Checking out working branch") as ts:
if not branch:
ts.abort("Working branch not found")
lancet.repo.checkout(branch.name)
ts.ok('Checked out "{}"', branch.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
theadtag = tabletag.find_next('thead')
headertags = theadtag.find_all('th')
if len(headertags) == 0:
headertags = theadtag.find_all('td')
headers = []
for tag in headertags:
headers.append(get_text(tag))
tbodytag = tabletag.find_next('tbody')
trtags = tbodytag.find_all('tr')
table = list()
for trtag in trtags:
row = dict()
tdtags = trtag.find_all('td')
for i, tag in enumerate(tdtags):
row[headers[i]] = get_text(tag)
table.append(row)
return table |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 strings. callable_obj (instance):
The callable object. Returns: A route instance. Raises: RouteError for invalid callable object type. """ |
if isinstance(callable_obj, HandlerMeta):
callable_obj.base_endpoint = uri
callable_obj.is_valid = True
return callable_obj
if isinstance(callable_obj, types.FunctionType):
return cls(uri=uri, methods=methods, callable_obj=callable_obj)
raise RouteError("Invalid handler type.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_app(self, app):
"""Register the route object to a `bottle.Bottle` app instance. Args: app (instance):
Returns: Route instance (for chaining purposes) """ |
app.route(self.uri, methods=self.methods)(self.callable_obj)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Returns: The Router instance (for chaining purposes). Raises: RouteError, for missing routing params or invalid callable object type. """ |
router_obj = Route.wrap_callable(
uri=entrypoint,
methods=methods,
callable_obj=callable_obj
)
if router_obj.is_valid:
self._routes.add(router_obj)
return self
raise RouteError( # pragma: no cover
"Missing params: methods: {} - entrypoint: {}".format(
methods, entrypoint
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
endpoint.register_app(app)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tolog(self,level):
""" log with different level """ |
def wrapper(msg):
if self.log_colors:
color = self.log_colors[level.upper()]
getattr(self.logger, level.lower())(coloring("- {}".format(msg), color))
else:
getattr(self.logger, level.lower())(msg)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_status(cls, status_line, msg=None):
"""Returns a class method from bottle.HTTPError.status_line attribute. Useful for patching `bottle.HTTPError` for web services. Args: status_line (str):
bottle.HTTPError.status_line text. msg: The message data for response. Returns: Class method based on status_line arg. Examples: ['Get out!'] 'Unauthorized' """ |
method = getattr(cls, status_line.lower()[4:].replace(' ', '_'))
return method(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def created(cls, data=None):
"""Shortcut API for HTTP 201 `Created` response. Args: data (object):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '201 Created'
return cls(201, data=data).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def not_modified(cls, errors=None):
"""Shortcut API for HTTP 304 `Not Modified` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '304 Not Modified'
return cls(304, None, errors).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bad_request(cls, errors=None):
"""Shortcut API for HTTP 400 `Bad Request` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '400 Bad Request'
return cls(400, errors=errors).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unauthorized(cls, errors=None):
"""Shortcut API for HTTP 401 `Unauthorized` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '401 Unauthorized'
return cls(401, errors=errors).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forbidden(cls, errors=None):
"""Shortcut API for HTTP 403 `Forbidden` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '403 Forbidden'
return cls(403, errors=errors).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def not_found(cls, errors=None):
"""Shortcut API for HTTP 404 `Not found` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '404 Not Found'
return cls(404, None, errors).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def method_not_allowed(cls, errors=None):
"""Shortcut API for HTTP 405 `Method not allowed` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '405 Method Not Allowed'
return cls(405, None, errors).to_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def not_implemented(cls, errors=None):
"""Shortcut API for HTTP 501 `Not Implemented` response. Args: errors (list):
Response key/value data. Returns: WSResponse Instance. """ |
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'application/json'
cls.response._status_line = '501 Not Implemented'
return cls(501, None, errors).to_json |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.