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 randdomain(self):
""" -> a randomized domain-like name """ |
return '.'.join(
rand_readable(3, 6, use=self.random, density=3)
for _ in range(self.random.randint(1, 2))
).lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_tuple(self, _list):
""" Recursively converts lists to tuples """ |
result = list()
for l in _list:
if isinstance(l, list):
result.append(tuple(self._to_tuple(l)))
else:
result.append(l)
return tuple(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None):
""" Generates random values for sequence-like objects @struct: the sequence-like struc... |
if not tree_depth:
return self._map_type()
_struct = struct()
add_struct = _struct.append if not append_callable \
else getattr(_struct, append_callable)
for x in range(size):
add_struct(self.sequence(
struct, size, tree_depth-1, appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mapping(self, struct, key_depth=1000, tree_depth=1, update_callable=None):
""" Generates random values for dict-like objects @struct: the dict-like structure... |
if not tree_depth:
return self._map_type()
_struct = struct()
add_struct = _struct.update if not update_callable \
else getattr(_struct, update_callable)
for x in range(key_depth):
add_struct({
self.randstr: self.mapping(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_numeric_sequence(self, _sequence, separator="."):
""" Length of the highest index in chars = justification size """ |
if not _sequence:
return colorize(_sequence, "purple")
_sequence = _sequence if _sequence is not None else self.obj
minus = (2 if self._depth > 0 else 0)
just_size = len(str(len(_sequence)))
out = []
add_out = out.append
for i, item in enumerate(_sequ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def objname(self, obj=None):
""" Formats object names in a pretty fashion """ |
obj = obj or self.obj
_objname = self.pretty_objname(obj, color=None)
_objname = "'{}'".format(colorize(_objname, "blue"))
return _objname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_obj(self, item=None):
""" Determines the type of the object and maps it to the correct formatter """ |
# Order here matters, odd behavior with tuples
if item is None:
return getattr(self, 'number')(item)
elif isinstance(item, self.str_):
#: String
return item + " "
elif isinstance(item, bytes):
#: Bytes
return getattr(self, 'byt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretty_objname(self, obj=None, maxlen=50, color="boldcyan"):
""" Pretty prints object name @obj: the object whose name you want to pretty print @maxlen: #int... |
parent_name = lambda_sub("", get_parent_name(obj) or "")
objname = get_obj_name(obj)
if color:
objname += colorize("<{}>".format(parent_name), color, close=False)
else:
objname += "<{}>".format(parent_name)
objname = objname if len(objname) < maxlen else ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_message(self, flag_message=None, color=None, padding=None, reverse=False):
""" Outputs the message to the terminal """ |
if flag_message:
flag_message = stdout_encode(flag(flag_message,
color=color if self.pretty else None,
show=False))
if not reverse:
print(padd(flag_message, padding),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Starts the timer """ |
if not self._start:
self._first_start = time.perf_counter()
self._start = self._first_start
else:
self._start = time.perf_counter() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pct_diff(self, best, other):
""" Calculates and colorizes the percent difference between @best and @other """ |
return colorize("{}%".format(
round(((best-other)/best)*100, 2)).rjust(10), "red") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def async_lru(size=100):
""" An LRU cache for asyncio coroutines in Python 3.5 .. @async_lru(1024) async def slow_coroutine(*args, **kwargs):
return await some_... |
cache = collections.OrderedDict()
def decorator(fn):
@wraps(fn)
@asyncio.coroutine
def memoizer(*args, **kwargs):
key = str((args, kwargs))
try:
result = cache.pop(key)
cache[key] = result
except KeyError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(msg, *args, **kw):
# type: (str, *Any, **Any) -> None """ Print sys message to stdout. System messages should inform about the flow of the script. This ... |
if len(args) or len(kw):
msg = msg.format(*args, **kw)
shell.cprint('-- <32>{}<0>'.format(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 err(msg, *args, **kw):
# type: (str, *Any, **Any) -> None """ Per step status messages Use this locally in a command definition to highlight more important i... |
if len(args) or len(kw):
msg = msg.format(*args, **kw)
shell.cprint('-- <31>{}<0>'.format(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 current_branch():
# type: () -> BranchDetails """ Return the BranchDetails for the current branch. Return: BranchDetails: The details of the current branch. ... |
cmd = 'git symbolic-ref --short HEAD'
branch_name = shell.run(
cmd,
capture=True,
never_pretend=True
).stdout.strip()
return BranchDetails.parse(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 commit_branches(sha1):
# type: (str) -> List[str] """ Get the name of the branches that this commit belongs to. """ |
cmd = 'git branch --contains {}'.format(sha1)
return shell.run(
cmd,
capture=True,
never_pretend=True
).stdout.strip().split() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_base_branch():
# type: (str) -> Optional[str, None] """ Try to guess the base branch for the current branch. Do not trust this guess. git makes it pret... |
my_branch = current_branch(refresh=True).name
curr = latest_commit()
if len(curr.branches) > 1:
# We're possibly at the beginning of the new branch (currently both
# on base and new branch).
other = [x for x in curr.branches if x != my_branch]
if len(other) == 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 commit_author(sha1=''):
# type: (str) -> Author """ Return the author of the given commit. Args: sha1 (str):
The sha1 of the commit to query. If not given, ... |
with conf.within_proj_dir():
cmd = 'git show -s --format="%an||%ae" {}'.format(sha1)
result = shell.run(
cmd,
capture=True,
never_pretend=True
).stdout
name, email = result.split('||')
return Author(name, email) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unstaged():
# type: () -> List[str] """ Return a list of unstaged files in the project repository. Returns: list[str]: The list of files not tracked by proje... |
with conf.within_proj_dir():
status = shell.run(
'git status --porcelain',
capture=True,
never_pretend=True
).stdout
results = []
for file_status in status.split(os.linesep):
if file_status.strip() and file_status[0] == ' ':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ignore():
# type: () -> List[str] """ Return a list of patterns in the project .gitignore Returns: list[str]: List of patterns set to be ignored by git. """ |
def parse_line(line): # pylint: disable=missing-docstring
# Decode if necessary
if not isinstance(line, string_types):
line = line.decode('utf-8')
# Strip comment
line = line.split('#', 1)[0].strip()
return line
ignore_files = [
conf.proj_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 branches():
# type: () -> List[str] """ Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. """ |
out = shell.run(
'git branch',
capture=True,
never_pretend=True
).stdout.strip()
return [x.strip('* \t\n') for x in out.splitlines()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag(name, message, author=None):
# type: (str, str, Author, bool) -> None """ Tag the current commit. Args: name (str):
The tag name. message (str):
The ta... |
cmd = (
'git -c "user.name={author.name}" -c "user.email={author.email}" '
'tag -a "{name}" -m "{message}"'
).format(
author=author or latest_commit().author,
name=name,
message=message.replace('"', '\\"').replace('`', '\\`'),
)
shell.run(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 config():
# type: () -> dict[str, Any] """ Return the current git configuration. Returns: dict[str, Any]: The current git config taken from ``git config --li... |
out = shell.run(
'git config --list',
capture=True,
never_pretend=True
).stdout.strip()
result = {}
for line in out.splitlines():
name, value = line.split('=', 1)
result[name.strip()] = value.strip()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tags():
# type: () -> List[str] """ Returns all tags in the repo. Returns: list[str]: List of all tags in the repo, sorted as versions. All tags returned by ... |
return shell.run(
'git tag --sort=v:refname',
capture=True,
never_pretend=True
).stdout.strip().splitlines() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_branch(branch_name):
# type: (str) -> bool """ Verify if the given branch exists. Args: branch_name (str):
The name of the branch to check. Returns: ... |
try:
shell.run(
'git rev-parse --verify {}'.format(branch_name),
never_pretend=True
)
return True
except IOError:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protected_branches():
# type: () -> list[str] """ Return branches protected by deletion. By default those are master and devel branches as configured in pelc... |
master = conf.get('git.master_branch', 'master')
develop = conf.get('git.devel_branch', 'develop')
return conf.get('git.protected_branches', (master, develop)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def branches(self):
# type: () -> List[str] """ List of all branches this commit is a part of. """ |
if self._branches is None:
cmd = 'git branch --contains {}'.format(self.sha1)
out = shell.run(
cmd,
capture=True,
never_pretend=True
).stdout.strip()
self._branches = [x.strip('* \t\n') for x in out.splitlines()]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parents(self):
# type: () -> List[CommitDetails] """ Parents of the this commit. """ |
if self._parents is None:
self._parents = [CommitDetails.get(x) for x in self.parents_sha1]
return self._parents |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def number(self):
# type: () -> int """ Return this commits number. This is the same as the total number of commits in history up until this commit. This value c... |
cmd = 'git log --oneline {}'.format(self.sha1)
out = shell.run(cmd, capture=True, never_pretend=True).stdout.strip()
return len(out.splitlines()) |
<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(cls, sha1=''):
# type: (str) -> CommitDetails """ Return details about a given commit. Args: sha1 (str):
The sha1 of the commit to query. If not given, ... |
with conf.within_proj_dir():
cmd = 'git show -s --format="%H||%an||%ae||%s||%b||%P" {}'.format(
sha1
)
result = shell.run(cmd, capture=True, never_pretend=True).stdout
sha1, name, email, title, desc, parents = result.split('||')
return Commi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_log_level(cls, log_level):
"""Sets the log level for cons3rt assets This method sets the logging level for cons3rt assets using pycons3rt. The loglevel i... |
log = logging.getLogger(cls.cls_logger + '.set_log_level')
log.info('Attempting to set the log level...')
if log_level is None:
log.info('Arg loglevel was None, log level will not be updated.')
return False
if not isinstance(log_level, basestring):
lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getattr_in(obj, name):
""" Finds an in @obj via a period-delimited string @name. @obj: (#object) @name: (#str) |.|-separated keys to search @obj in .. obj.de... |
for part in name.split('.'):
obj = getattr(obj, part)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_from(name):
""" Imports a module, class or method from string and unwraps it if wrapped by functools @name: (#str) name of the python object -> import... |
obj = name
if isinstance(name, str) and len(name):
try:
obj = locate(name)
assert obj is not None
except (AttributeError, TypeError, AssertionError, ErrorDuringImport):
try:
name = name.split(".")
attr = name[-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 unwrap_obj(obj):
""" Gets the actual object from a decorated or wrapped function @obj: (#object) the object to unwrap """ |
try:
obj = obj.fget
except (AttributeError, TypeError):
pass
try:
# Cached properties
if obj.func.__doc__ == obj.__doc__:
obj = obj.func
except AttributeError:
pass
try:
# Setter/Getters
obj = obj.getter
except AttributeError:
... |
<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():
# type: () -> None """ Load configuration from file. This will search the directory structure upwards to find the project root (directory containing ... |
with within_proj_dir():
if os.path.exists('pelconf.yaml'):
load_yaml_config('pelconf.yaml')
if os.path.exists('pelconf.py'):
load_py_config('pelconf.py') |
<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_yaml_config(conf_file):
# type: (str) -> None """ Load a YAML configuration. This will not update the configuration but replace it entirely. Args: conf_... |
global g_config
with open(conf_file) as fp:
# Initialize config
g_config = util.yaml_load(fp)
# Add src_dir to sys.paths if it's set. This is only done with YAML
# configs, py configs have to do this manually.
src_dir = get_path('src_dir', None)
if src_dir is n... |
<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_py_config(conf_file):
# type: (str) -> None """ Import configuration from a python file. This will just import the file into python. Sky is the limit. T... |
if sys.version_info >= (3, 5):
from importlib import util
spec = util.spec_from_file_location('pelconf', conf_file)
mod = util.module_from_spec(spec)
spec.loader.exec_module(mod)
elif sys.version_info >= (3, 3):
from importlib import machinery
loader = machiner... |
<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_template(filename):
# type: (str) -> str """ Load template from file. The templates are part of the package and must be included as ``package_data`` in ... |
template_file = os.path.join(PKG_DIR, 'templates', filename)
with open(template_file) as fp:
return fp.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 within_proj_dir(path='.'):
# type: (Optional[str]) -> str """ Return an absolute path to the given project relative path. :param path: Project relative path ... |
curr_dir = os.getcwd()
os.chdir(proj_path(path))
yield
os.chdir(curr_dir) |
<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(name, *default):
# type: (str, Any) -> Any """ Get config value with the given name and optional default. Args: name (str):
The name of the config value... |
global g_config
curr = g_config
for part in name.split('.'):
if part in curr:
curr = curr[part]
elif default:
return default[0]
else:
raise AttributeError("Config value '{}' does not exist".format(
name
))
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 get_path(name, *default):
# type: (str, Any) -> Any """ Get config value as path relative to the project directory. This allows easily defining the project c... |
global g_config
value = get(name, *default)
if value is None:
return None
return proj_path(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_proj_root():
# type: () -> Optional[str] """ Find the project path by going up the file tree. This will look in the current directory and upwards for t... |
proj_files = frozenset(('pelconf.py', 'pelconf.yaml'))
curr = os.getcwd()
while curr.startswith('/') and len(curr) > 1:
if proj_files & frozenset(os.listdir(curr)):
return curr
else:
curr = os.path.dirname(curr)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_bucket(self):
"""Verify the specified bucket exists This method validates that the bucket name passed in the S3Util constructor actually exists. :re... |
log = logging.getLogger(self.cls_logger + '.validate_bucket')
log.info('Attempting to get bucket: {b}'.format(b=self.bucket_name))
max_tries = 10
count = 1
while count <= max_tries:
log.info('Attempting to connect to S3 bucket %s, try %s of %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 __download_from_s3(self, key, dest_dir):
"""Private method for downloading from S3 This private helper method takes a key and the full path to the destinatio... |
log = logging.getLogger(self.cls_logger + '.__download_from_s3')
filename = key.split('/')[-1]
if filename is None:
log.error('Could not determine the filename from key: %s', key)
return None
destination = dest_dir + '/' + filename
log.info('Attempting to... |
<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_by_key(self, key, dest_dir):
"""Downloads a file by key from the specified S3 bucket This method takes the full 'key' as the arg, and attempts ... |
log = logging.getLogger(self.cls_logger + '.download_file_by_key')
if not isinstance(key, basestring):
log.error('key argument is not a string')
return None
if not isinstance(dest_dir, basestring):
log.error('dest_dir argument is not a string')
re... |
<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, regex, dest_dir):
"""Downloads a file by regex from the specified S3 bucket This method takes a regular expression as the arg, and attemp... |
log = logging.getLogger(self.cls_logger + '.download_file')
if not isinstance(regex, basestring):
log.error('regex argument is not a string')
return None
if not isinstance(dest_dir, basestring):
log.error('dest_dir argument is not a string')
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_key(self, regex):
"""Attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a mat... |
log = logging.getLogger(self.cls_logger + '.find_key')
if not isinstance(regex, basestring):
log.error('regex argument is not a string')
return None
log.info('Looking up a single S3 key based on regex: %s', regex)
matched_keys = []
for item in self.bucket... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_file(self, filepath, key):
"""Uploads a file using the passed S3 key This method uploads a file specified by the filepath to S3 using the provided S3 ... |
log = logging.getLogger(self.cls_logger + '.upload_file')
log.info('Attempting to upload file %s to S3 bucket %s as key %s...',
filepath, self.bucket_name, key)
if not isinstance(filepath, basestring):
log.error('filepath argument is not a string')
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_key(self, key_to_delete):
"""Deletes the specified key :param key_to_delete: :return: """ |
log = logging.getLogger(self.cls_logger + '.delete_key')
log.info('Attempting to delete key: {k}'.format(k=key_to_delete))
try:
self.s3client.delete_object(Bucket=self.bucket_name, Key=key_to_delete)
except ClientError:
_, ex, trace = sys.exc_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 assert_branch_type(branch_type):
# type: (str) -> None """ Print error and exit if the current branch is not of a given type. Args: branch_type (str):
The b... |
branch = git.current_branch(refresh=True)
if branch.type != branch_type:
if context.get('pretend', False):
log.info("Would assert that you're on a <33>{}/*<32> branch",
branch_type)
else:
log.err("Not on a <33>{}<31> branch!", branch_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 git_branch_delete(branch_name):
# type: (str) -> None """ Delete the given branch. Args: branch_name (str):
Name of the branch to delete. """ |
if branch_name not in git.protected_branches():
log.info("Deleting branch <33>{}", branch_name)
shell.run('git branch -d {}'.format(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 git_branch_rename(new_name):
# type: (str) -> None """ Rename the current branch Args: new_name (str):
New name for the current branch. """ |
curr_name = git.current_branch(refresh=True).name
if curr_name not in git.protected_branches():
log.info("Renaming branch from <33>{}<32> to <33>{}".format(
curr_name, new_name
))
shell.run('git branch -m {}'.format(new_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 git_checkout(branch_name, create=False):
# type: (str, bool) -> None """ Checkout or create a given branch Args: branch_name (str):
The name of the branch t... |
log.info("Checking out <33>{}".format(branch_name))
shell.run('git checkout {} {}'.format('-b' if create else '', 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 get_base_branch():
# type: () -> str """ Return the base branch for the current branch. This function will first try to guess the base branch and if it can't... |
base_branch = git.guess_base_branch()
if base_branch is None:
log.info("Can't guess the base branch, you have to pick one yourself:")
base_branch = choose_branch()
return base_branch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_branch(exclude=None):
# type: (List[str]) -> str """ Show the user a menu to pick a branch from the existing ones. Args: exclude (list[str]):
List of... |
if exclude is None:
master = conf.get('git.master_branch', 'master')
develop = conf.get('git.devel_branch', 'develop')
exclude = {master, develop}
branches = list(set(git.branches()) - exclude)
# Print the menu
for i, branch_name in enumerate(branches):
shell.cprint('<... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def autorun():
'''
Call the run method of the decorated class if the current file is the main file
'''
def wrapper(cls):
import inspect
if inspect.getmodule(cls).__name__ == "__main__":
cls().run()
return cls
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 randrange(seq):
""" Yields random values from @seq until @seq is empty """ |
seq = seq.copy()
choose = rng().choice
remove = seq.remove
for x in range(len(seq)):
y = choose(seq)
remove(y)
yield y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_ip_address(ip_address):
"""Validate the ip_address :param ip_address: (str) IP address :return: (bool) True if the ip_address is valid """ |
# Validate the IP address
log = logging.getLogger(mod_logger + '.validate_ip_address')
if not isinstance(ip_address, basestring):
log.warn('ip_address argument is not a string')
return False
# Ensure there are 3 dots
num_dots = 0
for c in ip_address:
if c == '.':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ip_addr():
"""Uses the ip addr command to enumerate IP addresses by device :return: (dict) Containing device: ip_address """ |
log = logging.getLogger(mod_logger + '.ip_addr')
log.debug('Running the ip addr command...')
ip_addr_output = {}
command = ['ip', 'addr']
try:
ip_addr_result = run_command(command, timeout_sec=20)
except CommandError:
_, ex, trace = sys.exc_info()
msg = 'There was a pro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0):
"""Configures the source IP address for a Linux interface :param sou... |
log = logging.getLogger(mod_logger + '.set_source_ip_for_interface')
if not isinstance(source_ip_address, basestring):
msg = 'arg source_ip_address must be a string'
log.error(msg)
raise TypeError(msg)
if not isinstance(desired_source_ip_address, basestring):
msg = 'arg desi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fmt(msg, *args, **kw):
# type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ |
global is_tty
if len(args) or len(kw):
msg = msg.format(*args, **kw)
opcode_subst = '\x1b[\\1m' if is_tty else ''
return re.sub(r'<(\d{1,2})>', opcode_subst, 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 cprint(msg, *args, **kw):
# type: (str, *Any, **Any) -> None """ Print colored message to stdout. """ |
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(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 send_cons3rt_agent_logs(self):
"""Send the cons3rt agent log file :return: """ |
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
if self.cons3rt_agent_log_dir is None:
log.warn('There is not CONS3RT agent log directory on this system')
return
log.debug('Searching for log files in directory: {d}'.format(d=self.cons3rt_agent_log... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_password(password):
"""Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password """ |
log = logging.getLogger(mod_logger + '.password_encoder')
log.debug('Encoding password: {p}'.format(p=password))
encoded_password = ''
for c in password:
encoded_password += encode_character(char=c)
log.debug('Encoded password: {p}'.format(p=encoded_password))
return encoded_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 encode_character(char):
"""Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character """ |
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
elif char == '%': return '%25'
elif char == '&': return '%26'
elif char == '\'': return '%27'
elif char == '(': return '%28'
elif char == ')': return '%29'
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 search_tags_as_filters(tags):
"""Get different tags as dicts ready to use as dropdown lists.""" |
# set dicts
actions = {}
contacts = {}
formats = {}
inspire = {}
keywords = {}
licenses = {}
md_types = dict()
owners = defaultdict(str)
srs = {}
unused = {}
# 0/1 values
compliance = 0
type_dataset = 0
# parsing tags
print(len(tags.keys()))
i = 0
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot.""" |
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 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 image(request, data):
""" Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data ... |
# Get image width, height, padding, and format from GET parameters, or
# fall-back to default values from settings.
try:
width = int(request.GET.get("w", PYDENTICON_WIDTH))
except ValueError:
raise SuspiciousOperation("Identicon width must be a positive integer.")
try:
heig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename(name):
# type: (str) -> None """ Give the currently developed hotfix a new name. """ |
from peltak.extra.gitflow import logic
if name is None:
name = click.prompt('Hotfix name')
logic.hotfix.rename(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 get(self, name, *default):
# type: (str, Any) -> Any """ Get context value with the given name and optional default. Args: name (str):
The name of the conte... |
curr = self.values
for part in name.split('.'):
if part in curr:
curr = curr[part]
elif default:
return default[0]
else:
fmt = "Context value '{}' does not exist:\n{}"
raise AttributeError(fmt.format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, name, value):
""" Set context value. Args: name (str):
The name of the context value to change. value (Any):
The new value for the selected conte... |
curr = self.values
parts = name.split('.')
for i, part in enumerate(parts[:-1]):
try:
curr = curr.setdefault(part, {})
except AttributeError:
raise InvalidPath('.'.join(parts[:i + 1]))
try:
curr[parts[-1]] = value
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alias_exists(alias, keystore_path=None, keystore_password='changeit'):
"""Checks if an alias already exists in a keystore :param alias: :param keystore_path:... |
log = logging.getLogger(mod_logger + '.alias_exists')
if not isinstance(alias, basestring):
msg = 'alias arg must be a string'
log.error(msg)
raise OSError(msg)
# Ensure JAVA_HOME is set
log.debug('Determining JAVA_HOME...')
try:
java_home = os.environ['JAVA_HOME']
... |
<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(self, query: Query, entity: type) -> Tuple[Query, Any]: """Define the filter function that every node must to implement. :param query: The sqlalchemy q... |
raise NotImplementedError('You must implement this.') |
<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_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]: """Transform the list of relation to list of cl... |
relations_list, last_relation = [], related_model
for relation in relations:
relationship = getattr(last_relation, relation, None)
if relationship is None:
return (None, None)
last_relation = relationship.mapper.class_
relations_list.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query: """Method to make the join when relation is found. :param query: The sqlalchemy ... |
joined_query = query
# Create the list of already joined entities
joined_tables = [mapper.class_ for mapper in query._join_entities]
if join_models:
for j_model in join_models:
if not j_model in joined_tables:
# /!\ join return a new query... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_sms(phone: str, message: str, sender: str='', **kw):
""" Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone num... |
if not hasattr(settings, 'SMS_TOKEN'):
raise Exception('Invalid configuration: settings.SMS_TOKEN missing')
if not sender:
sender = settings.SMS_SENDER_NAME
if not sender:
raise Exception('Invalid configuration: settings.SMS_SENDER_NAME missing')
headers = {
'Content-Typ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _meta_get_resource_sync(md_uuid):
"""Just a meta func to get execution time""" |
isogeo.resource(id_resource=md_uuid)
elapsed = default_timer() - START_TIME
time_completed_at = "{:5.2f}s".format(elapsed)
print("{0:<30} {1:>20}".format(md_uuid, time_completed_at))
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 setup(self, app):
'''
Setup properties from parent app on the command
'''
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = sel... |
<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_first_builder_window(builder):
"""Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit na... |
for obj in builder.get_objects():
if isinstance(obj, Gtk.Window):
# first window
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_slave(self, slave, container_name="widget"):
"""Add a slave delegate """ |
cont = getattr(self, container_name, None)
if cont is None:
raise AttributeError(
'Container name must be a member of the delegate')
cont.add(slave.widget)
self.slaves.append(slave)
return slave |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round_sig(x, sig):
"""Round the number to the specified number of significant figures""" |
return round(x, sig - int(floor(log10(abs(x)))) - 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 open_file(filename, as_text=False):
"""Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's open... |
if filename.lower().endswith('.gz'):
if as_text:
return gzip.open(filename, 'rt')
else:
return gzip.open(filename, 'rb')
else:
if as_text:
return open(filename, 'rt')
else:
return open(filename, 'rb') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metad... |
meta = {}
props = {}
# TODO add created property - how to handle date formats?
if datasetMetaProps:
props.update(datasetMetaProps)
if fieldMetaProps:
meta["fieldMetaProps"] = fieldMetaProps
if len(props) > 0:
meta["properties"] = props
if valueClassMappings:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_metrics(baseName, values):
"""Write the metrics data :param baseName: The base name of the output files. e.g. extensions will be appended to this base ... |
m = open(baseName + '_metrics.txt', 'w')
for key in values:
m.write(key + '=' + str(values[key]) + "\n")
m.flush()
m.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 generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: M... |
m = {"uuid": str(uuid.uuid4()), "source": source, "format": format}
if values:
m["values"] = values
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_nexus(query_url, timeout_sec, basic_auth=None):
"""Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query time... |
log = logging.getLogger(mod_logger + '.query_nexus')
# Attempt to query Nexus
retry_sec = 5
max_retries = 6
try_num = 1
query_success = False
nexus_response = None
while try_num <= max_retries:
if query_success:
break
log.debug('Attempt # {n} of {m} to query... |
<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():
"""Handles calling this module as a script :return: None """ |
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
parser.add_argument('-g', '--groupId', help='Group ID', required=True)
parser.... |
<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_doc(additional_doc=False, field_prefix='$', field_suffix=':', indent=4):
"""Return a formated string containing documentation about the audio fields. """ |
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields
field_length = get_max_field_length(f)
field_length = field_length + len(field_prefix) + len(field_suffix) + 4
description_indent = ' ' * (indent + field_length)
output = ''
for field, des... |
<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_images(self):
# type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ |
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] |
<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_tags(self, image_name):
# type: (str) -> Iterator[str] """ List all tags for the given image stored in the registry. Args: image_name (str):
The name o... |
tags_url = self.registry_url + '/v2/{}/tags/list'
r = self.get(tags_url.format(image_name), auth=self.auth)
data = r.json()
if 'tags' in data:
return reversed(sorted(data['tags']))
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 validate(asset_dir):
"""Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int) """ |
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
msg = 'Cons3rtAssetStructureError: Problem with asset validation\n{e}'.format(e=str(ex))
print('ERROR: {m}'.format(m=msg))
return 1
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(asset_dir, dest_dir):
"""Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param dest_dir: (full path to the de... |
val = validate(asset_dir=asset_dir)
if val != 0:
return 1
try:
asset_zip = make_asset_zip(asset_dir_path=asset_dir, destination_directory=dest_dir)
except AssetZipCreationError:
_, ex, trace = sys.exc_info()
msg = 'AssetZipCreationError: Problem with asset zip creation\n... |
<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_queryset(self):
""" This view should return a list of all the addresses the identity has for the supplied query parameters. Currently only supports addre... |
identity_id = self.kwargs["identity_id"]
address_type = self.kwargs["address_type"]
use_ct = "use_communicate_through" in self.request.query_params
default_only = "default" in self.request.query_params
if use_ct:
identity = Identity.objects.select_related("communicat... |
<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_api_response(self, response):
"""Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check... |
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400:
logging.error(
"{}: {} - {} - URL: {}".format(
response.status_code,
response.reason,
response.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 check_is_uuid(self, uuid_str: str):
"""Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ |
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
pass
# handle Isogeo specific UUID in XML exports
if "isogeo:metadata" in uuid_str:
uuid_str = "urn:uuid:{}".format(uuid_str.split(":... |
<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_edit_tab(self, tab: str, md_type: str):
"""Check if asked tab is part of Isogeo web form and reliable with metadata type. :param str tab: tab to check.... |
# check parameters types
if not isinstance(tab, str):
raise TypeError("'tab' expected a str value.")
else:
pass
if not isinstance(md_type, str):
raise TypeError("'md_type' expected a str value.")
else:
pass
# check paramete... |
<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_filter_specific_md(self, specific_md: list):
"""Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to ch... |
if isinstance(specific_md, list):
if len(specific_md) > 0:
# checking UUIDs and poping bad ones
for md in specific_md:
if not self.check_is_uuid(md):
specific_md.remove(md)
logging.error("Metadata UU... |
<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_filter_specific_tag(self, specific_tag: list):
"""Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check ""... |
if isinstance(specific_tag, list):
if len(specific_tag) > 0:
specific_tag = ",".join(specific_tag)
else:
specific_tag = ""
else:
raise TypeError("'specific_tag' expects a list")
return specific_tag |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version_cli(ctx, porcelain):
# type: (click.Context, bool) -> None """ Show project version. Has sub commands. For this command to work you must specify wher... |
if ctx.invoked_subcommand:
return
from peltak.core import log
from peltak.core import versioning
current = versioning.current()
if porcelain:
print(current)
else:
log.info("Version: <35>{}".format(current)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bump_version(component='patch', exact=None):
# type: (str, str) -> None """ Bump current project version without committing anything. No tags are created eit... |
from peltak.core import log
from peltak.core import versioning
old_ver, new_ver = versioning.bump(component, exact)
log.info("Project version bumped")
log.info(" old version: <35>{}".format(old_ver))
log.info(" new version: <35>{}".format(new_ver)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.