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 _remove_code(site):
""" Delete project files @type site: Site """ |
def handle_error(function, path, excinfo):
click.secho('Failed to remove path ({em}): {p}'.format(em=excinfo.message, p=path), err=True, fg='red')
if os.path.exists(site.root):
shutil.rmtree(site.root, onerror=handle_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 _handler(self, conn):
""" Connection handler thread. Takes care of communication with the client and running the proper task or applying a signal. """ |
incoming = self.recv(conn)
self.log(DEBUG, incoming)
try:
# E.g. ['twister', [7, 'invert'], {'guess_type': True}]
task, args, kw = self.codec.decode(incoming)
# OK, so we've received the information. Now to use it.
self.log(INFO, 'Fulfilling task %r' % task)
self.started_task()
pass_backend = False
obj = self.tasks[task]
if _is_iter(obj):
# (callable, bool)
obj, pass_backend = obj
if pass_backend:
# Have to do this, since args is a list
args = [self] + args
# Get and package the result
res = ['success', obj(*args, **kw)]
except Exception as e:
self.log(ERROR, 'Error while fullfilling task %r: %r' % (task, e))
res = ['error', e.__class__.__name__, e.args]
if self.tracebacks:
show_err()
else:
self.log(INFO, 'Finished fulfilling task %r' % task)
finally:
self.send(conn, self.codec.encode(res))
self.finished_task()
conn.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 stop_server(self):
""" Stop receiving connections, wait for all tasks to end, and then terminate the server. """ |
self.stop = True
while self.task_count:
time.sleep(END_RESP)
self.terminate = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fastqIterator(fn, verbose=False, allowNameMissmatch=False):
""" A generator function which yields FastqSequence objects read from a file or stream. This is a general function which wraps fastqIteratorSimple. In future releases, we may allow dynamic switching of which base iterator is used. :param fn: A file-like stream or a string; if this is a string, it's treated as a filename specifying the location of an input fastq file, else it's treated as a file-like object, which must have a readline() method. :param useMustableString: if True, construct sequences from lists of chars, rather than python string objects, to allow more efficient editing. Use with caution. :param verbose: if True, print messages on progress to stderr. :param debug: if True, print debugging messages to stderr. :param sanger: if True, assume quality scores are in sanger format. Otherwise, assume they're in Illumina format. :param allowNameMissmatch: don't throw error if name in sequence data and quality data parts of a read don't match. Newer version of CASVA seem to output data like this, probably to save space. """ |
it = fastqIteratorSimple(fn, verbose=verbose,
allowNameMissmatch=allowNameMissmatch)
for s in it:
yield 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 during(rrule, duration=None, timestamp=None, **kwargs):
""" Check if input timestamp is in rrule+duration period :param rrule: rrule to check :type rrule: str or dict (freq, dtstart, interval, count, wkst, until, bymonth, byminute, etc.) :param dict duration: time duration from rrule step. Ex:{'minutes': 60} :param float timestamp: timestamp to check between rrule+duration. If None, use now """ |
result = False
# if rrule is a string expression
if isinstance(rrule, string_types):
rrule_object = rrule_class.rrulestr(rrule)
else:
rrule_object = rrule_class(**rrule)
# if timestamp is None, use now
if timestamp is None:
timestamp = time()
# get now object
now = datetime.fromtimestamp(timestamp)
# get delta object
duration_delta = now if duration is None else relativedelta(**duration)
# get last date
last_date = rrule_object.before(now, inc=True)
# if a previous date exists
if last_date is not None:
next_date = last_date + duration_delta
# check if now is between last_date and next_date
result = last_date <= now <= next_date
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 _any(confs=None, **kwargs):
""" True iif at least one input condition is equivalent to True. :param confs: confs to check. :type confs: list or dict or str :param kwargs: additional task kwargs. :return: True if at least one condition is checked (compared to True, but not an strict equivalence to True). False otherwise. :rtype: bool """ |
result = False
if confs is not None:
# ensure confs is a list
if isinstance(confs, string_types) or isinstance(confs, dict):
confs = [confs]
for conf in confs:
result = run(conf, **kwargs)
if result: # leave function as soon as a result if True
break
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 _all(confs=None, **kwargs):
""" True iif all input confs are True. :param confs: confs to check. :type confs: list or dict or str :param kwargs: additional task kwargs. :return: True if all conditions are checked. False otherwise. :rtype: bool """ |
result = False
if confs is not None:
# ensure confs is a list
if isinstance(confs, string_types) or isinstance(confs, dict):
confs = [confs]
# if at least one conf exists, result is True by default
result = True
for conf in confs:
result = run(conf, **kwargs)
# stop when a result is False
if not result:
break
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 _not(condition=None, **kwargs):
""" Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ |
result = True
if condition is not None:
result = not run(condition, **kwargs)
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 condition(condition=None, statement=None, _else=None, **kwargs):
""" Run an statement if input condition is checked and return statement result. :param condition: condition to check. :type condition: str or dict :param statement: statement to process if condition is checked. :type statement: str or dict :param _else: else statement. :type _else: str or dict :param kwargs: condition and statement additional parameters. :return: statement result. """ |
result = None
checked = False
if condition is not None:
checked = run(condition, **kwargs)
if checked: # if condition is checked
if statement is not None: # process statement
result = run(statement, **kwargs)
elif _else is not None: # else process _else statement
result = run(_else, **kwargs)
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 switch( confs=None, remain=False, all_checked=False, _default=None, **kwargs ):
""" Execute first statement among conf where task result is True. If remain, process all statements conf starting from the first checked conf. :param confs: task confs to check. Each one may contain a task action at the key 'action' in conf. :type confs: str or dict or list :param bool remain: if True, execute all remaining actions after the first checked condition. :param bool all_checked: execute all statements where conditions are checked. :param _default: default task to process if others have not been checked. :type _default: str or dict :return: statement result or list of statement results if remain. :rtype: list or object """ |
# init result
result = [] if remain else None
# check if remain and one task has already been checked.
remaining = False
if confs is not None:
if isinstance(confs, string_types) or isinstance(confs, dict):
confs = [confs]
for conf in confs:
# check if task has to be checked or not
check = remaining
if not check:
# try to check current conf
check = run(conf=conf, **kwargs)
# if task is checked or remaining
if check:
if STATEMENT in conf: # if statements exist, run them
statement = conf[STATEMENT]
statement_result = run(statement, **kwargs)
# save result
if not remain: # if not remain, result is statement_result
result = statement_result
else: # else, add statement_result to result
result.append(statement_result)
# if remain
if remain:
# change of remaining status
if not remaining:
remaining = True
elif all_checked:
pass
else: # leave execution if one statement has been executed
break
# process _default statement if necessary
if _default is not None and (remaining or (not result) or all_checked):
last_result = run(_default, **kwargs)
if not remain:
result = last_result
else:
result.append(last_result)
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 error(self, message):
"""Overrides error to control printing output""" |
if self._debug:
import pdb
_, _, tb = sys.exc_info()
if tb:
pdb.post_mortem(tb)
else:
pdb.set_trace()
self.print_usage(sys.stderr)
self.exit(2, ('\nERROR: {}\n').format(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 format_help(self):
"""Overrides format_help to not print subparsers""" |
formatter = self._get_formatter()
# usage
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
# positionals, optionals and user-defined groups, except SubParsers
for action_group in self._action_groups:
if is_subparser(action_group):
continue
formatter.start_section(action_group.title)
formatter.add_text(action_group.description)
formatter.add_arguments(action_group._group_actions)
formatter.end_section()
# epilog
formatter.add_text(self.epilog)
# determine help from format above
return formatter.format_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 open_attributes_file(self):
'''
Called during initialization. Only needs to be explicitly
called if save_and_close_attributes is explicitly called
beforehand.
'''
if not self.saveable():
raise AttributeError("Cannot open attribute file without a valid file")
if self._db_closed:
self._fd = FileDict(self._file_name, db_ext=self._db_ext,
read_only=self._read_only, clear=False, cache_size=0,
immutable_vals=False, stringify_keys=False,
cache_misses=False)
self._db_closed = 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 save_and_close_attributes(self):
'''
Performs the same function as save_attributes but also closes
the attribute file.
'''
if not self.saveable():
raise AttributeError("Cannot save attribute file without a valid file")
if not self._db_closed:
self._db_closed = True
if not self._read_only:
self.save_attributes()
self._fd.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 split_task_parameters(line):
""" Split a string of comma separated words.""" |
if line is None:
result = []
else:
result = [parameter.strip() for parameter in line.split(",")]
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 find_tasks(lines):
""" Find task lines and corresponding line numbers in a list of lines. """ |
tasks = []
linenumbers = []
pattern = re.compile(TASK_PATTERN)
for n, line in enumerate(lines):
if "#" in line and "<-" in line:
m = pattern.match(line)
if m is not None:
groupdict = m.groupdict()
linenumbers.append(n)
for key in groupdict:
groupdict[key] = split_task_parameters(groupdict[key])
logging.debug(
"{0}: {1}".format(key, ", ".join(groupdict[key])))
tasks.append(groupdict)
linenumbers.append(len(lines))
return tasks, linenumbers |
<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_environment(preamble):
""" Create a dictionary of variables obtained from the preamble of the task file and the environment the program is running on. """ |
environment = copy.deepcopy(os.environ)
for line in preamble:
logging.debug(line)
if "=" in line and not line.startswith("#"):
tmp = line.split("=")
key = tmp[0].strip()
value = tmp[1].strip()
logging.debug(
"Found variable {} with value {}".format(key, value))
environment.update({key: value})
logging.debug("Env {}".format(environment))
return environment |
<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_input_file(text, variables=None):
""" Parser for a file with syntax somewhat similar to Drake.""" |
text = find_includes(text)
lines = text.splitlines()
tasks, linenumbers = find_tasks(lines)
preamble = [line for line in lines[:linenumbers[0]]]
logging.debug("Preamble:\n{}".format("\n".join(preamble)))
if variables is not None:
preamble += "\n" + "\n".join(variables)
environment = create_environment(preamble)
code_sections = []
for n in range(len(linenumbers) - 1):
code_sections.append((linenumbers[n], linenumbers[n+1]))
for n, task in zip(code_sections, tasks):
task["code"] = lines[n[0]: n[1]]
task["environment"] = environment
clean_tasks = []
for task in tasks:
clean_tasks.append(Task(**task))
return clean_tasks |
<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_fields(self, *values):
""" Take a list of values, which must be primary keys of the model linked to the related collection, and return a list of related fields. """ |
result = []
for related_instance in values:
if not isinstance(related_instance, model.RedisModel):
related_instance = self.related_field._model(related_instance)
result.append(getattr(related_instance, self.related_field.name))
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 _reverse_call(self, related_method, *values):
""" Convert each value to a related field, then call the method on each field, passing self.instance as argument. If related_method is a string, it will be the method of the related field. If it's a callable, it's a function which accept the related field and self.instance. """ |
related_fields = self._to_fields(*values)
for related_field in related_fields:
if callable(related_method):
related_method(related_field, self.instance._pk)
else:
getattr(related_field, related_method)(self.instance._pk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def srem(self, *values):
""" Do a "set" call with self.instance as parameter for each value. Values must be primary keys of the related model. """ |
self._reverse_call(lambda related_field, value: related_field.delete(), *values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lrem(self, *values):
""" Do a "lrem" call with self.instance as parameter for each value. Values must be primary keys of the related model. The "count" argument of the final call will be 0 to remove all the matching values. """ |
self._reverse_call(lambda related_field, value: related_field.lrem(0, value), *values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loaded(self, request, *args, **kwargs):
"""Return a list of loaded Packs. """ |
serializer = self.get_serializer(list(Pack.objects.all()),
many=True)
return Response(serializer.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 indexed_file(self, f):
""" Setter for information about the file this object indexes. :param f: a tuple of (filename, handle), either (or both) of which can be None. If the handle is None, but filename is provided, then handle is created from the filename. If both handle and filename are None, or they don't match the previous values indexed by this object, any current data in this index is cleared. If either are not None, we require the iterator and the hash function for this object to already be set. """ |
filename, handle = f
if handle is None and filename is not None:
handle = open(filename)
if (handle is None and filename is None) or \
(filename != self._indexed_filename) or \
(handle != self._indexed_file_handle):
self.index = {}
if ((handle is not None or filename is not None) and
(self.record_iterator is None or self.record_hash_function is None)):
raise IndexError("Setting index file failed; reason: iterator "
"(self.record_iterator) or hash function "
"(self.record_hash_function) have to be set first")
self._indexed_filename = filename
self._indexed_file_handle = handle |
<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_index(self, fh, to_str_func=str, generate=True, verbose=False):
""" Write this index to a file. Only the index dictionary itself is stored, no informatiom about the indexed file, or the open filehandle is retained. The Output format is just a tab-separated file, one record per line. The last column is the file location for the record and all columns before that are collectively considered to be the hash key for that record (which is probably only 1 column, but this allows us to permit tabs in hash keys). :param fh: either a string filename or a stream-like object to write to. :param to_str_func: a function to convert hash values to strings. We'll just use str() if this isn't provided. :param generate: build the full index from the indexed file if it hasn't already been built. This is the default, and almost certainly what you want, otherwise just the part of the index already constructed is written :param verbose: if True, output progress messages to stderr. """ |
try:
handle = open(fh, "w")
except TypeError:
# okay, not a filename, try to treat it as a stream to write to.
handle = fh
if generate:
self.__build_index(verbose=verbose)
for key in self._index:
handle.write(to_str_func(key) + "\t" + str(self._index[key]) + "\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 steps(self):
"""Returns an iterable containing the steps to this `Uri` from the root `Uri`, including the root `Uri`.""" |
def _iter(uri, acc):
acc.appendleft(uri.name if uri.name else '')
return _iter(uri.parent, acc) if uri.parent else acc
return _iter(self, acc=deque()) |
<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, addr):
"""Parses a new `Uri` instance from a string representation of a URI. (None, ['', 'foo', 'bar'], '/foo/bar', 'bar') ('somenode:123', ['', 'foo', 'bar'], '/foo/bar', 'bar') (None, ['foo', 'bar'], 'foo/bar', 'bar') """ |
if addr.endswith('/'):
raise ValueError("Uris must not end in '/'") # pragma: no cover
parts = addr.split('/')
if ':' in parts[0]:
node, parts[0] = parts[0], ''
else:
node = None
ret = None # Uri(name=None, parent=None, node=node) if node else None
for step in parts:
ret = Uri(name=step, parent=ret, node=node)
node = None # only set the node on the root Uri
return 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 new_scope(self, new_scope={}):
"""Add a new innermost scope for the duration of the with block. Args: new_scope (dict-like):
The scope to add. """ |
old_scopes, self.scopes = self.scopes, self.scopes.new_child(new_scope)
yield
self.scopes = old_scopes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(self, val):
"""Add a new value to me. Args: val (LispVal):
The value to be added. Returns: LispVal: The added value. Raises: ~parthial.errs.LimitationError: If I already contain the maximum number of elements. """ |
if len(self.things) >= self.max_things:
raise LimitationError('too many things')
self.things.add(val)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rec_new(self, val):
"""Recursively add a new value and its children to me. Args: val (LispVal):
The value to be added. Returns: LispVal: The added value. """ |
if val not in self.things:
for child in val.children():
self.rec_new(child)
self.new(val)
return val |
<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_rec_new(self, k, val):
"""Recursively add a new value and its children to me, and assign a variable to it. Args: k (str):
The name of the variable to assign. val (LispVal):
The value to be added and assigned. Returns: LispVal: The added value. """ |
self.rec_new(val)
self[k] = val
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval(self, expr):
"""Evaluate an expression. This does **not** add its argument (or its result) as an element of me! That is the responsibility of the code that created the object. This means that you need to :meth:`Environment.rec_new` any expression you get from user input before evaluating it. This, and any wrappers around it, are the **only** entry points to expression evaluation you should call from ordinary code (i.e., code that isn't part of a extension). Args: expr (LispVal):
The expression to evaluate. Returns: LispVal: The result of evaluating the expression. Raises: ~parthial.errs.LimitationError: If evaluating the expression would require more nesting, more time, or the allocation of more values than is permissible. """ |
if self.depth >= self.max_depth:
raise LimitationError('too much nesting')
if self.steps >= self.max_steps:
raise LimitationError('too many steps')
self.depth += 1
self.steps += 1
res = expr.eval(self)
self.depth -= 1
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(*args):
"""Display error message via stderr or GUI.""" |
if sys.stdin.isatty():
print('ERROR:', *args, file=sys.stderr)
else:
notify_error(*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 have(cmd):
"""Determine whether supplied argument is a command on the PATH.""" |
try:
# Python 3.3+ only
from shutil import which
except ImportError:
def which(cmd):
"""
Given a command, return the path which conforms to the given mode
on the PATH, or None if there is no such file.
"""
def _access_check(path):
"""
Check that a given file can be accessed with the correct mode.
Additionally check that `path` is not a directory.
"""
return (os.path.exists(path) and os.access(
path, os.F_OK | os.X_OK) and not os.path.isdir(path))
# If we're given a path with a directory part, look it up directly
# rather than referring to PATH directories. This includes checking
# relative to the current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd):
return cmd
return None
paths = os.environ.get('PATH', os.defpath.lstrip(':')).split(':')
seen = set()
for path in paths:
if path not in seen:
seen.add(path)
name = os.path.join(path, cmd)
if _access_check(name):
return name
return None
return which(cmd) is not 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 multithreader(args, paths):
"""Execute multiple processes at once.""" |
def shellprocess(path):
"""Return a ready-to-use subprocess."""
import subprocess
return subprocess.Popen(args + [path],
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
processes = [shellprocess(path) for path in paths]
for process in processes:
process.wait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt_gui(path):
"""Prompt for a new filename via GUI.""" |
import subprocess
filepath, extension = os.path.splitext(path)
basename = os.path.basename(filepath)
dirname = os.path.dirname(filepath)
retry_text = 'Sorry, please try again...'
icon = 'video-x-generic'
# detect and configure dialog program
if have('yad'):
args = ['yad',
'--borders=5',
'--entry',
'--entry-label=Filename:',
'--entry-text=' + basename,
'--title=Batch Tool',
'--window-icon=' + icon]
retry_args = args + ['--text=<b>' + retry_text + '</b>',
'--text-align=center']
elif have('zenity'):
base = ['zenity',
'--entry',
'--entry-text=' + basename,
'--title=Batch Tool',
'--window-icon=info']
args = base + ['--text=Filename:']
retry_args = base + ['--text=' + retry_text]
else:
fatal('Please install yad (or zenity)')
# display filename prompt
try:
new_basename = subprocess.check_output(
args, universal_newlines=True).strip()
except subprocess.CalledProcessError:
sys.exit(1)
# retry prompt if new filename already exists
while os.path.exists(os.path.join(dirname, new_basename + extension)) and \
new_basename != basename:
try:
new_basename = subprocess.check_output(
retry_args, universal_newlines=True).strip()
except subprocess.CalledProcessError:
sys.exit(1)
if new_basename == '':
new_basename = basename
return os.path.join(dirname, new_basename + extension) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt_terminal(path):
"""Prompt for a new filename via terminal.""" |
def rlinput(prompt_msg, prefill=''):
"""
One line is read from standard input. Display `prompt_msg` on
standard error. `prefill` is placed into the editing buffer
before editing begins.
"""
import readline
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt_msg)
finally:
readline.set_startup_hook()
filepath, extension = os.path.splitext(path)
basename = os.path.basename(filepath)
dirname = os.path.dirname(filepath)
# display filename prompt
new_basename = rlinput('Filename: ', basename)
# retry prompt if new filename already exists
while os.path.exists(os.path.join(dirname, new_basename + extension)) and \
new_basename != basename:
new_basename = rlinput('Sorry, please try again... Filename: ',
basename)
if new_basename == '':
new_basename = basename
return os.path.join(dirname, new_basename + extension) |
<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(path):
"""Rename a file if necessary.""" |
new_path = prompt(path)
if path != new_path:
try:
from shutil import move
except ImportError:
from os import rename as move
move(path, new_path)
return new_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 scan(subtitles):
"""Remove advertising from subtitles.""" |
from importlib.util import find_spec
try:
import subnuker
except ImportError:
fatal('Unable to scan subtitles. Please install subnuker.')
# check whether aeidon is available
aeidon = find_spec('aeidon') is not None
if sys.stdin.isatty():
# launch subnuker from the existing terminal
args = (['--aeidon'] if aeidon else []) + \
['--gui', '--regex'] + subtitles
subnuker.main(args)
else:
# launch subnuker from a new terminal
args = (['--aeidon'] if aeidon else []) + \
['--gui', '--regex']
execute(Config.TERMINAL,
'--execute',
'subnuker',
*args + subtitles) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getavailable(self):
"""Return a list of subtitle downloaders available.""" |
from importlib import import_module
available = []
for script in self.SCRIPTS:
if have(script):
available.append(script)
for module in self.MODULES:
try:
import_module(module)
available.append(module)
except ImportError:
pass
return sorted(available) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getdefault(self):
"""Return an available default downloader.""" |
if not self.available:
error('No supported downloaders available')
print('\nPlease install one of the following:', file=sys.stderr)
print(self.SUPPORTED, file=sys.stderr)
sys.exit(1)
default = Config.DOWNLOADER_DEFAULT
if default in self.available:
return default
else:
alternative = self.available[0]
warning('Default downloader {!r} not available, using {!r} instead'
.format(Config.DOWNLOADER_DEFAULT, alternative))
return alternative |
<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, paths, tool, language):
"""Download subtitles via a number of tools.""" |
if tool not in self.available:
fatal('{!r} is not installed'.format(tool))
try:
from . import plugins
downloader = plugins.__getattribute__(tool)
except AttributeError:
fatal('{!r} is not a supported download tool'.format(tool))
try:
if downloader.__code__.co_argcount is 2:
downloader(paths, language)
elif downloader.__code__.co_argcount is 1:
downloader(paths)
except: # pylint: disable=bare-except
if not check_connectivity():
error('Internet connectivity appears to be disabled')
else:
error('{!r} experienced an unknown error'.format(tool)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def epilog(self):
"""Return text formatted for the usage description's epilog.""" |
bold = '\033[1m'
end = '\033[0m'
available = self.available.copy()
index = available.index(Config.DOWNLOADER_DEFAULT)
available[index] = bold + '(' + available[index] + ')' + end
formatted = ' | '.join(available)
return 'Downloaders available: ' + formatted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch_mock_desc(self, patch, *args, **kwarg):
""" Context manager or decorator in order to patch a mock definition of service endpoint in a test. :param patch: Dictionary in order to update endpoint's mock definition :type patch: dict :param service_name: Name of service where you want to use mock. If None it will be used as soon as possible. :type service_name: str :param endpoint: Endpoint where you want to use mock. If None it will be used as soon as possible. :type endpoint: str :param offset: Times it must be ignored before use. Default 0. Only positive integers. :type offset: int :param limit: Times it could be used. Default 1. 0 means no limit. Only positive integers. :type limit: int :return: PatchMockDescDefinition """ |
return PatchMockDescDefinition(patch, self, *args, **kwarg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_mock(self, mock, *args, **kwarg):
""" Context manager or decorator in order to use a coroutine as mock of service endpoint in a test. :param mock: Coroutine to use as mock. It should behave like :meth:`~ClientSession.request`. :type mock: coroutine :param service_name: Name of service where you want to use mock. If None it will be used as soon as possible. :type service_name: str :param endpoint: Endpoint where you want to use mock. If None it will be used as soon as possible. :type endpoint: str :param offset: Times it must be ignored before use. Default 0. Only positive integers. :type offset: int :param limit: Times it could be used. Default 1. 0 means no limit. Only positive integers. :type limit: int :return: UseMockDefinition """ |
return UseMockDefinition(mock, self, *args, **kwarg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_install(context):
""" - sets an acl user group to hold all intranet users - setup the dynamic groups plugin - sets the addable types for the ploneintranet policy """ |
marker = 'ploneintranet-workspace.marker'
if context.readDataFile(marker) is None:
return
portal = api.portal.get()
# Set up a group to hold all intranet users
if api.group.get(groupname=INTRANET_USERS_GROUP_ID) is None:
api.group.create(groupname=INTRANET_USERS_GROUP_ID)
# All users have Reader role on portal root
api.group.grant_roles(groupname=INTRANET_USERS_GROUP_ID,
roles=['Reader', ],
obj=portal)
# Set up dynamic groups plugin to put all users into the above group
pas = api.portal.get_tool('acl_users')
if DYNAMIC_GROUPS_PLUGIN_ID not in pas.objectIds():
addDynamicGroupsPlugin(
pas,
DYNAMIC_GROUPS_PLUGIN_ID,
"ploneintranet.workspace Dynamic Groups"
)
plugin = pas[DYNAMIC_GROUPS_PLUGIN_ID]
plugin.addGroup(
group_id=INTRANET_USERS_GROUP_ID,
predicate='python: True',
title='All Intranet Users',
description='',
active=True,
)
# activate the plugin (all interfaces)
activatePluginInterfaces(portal, DYNAMIC_GROUPS_PLUGIN_ID)
# deactivate the enumerate groups interface for collective.workspace
activatePluginInterfaces(portal, 'workspace_groups',
disable=['IGroupEnumerationPlugin'])
# Set up the ploneintranet policy for all addable types
default_types = []
types = api.portal.get_tool('portal_types')
for type_info in types.listTypeInfo():
if type_info.global_allow:
default_types.append(type_info.getId())
if default_types:
pwftool = api.portal.get_tool('portal_placeful_workflow')
policy = pwftool['ploneintranet_policy']
policy.setChainForPortalTypes(default_types, ('(Default)',)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, value, **kwargs):
""" pre-serialize value """ |
if self._serialize is not None:
return self._serialize(value, **kwargs)
else:
return 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 complete_message(buf):
"returns msg,buf_remaining or None,buf"
# todo: read dollar-length for strings; I dont think I can blindly trust newlines. learn about escaping
# note: all the length checks are +1 over what I need because I'm asking for *complete* lines.
lines=buf.split('\r\n')
if len(lines)<=1: return None,buf
nargs_raw=lines.pop(0)
assert nargs_raw[0]=='*'
nargs=int(nargs_raw[1:])
args=[]
while len(lines)>=2: # 2 because if there isn't at least a blank at the end, we're missing a terminator
if lines[0][0]=='+': args.append(lines.pop(0))
elif lines[0][0]==':': args.append(int(lines.pop(0)[1:]))
elif lines[0][0]=='$':
if len(lines)<3: return None,buf
slen,s=int(lines[0][1:]),lines[1]
if slen!=len(s): raise ValueError('length mismatch %s %r'%(slen,s)) # probably an escaping issue
lines=lines[2:]
args.append(s)
else: raise ValueError('expected initial code in %r'%lines)
if len(args)==nargs: return args,'\r\n'.join(lines)
else: return None,buf |
<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_message(self,msg,sock):
"serialize and deserialize"
command=msg[0]
try: f={'GET':self.get,'SET':self.set,'SUBSCRIBE':self.sub,'PUBLISH':self.pub,
'PING':self.ping,'GETSET':self.getset,'EXPIRE':self.expire,'DEL':self.delete}[command]
except KeyError: print msg; raise
args=msg[1:]
try: return f(sock,*args) if command in self.SOCK_COMMANDS else f(*args)
except Exception as e:
print e
print msg
return '-ERROR\r\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_playbook_from_file(self, path, vars={}):
'''
run top level error checking on playbooks and allow them to include other playbooks.
'''
playbook_data = utils.parse_yaml_from_file(path)
accumulated_plays = []
play_basedirs = []
if type(playbook_data) != list:
raise errors.AnsibleError("parse error: playbooks must be formatted as a YAML list")
basedir = os.path.dirname(path) or '.'
utils.plugins.push_basedir(basedir)
for play in playbook_data:
if type(play) != dict:
raise errors.AnsibleError("parse error: each play in a playbook must a YAML dictionary (hash), recieved: %s" % play)
if 'include' in play:
tokens = shlex.split(play['include'])
items = ['']
for k in play.keys():
if not k.startswith("with_"):
# These are the keys allowed to be mixed with playbook includes
if k in ("include", "vars"):
continue
else:
raise errors.AnsibleError("parse error: playbook includes cannot be used with other directives: %s" % play)
plugin_name = k[5:]
if plugin_name not in utils.plugins.lookup_loader:
raise errors.AnsibleError("cannot find lookup plugin named %s for usage in with_%s" % (plugin_name, plugin_name))
terms = utils.template_ds(basedir, play[k], vars)
items = utils.plugins.lookup_loader.get(plugin_name, basedir=basedir, runner=None).run(terms, inject=vars)
for item in items:
incvars = vars.copy()
incvars['item'] = item
if 'vars' in play:
if isinstance(play['vars'], dict):
incvars.update(play['vars'])
elif isinstance(play['vars'], list):
for v in play['vars']:
incvars.update(v)
for t in tokens[1:]:
(k,v) = t.split("=", 1)
incvars[k] = utils.template_ds(basedir, v, incvars)
included_path = utils.path_dwim(basedir, tokens[0])
(plays, basedirs) = self._load_playbook_from_file(included_path, incvars)
for p in plays:
if 'vars' not in p:
p['vars'] = {}
if isinstance(p['vars'], dict):
p['vars'].update(incvars)
elif isinstance(p['vars'], list):
p['vars'].extend([dict(k=v) for k,v in incvars.iteritems()])
accumulated_plays.extend(plays)
play_basedirs.extend(basedirs)
else:
accumulated_plays.append(play)
play_basedirs.append(basedir)
return (accumulated_plays, play_basedirs) |
<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(self):
''' run all patterns in the playbook '''
plays = []
matched_tags_all = set()
unmatched_tags_all = set()
# loop through all patterns and run them
self.callbacks.on_start()
for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs):
play = Play(self, play_ds, play_basedir)
matched_tags, unmatched_tags = play.compare_tags(self.only_tags)
matched_tags_all = matched_tags_all | matched_tags
unmatched_tags_all = unmatched_tags_all | unmatched_tags
# if we have matched_tags, the play must be run.
# if the play contains no tasks, assume we just want to gather facts
if (len(matched_tags) > 0 or len(play.tasks()) == 0):
plays.append(play)
# if the playbook is invoked with --tags that don't exist at all in the playbooks
# then we need to raise an error so that the user can correct the arguments.
unknown_tags = set(self.only_tags) - (matched_tags_all | unmatched_tags_all)
unknown_tags.discard('all')
if len(unknown_tags) > 0:
unmatched_tags_all.discard('all')
msg = 'tag(s) not found in playbook: %s. possible values: %s'
unknown = ','.join(sorted(unknown_tags))
unmatched = ','.join(sorted(unmatched_tags_all))
raise errors.AnsibleError(msg % (unknown, unmatched))
for play in plays:
if not self._run_play(play):
break
# summarize the results
results = {}
for host in self.stats.processed.keys():
results[host] = self.stats.summarize(host)
return results |
<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_poll(self, poller, async_seconds, async_poll_interval):
''' launch an async job, if poll_interval is set, wait for completion '''
results = poller.wait(async_seconds, async_poll_interval)
# mark any hosts that are still listed as started as failed
# since these likely got killed by async_wrapper
for host in poller.hosts_to_poll:
reason = { 'failed' : 1, 'rc' : None, 'msg' : 'timed out' }
self.runner_callbacks.on_failed(host, reason)
results['contacted'][host] = reason
return results |
<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_available_hosts(self, *args):
''' returns a list of hosts that haven't failed and aren't dark '''
return [ h for h in self.inventory.list_hosts(*args) if (h not in self.stats.failures) and (h not in self.stats.dark)] |
<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_task_internal(self, task):
''' run a particular module step in a playbook '''
hosts = self._list_available_hosts()
self.inventory.restrict_to(hosts)
runner = cirruscluster.ext.ansible.runner.Runner(
pattern=task.play.hosts, inventory=self.inventory, module_name=task.module_name,
module_args=task.module_args, forks=self.forks,
remote_pass=self.remote_pass, module_path=self.module_path,
timeout=self.timeout, remote_user=task.play.remote_user,
remote_port=task.play.remote_port, module_vars=task.module_vars,
private_key_file=self.private_key_file,
private_key=self.private_key,
setup_cache=self.SETUP_CACHE, basedir=task.play.basedir,
conditional=task.only_if, callbacks=self.runner_callbacks,
sudo=task.sudo, sudo_user=task.sudo_user,
transport=task.transport, sudo_pass=task.sudo_pass, is_playbook=True
)
if task.async_seconds == 0:
results = runner.run()
else:
results, poller = runner.run_async(task.async_seconds)
self.stats.compute(results)
if task.async_poll_interval > 0:
# if not polling, playbook requested fire and forget, so don't poll
results = self._async_poll(poller, task.async_seconds, task.async_poll_interval)
contacted = results.get('contacted',{})
dark = results.get('dark', {})
self.inventory.lift_restriction()
if len(contacted.keys()) == 0 and len(dark.keys()) == 0:
return None
return results |
<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_task(self, play, task, is_handler):
''' run a single task in the playbook and recursively run any subtasks. '''
self.callbacks.on_task_start(utils.template(play.basedir, task.name, task.module_vars, lookup_fatal=False), is_handler)
# load up an appropriate ansible runner to run the task in parallel
results = self._run_task_internal(task)
# if no hosts are matched, carry on
hosts_remaining = True
if results is None:
hosts_remaining = False
results = {}
contacted = results.get('contacted', {})
self.stats.compute(results, ignore_errors=task.ignore_errors)
# add facts to the global setup cache
for host, result in contacted.iteritems():
# Skip register variable if host is skipped
if result.get('skipped', False):
continue
facts = result.get('ansible_facts', {})
self.SETUP_CACHE[host].update(facts)
# extra vars need to always trump - so update again following the facts
self.SETUP_CACHE[host].update(self.extra_vars)
if task.register:
if 'stdout' in result:
result['stdout_lines'] = result['stdout'].splitlines()
self.SETUP_CACHE[host][task.register] = result
# flag which notify handlers need to be run
if len(task.notify) > 0:
for host, results in results.get('contacted',{}).iteritems():
if results.get('changed', False):
for handler_name in task.notify:
self._flag_handler(play, utils.template(play.basedir, handler_name, task.module_vars), host)
return hosts_remaining |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _flag_handler(self, play, handler_name, host):
'''
if a task has any notify elements, flag handlers for run
at end of execution cycle for hosts that have indicated
changes have been made
'''
found = False
for x in play.handlers():
if handler_name == utils.template(play.basedir, x.name, x.module_vars):
found = True
self.callbacks.on_notify(host, x.name)
x.notified_by.append(host)
if not found:
raise errors.AnsibleError("change handler (%s) is not defined" % handler_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 _do_setup_step(self, play):
''' get facts from the remote system '''
host_list = self._list_available_hosts(play.hosts)
if play.gather_facts is False:
return {}
elif play.gather_facts is None:
host_list = [h for h in host_list if h not in self.SETUP_CACHE or 'module_setup' not in self.SETUP_CACHE[h]]
if len(host_list) == 0:
return {}
self.callbacks.on_setup()
self.inventory.restrict_to(host_list)
# push any variables down to the system
setup_results = cirruscluster.ext.ansible.runner.Runner(
pattern=play.hosts, module_name='setup', module_args={}, inventory=self.inventory,
forks=self.forks, module_path=self.module_path, timeout=self.timeout, remote_user=play.remote_user,
remote_pass=self.remote_pass, remote_port=play.remote_port, private_key_file=self.private_key_file,
private_key=self.private_key,
setup_cache=self.SETUP_CACHE, callbacks=self.runner_callbacks, sudo=play.sudo, sudo_user=play.sudo_user,
transport=play.transport, sudo_pass=self.sudo_pass, is_playbook=True, module_vars=play.vars,
).run()
self.stats.compute(setup_results, setup=True)
self.inventory.lift_restriction()
# now for each result, load into the setup cache so we can
# let runner template out future commands
setup_ok = setup_results.get('contacted', {})
for (host, result) in setup_ok.iteritems():
self.SETUP_CACHE[host].update({'module_setup': True})
self.SETUP_CACHE[host].update(result.get('ansible_facts', {}))
return setup_results |
<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_play(self, play):
''' run a list of tasks for a given pattern, in order '''
self.callbacks.on_play_start(play.name)
# if no hosts matches this play, drop out
if not self.inventory.list_hosts(play.hosts):
self.callbacks.on_no_hosts_matched()
return True
# get facts from system
self._do_setup_step(play)
# now with that data, handle contentional variable file imports!
all_hosts = self._list_available_hosts(play.hosts)
play.update_vars_files(all_hosts)
serialized_batch = []
if play.serial <= 0:
serialized_batch = [all_hosts]
else:
# do N forks all the way through before moving to next
while len(all_hosts) > 0:
play_hosts = []
for x in range(play.serial):
if len(all_hosts) > 0:
play_hosts.append(all_hosts.pop())
serialized_batch.append(play_hosts)
for on_hosts in serialized_batch:
self.inventory.also_restrict_to(on_hosts)
for task in play.tasks():
# only run the task if the requested tags match
should_run = False
for x in self.only_tags:
for y in task.tags:
if (x==y):
should_run = True
break
if should_run:
if not self._run_task(play, task, False):
# whether no hosts matched is fatal or not depends if it was on the initial step.
# if we got exactly no hosts on the first step (setup!) then the host group
# just didn't match anything and that's ok
return False
host_list = self._list_available_hosts(play.hosts)
# if no hosts remain, drop out
if not host_list:
self.callbacks.on_no_hosts_remaining()
return False
# run notify actions
for handler in play.handlers():
if len(handler.notified_by) > 0:
self.inventory.restrict_to(handler.notified_by)
self._run_task(play, handler, True)
self.inventory.lift_restriction()
handler.notified_by = []
self.inventory.lift_also_restriction()
return True |
<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_cmdLine_instructions(args):
""" Parses command-line arguments. These are instruction to the manager to create instances and put settings. """ |
instructions = dict()
rargs = list()
for arg in args:
if arg[:2] == '--':
tmp = arg[2:]
bits = tmp.split('=', 1)
if len(bits) == 1:
bits.append('')
instructions[bits[0]] = bits[1]
else:
rargs.append(arg)
return instructions, rargs |
<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():
""" Entry-point """ |
sarah.coloredLogging.basicConfig(level=logging.DEBUG,
formatter=MirteFormatter())
l = logging.getLogger('mirte')
instructions, args = parse_cmdLine_instructions(sys.argv[1:])
m = Manager(l)
load_mirteFile(args[0] if args else 'default', m, logger=l)
execute_cmdLine_instructions(instructions, m, l)
m.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def installed(cls):
""" Used in ``yacms.pages.views.page`` to ensure ``PageMiddleware`` or a subclass has been installed. We cache the result on the ``PageMiddleware._installed`` to only run this once. Short path is to just check for the dotted path to ``PageMiddleware`` in ``MIDDLEWARE_CLASSES`` - if not found, we need to load each middleware class to match a subclass. """ |
try:
return cls._installed
except AttributeError:
name = "yacms.pages.middleware.PageMiddleware"
mw_setting = get_middleware_setting()
installed = name in mw_setting
if not installed:
for name in mw_setting:
if issubclass(import_dotted_path(name), cls):
installed = True
break
setattr(cls, "_installed", installed)
return installed |
<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_view(self, request, view_func, view_args, view_kwargs):
""" Per-request mechanics for the current page object. """ |
# Load the closest matching page by slug, and assign it to the
# request object. If none found, skip all further processing.
slug = path_to_slug(request.path_info)
pages = Page.objects.with_ascendants_for_slug(slug,
for_user=request.user, include_login_required=True)
if pages:
page = pages[0]
setattr(request, "page", page)
context_processors.page(request)
else:
return
# Handle ``page.login_required``.
if page.login_required and not request.user.is_authenticated():
return redirect_to_login(request.get_full_path())
# If the view isn't yacms's page view, try to return the result
# immediately. In the case of a 404 with an URL slug that matches a
# page exactly, swallow the exception and try yacms's page view.
#
# This allows us to set up pages with URLs that also match non-page
# urlpatterns. For example, a page could be created with the URL
# /blog/about/, which would match the blog urlpattern, and assuming
# there wasn't a blog post with the slug "about", would raise a 404
# and subsequently be rendered by yacms's page view.
if view_func != page_view:
try:
return view_func(request, *view_args, **view_kwargs)
except Http404:
if page.slug != slug:
raise
# Run page processors.
extra_context = {}
model_processors = page_processors.processors[page.content_model]
slug_processors = page_processors.processors["slug:%s" % page.slug]
for (processor, exact_page) in slug_processors + model_processors:
if exact_page and not page.is_current:
continue
processor_response = processor(request, page)
if isinstance(processor_response, HttpResponse):
return processor_response
elif processor_response:
try:
for k, v in processor_response.items():
if k not in extra_context:
extra_context[k] = v
except (TypeError, ValueError):
name = "%s.%s" % (processor.__module__, processor.__name__)
error = ("The page processor %s returned %s but must "
"return HttpResponse or dict." %
(name, type(processor_response)))
raise ValueError(error)
return page_view(request, slug, extra_context=extra_context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unshare(flags):
""" Disassociate parts of the process execution context. :param flags int: A bitmask that specifies which parts of the execution context should be unshared. """ |
res = lib.unshare(flags)
if res != 0:
_check_error(ffi.errno) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setns(fd, nstype):
""" Reassociate thread with a namespace :param fd int: The file descriptor referreing to one of the namespace entries in a :directory::`/proc/<pid>/ns/` directory. :param nstype int: The type of namespace the calling thread should be reasscoiated with. """ |
res = lib.setns(fd, nstype)
if res != 0:
_check_error(ffi.errno) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reset(self):
""" Resets class properties. """ |
self._name = None
self._start_time = None
self._owner = os.getuid()
self._paths['task_dir'] = None
self._paths['task_config'] = None
self._loaded = 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 _save_active_file(self):
""" Saves current task information to active file. Example format:: active_task { name "task name"; start_time "2012-04-23 15:18:22"; } """ |
_parser = parser.SettingParser()
# add name
_parser.add_option(None, 'name', common.to_utf8(self._name))
# add start time
start_time = self._start_time.strftime('%Y-%m-%d %H:%M:%S.%f')
_parser.add_option(None, 'start_time', start_time)
# write it to file
return _parser.write(self._paths['active_file'],
self.HEADER_ACTIVE_FILE) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_prior(self):
""" Cleans up from a previous task that didn't exit cleanly. Returns ``True`` if previous task was cleaned. """ |
if self._loaded:
try:
pid_file = daemon.get_daemon_pidfile(self)
# check if it exists so we don't raise
if os.path.isfile(pid_file):
# read pid from file
pid = int(common.readfile(pid_file))
# check if pid file is stale
if pid and not daemon.pid_exists(pid):
common.safe_remove_file(pid_file)
raise ValueError
except (ValueError, TypeError):
self._clean()
return True
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 load(self):
""" Loads a task if the active file is available. """ |
try:
_parser = parser.parse_config(self._paths['active_file'],
self.HEADER_ACTIVE_FILE)
# parse expected options into a dict to de-dupe
keys = ('name', 'start_time')
opts = dict(o for o in _parser.options if o[0] in keys)
# check for all keys
for k in keys:
if not opts.get(k):
return False
task_name = opts.get('name')[0]
# setup the paths
task_dir = self._get_task_dir(task_name)
task_config = os.path.join(task_dir, 'task.cfg')
# validate start time
value = opts.get('start_time')[0]
start_time = datetime.datetime.strptime(value,
'%Y-%m-%d %H:%M:%S.%f')
# get user id for process ownership when running task
# here, we use the owner of the active file
file_meta = os.stat(self._paths['active_file'])
owner = file_meta.st_uid
# parse task config and send its options to registered plugins
_parser = parser.parse_config(task_config, self.HEADER_TASK_CONFIG)
registration.run_option_hooks(_parser)
self._name = common.from_utf8(task_name)
self._start_time = start_time
self._owner = owner
self._paths['task_dir'] = task_dir
self._paths['task_config'] = task_config
self._loaded = True
except (parser.ParseError, ValueError, TypeError, OSError):
# something failed, cleanup
self._clean()
self._clean_prior()
return self._loaded |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self, task_name):
""" Determines if task directory exists. `task_name` Task name. Returns ``True`` if task exists. """ |
try:
return os.path.exists(self._get_task_dir(task_name))
except OSError:
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 create(self, task_name, clone_task=None):
""" Creates a new task directory. `task_name` Task name. `clone_task` Existing task name to use as a template for new task. Returns boolean. * Raises ``Value`` if task name is invalid, ``TaskExists`` if task already exists, or ``TaskNotFound`` if task for `clone_from` doesn't exist. """ |
if not task_name or task_name.startswith('-'):
raise ValueError('Invalid task name')
try:
task_dir = self._get_task_dir(task_name)
if self.exists(task_dir):
raise errors.TaskExists(task_name)
task_cfg = self.get_config_path(task_name)
if clone_task:
if not self.exists(clone_task):
raise errors.TaskNotFound(clone_task)
# copy task directory
shutil.copytree(self._get_task_dir(clone_task), task_dir)
else:
os.mkdir(task_dir)
# write default task configuration
shutil.copy(self._default_task_config, task_cfg)
return True
except OSError:
shutil.rmtree(task_dir, ignore_errors=True)
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 rename(self, old_task_name, new_task_name):
""" Renames an existing task directory. `old_task_name` Current task name. `new_task_name` New task name. Returns ``True`` if rename successful. """ |
if not old_task_name or old_task_name.startswith('-'):
raise ValueError('Old task name is invalid')
if not new_task_name or new_task_name.startswith('-'):
raise ValueError('New new task name is invalid')
if old_task_name == new_task_name:
raise ValueError('Cannot rename task to itself')
try:
old_task_dir = self._get_task_dir(old_task_name)
if not self.exists(old_task_dir):
raise errors.TaskNotFound(old_task_name)
new_task_dir = self._get_task_dir(new_task_name)
if self.exists(new_task_dir):
raise errors.TaskExists(new_task_name)
os.rename(old_task_dir, new_task_dir)
return True
except OSError:
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 remove(self, task_name):
""" Removes an existing task directory. `task_name` Task name. Returns ``True`` if removal successful. """ |
try:
task_dir = self._get_task_dir(task_name)
shutil.rmtree(task_dir)
return True
except OSError:
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 get_list_info(self, task_name=None):
""" Lists all tasks and associated information. `task_name` Task name to limit. Default: return all valid tasks. Returns list of tuples (task_name, options, block_options) """ |
try:
tasks = []
# get all tasks dirs
tasks_dir = os.path.join(self._paths['base_dir'], 'tasks')
if task_name:
# if task folder doesn't exist, return nothing
if not os.path.isdir(os.path.join(tasks_dir, task_name)):
return []
task_names = [task_name]
else:
task_names = [name for name in os.listdir(tasks_dir)
if os.path.isdir(os.path.join(tasks_dir, name))]
task_names.sort()
for name in task_names:
try:
# parse task config and run option hooks
task_config = os.path.join(tasks_dir, name, 'task.cfg')
parser_ = parser.parse_config(task_config,
self.HEADER_TASK_CONFIG)
registration.run_option_hooks(parser_,
disable_missing=False)
tasks.append((name, parser_.options, parser_.blocks))
except (parser.ParseError, errors.InvalidTaskConfig):
tasks.append((name, None, None))
return tasks
except OSError:
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 start(self, task_name):
""" Starts a new task matching the provided name. `task_name` Name of existing task to start. Returns boolean. * Raises a ``TaskNotFound`` exception if task doesn't exist, an ``InvalidTaskConfig` exception if task config file is invalid, or ``DaemonFailStart`` exception if task daemons failed to fork. """ |
self._clean_prior()
if self._loaded:
raise errors.ActiveTask
# get paths
task_dir = os.path.join(self._paths['base_dir'], 'tasks', task_name)
task_config = os.path.join(task_dir, 'task.cfg')
if not os.path.isdir(task_dir):
raise errors.TaskNotFound(task_name)
try:
# raise if task config is missing
if not os.path.isfile(task_config):
reason = u"Config file could not be found."
raise errors.InvalidTaskConfig(task_config, reason=reason)
# parse task config and send its options to registered plugins
_parser = parser.parse_config(task_config, self.HEADER_TASK_CONFIG)
registration.run_option_hooks(_parser)
except parser.ParseError as exc:
raise errors.InvalidTaskConfig(task_config,
reason=unicode(exc))
# populate task info
self._name = common.from_utf8(task_name)
self._start_time = datetime.datetime.now()
self._owner = os.getuid()
self._paths['task_dir'] = task_dir
self._paths['task_config'] = task_config
self._loaded = True
# task is setup, save active file
# note, order is *important*; this is needed first
# for the daemon to load
self._save_active_file()
# shell the focusd daemon
try:
started = daemon.shell_focusd(self._paths['base_dir'])
# user cancelled or passwords failed?
except (KeyboardInterrupt, ValueError):
self._clean()
return False
# no event plugins registered, carry on
except errors.NoPluginsRegistered:
return True
# failed, cleanup our mess
if not started:
self._clean()
raise errors.DaemonFailStart
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Stops the current task and cleans up, including removing active task config file. * Raises ``NoActiveTask`` exception if no active task found. """ |
self._clean_prior()
if not self._loaded:
raise errors.NoActiveTask
self._clean() |
<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_total_duration(self, duration):
""" Set the total task duration in minutes. """ |
if duration < 1:
raise ValueError(u'Duration must be postive')
elif self.duration > duration:
raise ValueError(u'{0} must be greater than current duration')
self._total_duration = duration |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active(self):
""" Returns if task is active. """ |
if not os.path.isfile(self._paths['active_file']):
return False
return self._loaded |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def duration(self):
""" Returns task's current duration in minutes. """ |
if not self._loaded:
return 0
delta = datetime.datetime.now() - self._start_time
total_secs = (delta.microseconds +
(delta.seconds + delta.days * 24 * 3600) *
10 ** 6) / 10 ** 6
return max(0, int(round(total_secs / 60.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 list_objects(self, resources):
"""Generate a listing for a set of resource handles consisting of resource identifier, name, and timestamp. Parameters resources : list(ResourceHandle) List of resource handles Returns ------- list(string) """ |
result = []
for res in resources:
result.append('\t'.join([res.identifier, res.name, str(res.timestamp)[:19]]))
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 set_locale(request):
"""Return locale from GET lang param or automatically.""" |
return request.query.get('lang', app.ps.babel.select_locale_by_request(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def globals(self):
"""Find the globals of `self` by importing `self.module`""" |
try:
return vars(__import__(self.module, fromlist=self.module.split('.')))
except ImportError:
if self.warn_import:
warnings.warn(ImportWarning(
'Cannot import module {} for SerializableFunction. Restricting to builtins.'.format(self.module)
))
return {'__builtins__': __builtins__} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
"""Import the constant from `self.module`""" |
module = __import__(self.module, fromlist=self.module.split('.'))
if self.name is None:
return module
return getattr(module, self.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 agg(self, func, *fields, **name):
""" Calls the aggregation function `func` on each group in the GroubyTable, and leaves the results in a new column with the name of the aggregation function. Call `.agg` with `name='desired_column_name' to choose a column name for this aggregation. """ |
if name:
if len(name) > 1 or 'name' not in name:
raise TypeError("Unknown keyword args passed into `agg`: %s"
% name)
name = name.get('name')
if not isinstance(name, basestring):
raise TypeError("Column names must be strings, not `%s`"
% type(name))
else:
name = name
elif func.__name__ == '<lambda>':
name = "lambda%04d" % self.__lambda_num
self.__lambda_num += 1
name += "(%s)" % ','.join(fields)
else:
name = func.__name__
name += "(%s)" % ','.join(fields)
aggregated_column = []
if len(fields) > 1:
for groupkey in self.__grouptable['groupkey']:
agg_data = [tuple([row[field] for field in fields])
for row in self.__key_to_group_map[groupkey]]
aggregated_column.append(func(agg_data))
elif len(fields) == 1:
field = fields[0]
for groupkey in self.__grouptable['groupkey']:
agg_data = [row[field]
for row in self.__key_to_group_map[groupkey]]
aggregated_column.append(func(agg_data))
else:
for groupkey in self.__grouptable['groupkey']:
agg_data = self.__key_to_group_map[groupkey]
aggregated_column.append(func(agg_data))
self.__grouptable[name] = aggregated_column
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 collect(self):
""" After adding the desired aggregation columns, `collect` finalizes the groupby operation by converting the GroupbyTable into a DataTable. The first columns of the resulting table are the groupfields, followed by the aggregation columns specified in preceeding `agg` calls. """ |
# The final order of columns is determined by the
# group keys and the aggregation columns
final_field_order = list(self.__groupfields) + self.__grouptable.fields
# Transform the group key rows into columns
col_values = izip(*self.__grouptable['groupkey'])
# Assign the columns to the table with the relevant name
for groupfield, column in izip(self.__groupfields, col_values):
self.__grouptable[groupfield] = column
# Reorder the columns as defined above
self.__grouptable.reorder(final_field_order)
del self.__grouptable['groupkey']
return self.__grouptable |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kv_format_dict(d, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats the given dictionary ``d``. For more details see :func:`kv_format`. :param collections.Mapping d: Dictionary containing values to format. :param collections.Iterable keys: List of keys to extract from the dict. :param str separator: Value between two pairs. :return: Key-Value formatted content generated from ``d``. :rtype: :data:`six.text_type <six:six.text_type>` """ |
return _format_pairs(dump_dict(d, keys), separator=separator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kv_format_object(o, keys=None, separator=DEFAULT_SEPARATOR):
"""Formats an object's attributes. Useful for object representation implementation. Will skip methods or private attributes. For more details see :func:`kv_format`. :param o: Object to format. :param collections.Sequence keys: Explicit list of attributes to format. ``None`` means all public visible attribute for the given object will be formatted. :param str separator: Value between two pairs. :return: Formatted Object attributes. :rtype: :data:`six.text_type <six:six.text_type>` """ |
if keys is None:
key_values = []
for k, v in ((x, getattr(o, x)) for x in sorted(dir(o))):
if k.startswith('_') or isroutine(v):
continue
key_values += (k, v),
else:
key_values = ((k, getattr(o, k)) for k in keys)
return kv_format_pairs(key_values, separator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, request, *args, **kwargs):
""" Triggers the task that sends invitation messages """ |
status = 201
accepted = {"accepted": True}
send_invite_messages.apply_async()
return Response(accepted, status=status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def post(self, request):
'''Create a user and token, given an email. If user exists just
provide the token.'''
serializer = CreateUserSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data.get('email')
try:
user = User.objects.get(username=email)
except User.DoesNotExist:
user = User.objects.create_user(email, email=email)
token, created = Token.objects.get_or_create(user=user)
return Response(
status=status.HTTP_201_CREATED, data={'token': token.key}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, request, *args, **kwargs):
""" Redefine parent's method. Called on each new request from user. Main difference between Django's approach and ours - we don't push a 'request' to a method call. We use 'self.request' instead. """ |
# this part copied from django source code
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
# we changed only this line - removed first 'request' argument
return handler(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def html(self, data=None, template=None):
""" Send html document to user. Args: - data: Dict to render template, or string with rendered HTML. - template: Name of template to render HTML document with passed data. """ |
if data is None:
data = {}
if template:
return render(self.request, template, data)
return HttpResponse(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 by_skills(queryset, skill_string=None):
""" Filter queryset by a comma delimeted skill list """ |
if skill_string:
operator, items = get_operator_and_items(skill_string)
q_obj = SQ()
for s in items:
if len(s) > 0:
q_obj.add(SQ(skills=s), operator)
queryset = queryset.filter(q_obj)
return queryset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_causes(queryset, cause_string=None):
""" Filter queryset by a comma delimeted cause list """ |
if cause_string:
operator, items = get_operator_and_items(cause_string)
q_obj = SQ()
for c in items:
if len(c) > 0:
q_obj.add(SQ(causes=c), operator)
queryset = queryset.filter(q_obj)
return queryset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_published(queryset, published_string='true'):
""" Filter queryset by publish status """ |
if published_string == 'true':
queryset = queryset.filter(published=1)
elif published_string == 'false':
queryset = queryset.filter(published=0)
# Any other value will return both published and unpublished
return queryset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_name(queryset, name=None):
""" Filter queryset by name, with word wide auto-completion """ |
if name:
queryset = queryset.filter(name=name)
return queryset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_address(queryset, address='', project=False):
""" Filter queryset by publish status. If project=True, we also apply a project exclusive filter """ |
if address:
address = json.loads(address)
if u'address_components' in address:
q_objs = []
"""
Caribbean filter
"""
if len(address[u'address_components']):
if address[u'address_components'][0]['long_name'] == 'Caribbean':
queryset = queryset.filter(
SQ(address_components=helpers.whoosh_raw(u"{}-{}".format('Jamaica', 'country').strip())) |
SQ(address_components=helpers.whoosh_raw(u"{}-{}".format('Haiti', 'country').strip())) |
SQ(address_components=helpers.whoosh_raw(u"{}-{}".format('Saint Lucia', 'country').strip())) |
SQ(address_components=helpers.whoosh_raw(u"{}-{}".format('Suriname', 'country').strip())) |
SQ(address_components=helpers.whoosh_raw(u"{}-{}".format('Trinidad & Tobago', 'country').strip()))
)
return queryset
for component in address[u'address_components']:
q_obj = SQ()
test = ''
for component_type in component[u'types']:
type_string = helpers.whoosh_raw(u"{}-{}".format(component[u'long_name'], component_type).strip())
q_obj.add(SQ(address_components=type_string), SQ.OR)
q_objs.append(q_obj)
# Filter all address components
for obj in q_objs:
queryset = queryset.filter(obj)
else: # remote projects
if project:
queryset = queryset.filter(can_be_done_remotely=1)
return queryset |
<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_out(queryset, setting_name):
""" Remove unwanted results from queryset """ |
kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {})
queryset = queryset.exclude(**kwargs)
return queryset |
<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_apps():
""" It returns a list of application contained in PROJECT_APPS """ |
return [(d.split('.')[-1], d.split('.')[-1]) for d in os.listdir(
os.getcwd()) if is_app(u"{}/{}".format(os.getcwd(), d))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slug(self):
""" It returns node's slug """ |
if self.is_root_node():
return ""
if self.slugable and self.parent.parent:
if not self.page.regex or (self.page.regex and not self.page.show_regex) or self.is_leaf_node():
return u"{0}/{1}".format(self.parent.slug, self.page.slug)
elif self.page.regex and self.value_regex and self.page.show_regex:
return u'{0}/{1}/{2}'.format(self.parent.slug, self.page.slug, self.value_regex)
elif not self.hide_in_url:
return u'{0}/{1}'.format(self.parent.slug, self.name)
elif self.slugable:
if not self.page.regex or (self.page.regex and not self.page.show_regex) or self.is_leaf_node():
return u"{0}".format(self.page.slug)
elif self.page.regex and self.value_regex and self.page.show_regex:
return u'{0}/{1}'.format(self.page.slug, self.value_regex)
elif not self.hide_in_url:
return u'{0}'.format(self.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_pattern(self):
""" It returns its url pattern """ |
if self.is_root_node():
return ""
else:
parent_pattern = self.parent.get_pattern()
if parent_pattern != "":
parent_pattern = u"{}".format(parent_pattern)
if not self.page and not self.is_leaf_node():
if self.hide_in_url:
return u'{0}'.format(parent_pattern)
else:
return u'{0}{1}'.format(parent_pattern, self.name)
else:
if self.is_leaf_node() and self.page.regex and self.page.show_regex:
return u'{0}{1}/{2}'.format(parent_pattern, self.page.slug, self.page.regex)
elif self.is_leaf_node() and (not self.page.regex or not self.page.show_regex):
return u'{0}{1}/'.format(parent_pattern, self.page.slug)
elif not self.is_leaf_node() and self.page.regex and self.page.show_regex:
return u'{0}{1}/{2}/'.format(parent_pattern, self.page.slug, self.page.regex)
else:
return u'{0}{1}/'.format(parent_pattern, self.page.slug) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def presentation_type(self):
""" It returns page's presentation_type """ |
if self.page and self.page.presentation_type:
return self.page.presentation_type
return "" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.