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 certify_set( value, certifier=None, min_len=None, max_len=None, include_collections=False, required=True, ):
""" Certifier for a set. :param set value: The s... |
certify_bool(include_collections, required=True)
certify_iterable(
value=value,
types=tuple([set, MutableSet, Set]) if include_collections else tuple([set]),
certifier=certifier,
min_len=min_len,
max_len=max_len,
schema=None,
required=required,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def certify_tuple(value, certifier=None, min_len=None, max_len=None, required=True, schema=None):
""" Validates a tuple, checking it against an optional schema. ... |
certify_iterable(
value=value,
types=tuple([tuple]),
certifier=certifier,
min_len=min_len,
max_len=max_len,
schema=schema,
required=required,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def certify_list( value, certifier=None, min_len=None, max_len=None, required=True, schema=None, include_collections=False, ):
""" Certifier for a list. :param l... |
certify_bool(include_collections, required=True)
certify_iterable(
value=value,
types=tuple([list, MutableSequence, Sequence]) if include_collections else tuple([list]),
certifier=certifier,
min_len=min_len,
max_len=max_len,
schema=schema,
required=requir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def certify_email(value, required=True):
""" Certifier which verifies that email addresses are well-formed. Does not check that the address exists. :param six.st... |
certify_required(
value=value,
required=required,
)
certify_string(value, min_length=3, max_length=320)
try:
certification_result = email_validator.validate_email(
value,
check_deliverability=False,
)
except email_validator.EmailNotValidError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid(self, model, validator=None):
"""Returns true if the model passes the validation, and false if not. Validator must be present_optional if validation... |
if self.property_name and self.is_property_specific:
arg0 = getattr(model, self.property_name)
else:
arg0 = model
if self.is_simple:
is_valid = self.callback(arg0)
else:
is_valid = self.callback(arg0, validator)
return (is_valid, None if is_valid else (self.message or "is ... |
<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(self, model, validator=None):
"""Checks the model against all filters, and if it shoud be validated, runs the validation. if the model is invalid, a... |
for filter_ in self.filters:
if not filter_(model):
return True
is_valid, message = self.is_valid(model, validator)
if not is_valid:
model.add_error(self.pretty_property_name or self.property_name, message)
return is_valid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_present(val):
"""Returns True if the value is not None, and if it is either not a string, or a string with length > 0. """ |
if val is None:
return False
if isinstance(val, str):
return len(val) > 0
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 is_length(property_name, *, min_length=1, max_length=None, present_optional=False):
"""Returns a Validation that checks the length of a string.""" |
def check(val):
"""Checks that a value matches a scope-enclosed set of length parameters."""
if not val:
return present_optional
else:
if len(val) >= min_length:
if max_length is None:
return True
else:
return len(val) <= max_length
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matches(property_name, regex, *, present_optional=False, message=None):
"""Returns a Validation that checks a property against a regex.""" |
def check(val):
"""Checks that a value matches a scope-enclosed regex."""
if not val:
return present_optional
else:
return True if regex.search(val) else False
return Validation(check, property_name, 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 is_numeric(property_name, *, numtype="float", min=None, max=None, present_optional=False, message=None):
"""Returns a Validation that checks a property as a ... |
if numtype == "int":
cast = util.try_parse_int
elif numtype == "decimal":
cast = util.try_parse_decimal
elif numtype == "float":
cast = util.try_parse_float
else:
raise ValueError("numtype argument must be one of: int, decimal, float")
def check(val):
"""Checks that a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_date(property_name, *, format=None, present_optional=False, message=None):
"""Returns a Validation that checks a value as a date.""" |
# NOTE: Not currently using format param
def check(val):
"""Checks that a value can be parsed as a date."""
if val is None:
return present_optional
else:
is_date, _ = util.try_parse_date(val)
return is_date
return Validation(check, property_name, 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 is_datetime(property_name, *, format=None, present_optional=False, message=None):
"""Returns a Validation that checks a value as a datetime.""" |
# NOTE: Not currently using format param
def check(val):
"""Checks that a value can be parsed as a datetime."""
if val is None:
return present_optional
else:
is_date, _ = util.try_parse_datetime(val)
return is_date
return Validation(check, property_name, 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 is_in(property_name, set_values, *, present_optional=False, message=None):
"""Returns a Validation that checks that a value is contained within a given set."... |
def check(val):
"""Checks that a value is contained within a scope-enclosed set."""
if val is None:
return present_optional
else:
return val in set_values
return Validation(check, property_name, 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 is_unique(keys, *, scope=None, comparison_operators=None, present_optional=False, message=None):
"""Returns a Validation that makes sure the given value is u... |
def check(pname, validator):
"""Checks that a value is unique in its column, with an optional scope."""
# pylint: disable=too-many-branches
model = validator.model
data_access = validator.data_access
pkname = model.primary_key_name
pkey = model.primary_key
if isinstance(k... |
<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(self, model, data_access=None, *, fail_fast=None):
"""Validates a model against the collection of Validations. Returns True if all Validations pass,... |
if fail_fast is None:
fail_fast = self.fail_fast
self.model = model
self.data_access = data_access
is_valid = True
for validation in self.validations:
if not validation.validate(model, self):
is_valid = False
if fail_fast:
break
return is_valid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configured_options(self):
"""What are the configured options in the git repo.""" |
stdout_lines = self._check_output(['config', '--list']).splitlines()
return {key: value for key, value in [line.split('=') for line in stdout_lines]} |
<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_es_action_item(data_item, action_settings, es_type, id_field=None):
''' This method will return an item formated and ready to append
to the action list '''
action_item = dict.copy(action_settings)
if id_field is not None:
id_val = first(list(get_dict_key(data_item, id_field)))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def es_field_sort(fld_name):
""" Used with lambda to sort fields """ |
parts = fld_name.split(".")
if "_" not in parts[-1]:
parts[-1] = "_" + parts[-1]
return ".".join(parts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_routes(app):
""" list of route of an app """ |
_routes = []
for rule in app.url_map.iter_rules():
_routes.append({
'path': rule.rule,
'name': rule.endpoint,
'methods': list(rule.methods)
})
return jsonify({'routes': _routes}) |
<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_input_type(self, type_or_parse):
""" Set an unique input type. If you use this then you have only one input for the play. """ |
self._inputs = OrderedDict()
default_inputs = self.engine.in_name
if len(default_inputs) > 1:
raise ValueError("Need more than one input, you sould use `add_input` for each of them")
self.add_input(default_inputs[0], type_or_parse) |
<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_input(self, in_name, type_or_parse=None):
""" Declare a possible input """ |
if type_or_parse is None:
type_or_parse = GenericType()
elif not isinstance(type_or_parse, GenericType) and callable(type_or_parse):
type_or_parse = GenericType(parse=type_or_parse)
elif not isinstance(type_or_parse, GenericType):
raise ValueError("the given ... |
<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_outputs(self, *outputs):
""" Set the outputs of the view """ |
self._outputs = OrderedDict()
for output in outputs:
out_name = None
type_or_serialize = None
if isinstance((list, tuple), output):
if len(output) == 1:
out_name = output[0]
elif len(output) == 2:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_output(self, out_name, type_or_serialize=None, **kwargs):
""" Declare an output """ |
if out_name not in self.engine.all_outputs():
raise ValueError("'%s' is not generated by the engine %s" % (out_name, self.engine.all_outputs()))
if type_or_serialize is None:
type_or_serialize = GenericType()
if not isinstance(type_or_serialize, GenericType) and callable... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def options(self):
""" Engine options discover HTTP entry point """ |
#configure engine with an empty dict to ensure default selection/options
self.engine.configure({})
conf = self.engine.as_dict()
conf["returns"] = [oname for oname in six.iterkeys(self._outputs)]
# Note: we overide args to only list the ones that are declared in this view
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def init_stream_from_settings(cfg: dict) -> Stream: """ Shortcut to create Stream from configured settings. Will definitely fail if there is no meaningful c... |
cfg_name = cfg["active_stream"]
stream_init_kwargs = cfg["streams"][cfg_name]
stream = Stream(**stream_init_kwargs)
await stream.connect()
_stream_storage.push(cfg_name, stream)
return stream |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpret(self, infile):
""" Process a file of rest and return list of dicts """ |
data = []
for record in self.generate_records(infile):
data.append(record)
return 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 read_profile(name):
"""Get a named profile from the CONFIG_FILE. Args: name The name of the profile to load. Returns: A dictionary with the profile's ``repo`... |
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
profile = config[name]
repo = profile["repo"]
token = profile["token"]
return {"repo": repo, "token": token} |
<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_profile(name, repo, token):
"""Save a profile to the CONFIG_FILE. After you use this method to save a profile, you can load it anytime later with the `... |
make_sure_folder_exists(CONFIG_FOLDER)
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
profile = {"repo": repo, "token": token}
config[name] = profile
with open(CONFIG_FILE, "w") as configfile:
config.write(configfile)
return profile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requirements(fname):
""" Utility function to create a list of requirements from the output of the pip freeze command saved in a text file. """ |
packages = Setup.read(fname, fail_silently=True).split('\n')
packages = (p.strip() for p in packages)
packages = (p for p in packages if p and not p.startswith('#'))
return list(packages) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_parser():
""" Returns an argparse.ArgumentParser instance to parse the command line arguments for lk """ |
import argparse
description = "A programmer's search tool, parallel and fast"
parser = argparse.ArgumentParser(description=description)
parser.add_argument('pattern', metavar='PATTERN', action='store',
help='a python re regular expression')
parser.add_argument('--ignore-case... |
<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_file_contents(path, binary=False):
""" Return the contents of the text file at path. If it is a binary file,raise an IOError """ |
# if this isn't a text file, we should raise an IOError
f = open(path, 'r')
file_contents = f.read()
f.close()
if not binary and file_contents.find('\000') >= 0:
raise IOError('Expected text file, got binary file')
return file_contents |
<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():
""" if lk.py is run as a script, this function will run """ |
parser = build_parser()
args = parser.parse_args()
flags = re.LOCALE
if args.dot_all:
flags |= re.DOTALL
if args.ignorecase:
flags |= re.IGNORECASE
if args.unicode:
flags |= re.UNICODE
if args.multiline:
flags |= re.MULTILINE
exclude_path_flags = 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 enqueue_directory(self, directory):
""" add a search of the directory to the queue """ |
exclude_path_regexes = self.exclude_path_regexes[:]
if not self.search_hidden:
exclude_path_regexes.append(self.hidden_file_regex)
else:
exclude_path_regexes.remove(self.hidden_file_regex)
self.mark = datetime.datetime.now()
def is_path_excluded(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 search_worker(self, regex, directory_path, names, binary=False, callback=None):
""" build a DirectoryResult for the given regex, directory path, and file nam... |
try:
result = DirectoryResult(directory_path)
def find_matches(name):
full_path = path.join(directory_path, name)
file_contents = get_file_contents(full_path, binary)
start = 0
match = regex.search(file_contents, start)
... |
<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_result(self, directory_result):
""" Print out the contents of the directory result, using ANSI color codes if supported """ |
for file_name, line_results_dict in directory_result.iter_line_results_items():
full_path = path.join(directory_result.directory_path, file_name)
self.write(full_path, 'green')
self.write('\n')
for line_number, line_results in sorted(line_results_dict.items()):
... |
<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_or_get_from_request(request):
"""Returns `RequestInfo` instance. If object was already created during ``request`` it is returned. Otherwise new instan... |
saved = getattr(request, REQUEST_CACHE_FIELD, None)
if isinstance(saved, RequestInfo):
return saved
req = RequestInfo()
req.user_ip = request.META.get('REMOTE_ADDR')
req.user_host = request.META.get('REMOTE_HOST')
req.user_agent = request.META.get('HTTP_USER_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def materialize(self):
"""Returns instance of ``TrackedModel`` created from current ``History`` snapshot. To rollback to current snapshot, simply call ``save`` o... |
if self.action_type == ActionType.DELETE:
# On deletion current state is dumped to change_log
# so it's enough to just restore it to object
data = serializer.from_json(self.change_log)
obj = serializer.restore_model(self._tracked_model, data)
return o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_plugin_disabled(plugin):
""" Determines if provided plugin is disabled from running for the active task. """ |
item = _registered.get(plugin.name)
if not item:
return False
_, props = item
return bool(props.get('disabled')) |
<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_events(plugin):
""" Handles setup or teardown of event hook registration for the provided plugin. `plugin` ``Plugin`` class. """ |
events = plugin.events
if events and isinstance(events, (list, tuple)):
for event in [e for e in events if e in _EVENT_VALS]:
register('event', event, plugin) |
<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_options(plugin):
""" Handles setup or teardown of option hook registration for the provided plugin. `plugin` ``Plugin`` class. """ |
options = plugin.options
if options and isinstance(options, (list, tuple)):
for props in options:
if isinstance(props, dict):
if 'block' in props and 'options' in props: # block
block = props['block']
option_list = props['options']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(hook_type, key, plugin_cls, properties=None):
""" Handles registration of a plugin hook in the global registries. `hook_type` Type of hook to regist... |
def fetch_plugin():
""" This function is used as a lazy evaluation of fetching the
specified plugin. This is required, because at the time of
registration of hooks (metaclass creation), the plugin class won't
exist yet in the class namespace, which is required for the
... |
<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_sudo_access(plugin):
""" Injects a `run_root` method into the provided plugin instance that forks a shell command using sudo. Used for command plugin n... |
def run_root(self, command):
""" Executes a shell command as root.
`command`
Shell command string.
Returns boolean.
"""
try:
return not (common.shell_process('sudo ' + command) is None)
except KeyboardInterrupt: # user can... |
<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_registered(option_hooks=None, event_hooks=None, command_hooks=None, root_access=None, task_active=True):
""" Returns a generator of registered plugins ma... |
plugins = []
for _, item in _registered:
plugin, type_info = item
# filter out any task-specific plugins
if task_active:
if type_info.get('disabled'):
continue
else:
if plugin.options or plugin.task_only:
continue
... |
<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_command_hook(command, task_active=True):
""" Gets registered command ``Plugin`` instance for the provided command. `command` Command string registered to... |
plugin_obj = _command_hooks.get(command)
if plugin_obj:
if task_active or (not plugin_obj.options and
not plugin_obj.task_only):
if not _is_plugin_disabled(plugin_obj):
return plugin_obj
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 run_event_hooks(event, task):
""" Executes registered task event plugins for the provided event and task. `event` Name of the event to trigger for the plugin... |
# get chain of classes registered for this event
call_chain = _event_hooks.get(event)
if call_chain:
# lookup the associated class method for this event
event_methods = {
'task_start': 'on_taskstart',
'task_run': 'on_taskrun',
'task_end': 'on_taskend'
... |
<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_option_hooks(parser, disable_missing=True):
""" Executes registered plugins using option hooks for the provided ``SettingParser`` instance. `parser` ``Se... |
plugins = []
state = {} # state information
def _raise_error(msg, block):
""" Raises ``InvalidTaskConfig`` exception with given message.
"""
if block:
msg += u' (block: "{0}")'.format(block)
raise errors.InvalidTaskConfig(parser.filename, reason=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 _recursive_merge(dct, merge_dct, raise_on_missing):
# type: (Dict[str, Any], Dict[str, Any], bool) -> Dict[str, Any] """Recursive dict merge This modifies `d... |
for k, v in merge_dct.items():
if k in dct:
if isinstance(dct[k], dict) and isinstance(merge_dct[k], BaseMapping):
dct[k] = _recursive_merge(dct[k], merge_dct[k], raise_on_missing)
else:
dct[k] = merge_dct[k]
elif isinstance(dct, Extensible):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, config, raise_on_unknown_key=True):
# type: (Dict[str, Any], bool) -> None """Apply additional configuration from a dictionary This will look for... |
_recursive_merge(self._data, config, raise_on_unknown_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 apply_object(self, config_obj, apply_on=None):
"""Apply additional configuration from any Python object This will look for object attributes that exist in th... |
self._init_flat_pointers()
try:
config_obj_keys = vars(config_obj).keys() # type: Iterable[str]
except TypeError:
config_obj_keys = filter(lambda k: k[0] != '_', dir(config_obj))
for config_key in config_obj_keys:
if apply_on:
flat_k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_flat(self, config, namespace_separator='_', prefix=''):
# type: (Dict[str, Any], str, str) -> None """Apply additional configuration from a flattened d... |
self._init_flat_pointers()
for key_stack, (container, orig_key) in self._flat_pointers.items():
flat_key = '{prefix}{joined_key}'.format(prefix=prefix, joined_key=namespace_separator.join(key_stack))
if flat_key in config:
container[orig_key] = config[flat_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 cross(environment, book, row, sheet_source, column_source, column_key):
""" Returns a single value from a column from a different dataset, matching by the ke... |
a = book.sheets[sheet_source]
return environment.copy(a.get(**{column_key: row[column_key]})[column_source]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def column(environment, book, sheet_name, sheet_source, column_source, column_key):
""" Returns an array of values from column from a different dataset, ordered ... |
a = book.sheets[sheet_source]
b = book.sheets[sheet_name]
return environment.copy([a.get(**{column_key: row[column_key]})[column_source] for row in b.all()]) |
<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(input_file, output, format):
"""Converts an image file to a Leaflet map.""" |
try:
process_image(input_file, subfolder=output, ext=format)
except Exception as e:
sys.exit(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 with_lock(lock, func, *args, **kwargs):
"""A 'context manager' for performing operations requiring a lock. :param lock: A BasicLock instance :type lock: silv... |
d = lock.acquire()
def release_lock(result):
deferred = lock.release()
return deferred.addCallback(lambda x: result)
def lock_acquired(lock):
return defer.maybeDeferred(func, *args, **kwargs).addBoth(release_lock)
d.addCallback(lock_acquired)
return 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 koji_instance(config, message, instance=None, *args, **kw):
""" Particular koji instances You may not have even known it, but we have multiple instances of t... |
instance = kw.get('instance', instance)
if not instance:
return False
instances = [item.strip() for item in instance.split(',')]
return message['msg'].get('instance') in instances |
<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(self, value_id, name, value_class):
""" Factory function that creates a value. :param value_id: id of the value, used to reference the value within this ... |
item = value_class(
name,
value_id=self.controller.component_id + "." + value_id,
is_input=self.is_input,
index=self.count,
spine = self.controller.spine
)
#if self._inject and self.controller:
# setattr(self.controller, va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, name):
"""Decorator for registering a named function in the sesion logic. Args: name: str. Function name. func: obj. Parameterless function to... |
def decorator(func):
"""Inner decorator, not used directly.
Args:
func: obj. Parameterless function to register.
Returns:
func: decorated function.
"""
self.logic[name] = func
@wraps(func)
def ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_session_attributes(self):
"""Copies request attributes to response""" |
for key, value in six.iteritems(self.request.session.attributes):
self.response.sessionAttributes[key] = 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 dispatch(self):
"""Calls the matching logic function by request type or intent name.""" |
if self.request.request.type == 'IntentRequest':
name = self.request.request.intent.name
else:
name = self.request.request.type
if name in self.logic:
self.logic[name]()
else:
error = 'Unable to find a registered logic function named: {}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, body, url=None, sig=None):
"""Process request body given skill logic. To validate a request, both, url and sig are required. Attributes receive... |
self.request = RequestBody()
self.response = ResponseBody()
self.request.parse(body)
app_id = self.request.session.application.application_id
stamp = self.request.request.timestamp
if not self.valid.request(app_id, body, stamp, url, sig):
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 walk(self, filters: str=None, filter_type: type=None, pprint=False, depth=-1):
""" Iterate tree in pre-order wide-first search order :param filters: filter b... |
children = self.children()
if children is None:
children = []
res = []
if depth == 0:
return res
elif depth != -1:
depth -= 1
for child in children:
if isinstance(child, Formula):
tmp = child.walk(filters=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def red_workshift(request, message=None):
'''
Redirects to the base workshift page for users who are logged in
'''
if message:
messages.add_message(request, messages.ERROR, message)
return HttpResponseRedirect(reverse('workshift:view_semester')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _user_settings(self):
""" Resolve settings dict from django settings module. Validate that all the required keys are present and also that none of the remove... |
user_settings = getattr(settings, self._name, {})
if not user_settings and self._required:
raise ImproperlyConfigured("Settings file is missing dict options with name {}".format(self._name))
keys = frozenset(user_settings.keys())
required = self._required - keys
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, empty=False):
"""returns an independent copy of the current object.""" |
# Create an empty object
newobject = self.__new__(self.__class__)
if empty:
return
# And fill it !
for prop in ["_properties","_side_properties",
"_derived_properties","_build_properties"
]:
if 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 msg(self, message, *args, **kwargs):
"""Shortcut to send a message through the connection. This function sends the input message through the connection. A ta... |
target = kwargs.pop('target', None)
raw = kwargs.pop('raw', False)
if not target:
target = self.line.sender.nick if self.line.pm else \
self.line.target
if not raw:
kw = {
'm': self,
'b': chr(2),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def shell_run(cmd,
cin=None, cwd=None, timeout=10, critical=True, verbose=True):
'''
Runs a shell command within a controlled environment.
.. note:: |use_photon_m|
:param cmd: The command to run
* A string one would type into a console like \
:command:`git push -u origin... |
<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_timestamp(time=True, precice=False):
'''
What time is it?
:param time:
Append ``-%H.%M.%S`` to the final string.
:param precice:
Append ``-%f`` to the final string.
Is only recognized when `time` is set to ``True``
:returns:
A timestamp string of now in the f... |
<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_hostname():
'''
Determines the current hostname by probing ``uname -n``.
Falls back to ``hostname`` in case of problems.
|appteardown| if both failed (usually they don't but consider
this if you are debugging weird problems..)
:returns:
The hostname as string. Domain parts wil... |
<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_connection(self, verbose=False):
""" Initializes a new IMAP4_SSL connection to an email server.""" |
# Connect to server
hostname = self.configs.get('IMAP', 'hostname')
if verbose:
print('Connecting to ' + hostname)
connection = imaplib.IMAP4_SSL(hostname)
# Authenticate
username = self.configs.get('IMAP', 'username')
password = self.configs.get('I... |
<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_body(self, msg):
""" Extracts and returns the decoded body from an EmailMessage object""" |
body = ""
charset = ""
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# skip any text/plain (txt) attachments
if ctype == 'text/plain' and... |
<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_subject(self, msg):
"""Extracts the subject line from an EmailMessage object.""" |
text, encoding = decode_header(msg['subject'])[-1]
try:
text = text.decode(encoding)
# If it's already decoded, ignore error
except AttributeError:
pass
return text |
<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, conn, tmp, module_name, module_args, inject):
''' transfer the given module name, plus the async module, then run it '''
# shell and command module are the same
if module_name == 'shell':
module_name = 'command'
module_args += " #USE_SHELL"
(module... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getparams(self, param):
"""Get parameters which match with input param. :param Parameter param: parameter to compare with this parameters. :rtype: list """ |
return list(cparam for cparam in self.values() if cparam == param) |
<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():
""" Parse the arguments and use them to create a ExistCli object """ |
version = 'Python Exist %s' % __version__
arguments = docopt(__doc__, version=version)
ExistCli(arguments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_config(self):
""" Read credentials from the config file """ |
with open(self.config_file) as cfg:
try:
self.config.read_file(cfg)
except AttributeError:
self.config.readfp(cfg)
self.client_id = self.config.get('exist', 'client_id')
self.client_secret = self.config.get('exist', 'client_secret')
... |
<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_config(self, access_token):
""" Write credentials to the config file """ |
self.config.add_section('exist')
# TODO: config is reading 'None' as string during authorization, so clearing this out
# if no id or secret is set - need to fix this later
if self.client_id:
self.config.set('exist', 'client_id', self.client_id)
else:
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_resource(self, arguments):
""" Gets the resource requested in the arguments """ |
attribute_name = arguments['<attribute_name>']
limit = arguments['--limit']
page = arguments['--page']
date_min = arguments['--date_min']
date_max = arguments['--date_max']
# feed in the config we have, and let the Exist class figure out the best
# way to authen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(self, api_token=None, username=None, password=None):
""" Authorize a user using the browser and a CherryPy server, and write the resulting credenti... |
access_token = None
if username and password:
# if we have a username and password, go and collect a token
auth = ExistAuthBasic(username, password)
auth.authorize()
if auth.token:
access_token = auth.token['access_token']
elif a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_token(self, arguments):
""" Refresh a user's access token, using existing the refresh token previously received in the auth flow. """ |
new_access_token = None
auth = ExistAuth(self.client_id, self.client_secret)
resp = auth.refresh_token(self.access_token)
if auth.token:
new_access_token = auth.token['access_token']
print('OAuth token refreshed: %s' % new_access_token)
self.write_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 _version_find_existing():
"""Returns set of existing versions in this repository. This information is backed by previously used version tags in git. Availabl... |
_tool_run('git fetch origin -t')
git_tags = [x for x in (y.strip() for y in (_tool_run('git tag -l')
.stdout.split('\n'))) if x]
return {tuple(int(n) if n else 0 for n in m.groups())
for m in (_version_re.match(t) for t in git_tags) if 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 _git_enable_branch(desired_branch):
"""Enable desired branch name.""" |
preserved_branch = _git_get_current_branch()
try:
if preserved_branch != desired_branch:
_tool_run('git checkout ' + desired_branch)
yield
finally:
if preserved_branch and preserved_branch != desired_branch:
_tool_run('git checkout ' + preserved_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 mk_travis_config():
"""Generate configuration for travis.""" |
t = dedent("""\
language: python
python: 3.4
env:
{jobs}
install:
- pip install -r requirements/ci.txt
script:
- invoke ci_run_job $TOX_JOB
after_success:
coveralls
""")
jobs = [env for env in parseconfig(None, 'tox... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mkrelease(finish='yes', version=''):
"""Allocates the next version number and marks current develop branch state as a new release with the allocated version ... |
if not version:
version = _version_format(_version_guess_next())
if _git_get_current_branch() != 'release/' + version:
_tool_run('git checkout develop',
'git flow release start ' + version)
_project_patch_version(version)
_project_patch_changelog()
patched_files ... |
<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_allow_future(self):
""" Only superusers and users with the permission can edit the post. """ |
qs = self.get_queryset()
post_edit_permission = '{}.edit_{}'.format(
qs.model._meta.app_label, qs.model._meta.model_name
)
if self.request.user.has_perm(post_edit_permission):
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 update_changed_requirements():
""" Checks for changes in the requirements file across an update, and gets new requirements if changes have occurred. """ |
reqs_path = join(env.proj_path, env.reqs_path)
get_reqs = lambda: run("cat %s" % reqs_path, show=False)
old_reqs = get_reqs() if env.reqs_path else ""
yield
if old_reqs:
new_reqs = get_reqs()
if old_reqs == new_reqs:
# Unpinned requirements should always be checked.
... |
<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(command, show=True, *args, **kwargs):
""" Runs a shell comand on the remote server. """ |
if show:
print_command(command)
with hide("running"):
return _run(command, *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 sudo(command, show=True, *args, **kwargs):
""" Runs a command as sudo on the remote server. """ |
if show:
print_command(command)
with hide("running"):
return _sudo(command, *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 get_templates():
""" Returns each of the templates with env vars injected. """ |
injected = {}
for name, data in templates.items():
injected[name] = dict([(k, v % env) for k, v in data.items()])
return injected |
<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_template_and_reload(name):
""" Uploads a template only if it has changed, and if so, reload the related service. """ |
template = get_templates()[name]
local_path = template["local_path"]
if not os.path.exists(local_path):
project_root = os.path.dirname(os.path.abspath(__file__))
local_path = os.path.join(project_root, local_path)
remote_path = template["remote_path"]
reload_command = template.get("... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rsync_upload():
""" Uploads the project with rsync excluding some files and folders. """ |
excludes = ["*.pyc", "*.pyo", "*.db", ".DS_Store", ".coverage",
"local_settings.py", "/static", "/.git", "/.hg"]
local_dir = os.getcwd() + os.sep
return rsync_project(remote_dir=env.proj_path, local_dir=local_dir,
exclude=excludes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vcs_upload():
""" Uploads the project with the selected VCS tool. """ |
if env.deploy_tool == "git":
remote_path = "ssh://%s@%s%s" % (env.user, env.host_string,
env.repo_path)
if not exists(env.repo_path):
run("mkdir -p %s" % env.repo_path)
with cd(env.repo_path):
run("git init --bare")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def postgres(command):
""" Runs the given command as the postgres user. """ |
show = not command.startswith("psql")
return sudo(command, show=show, user="postgres") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def psql(sql, show=True):
""" Runs SQL against the project's database. """ |
out = postgres('psql -c "%s"' % sql)
if show:
print_command(sql)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backup(filename):
""" Backs up the project database. """ |
tmp_file = "/tmp/%s" % filename
# We dump to /tmp because user "postgres" can't write to other user folders
# We cd to / because user "postgres" might not have read permissions
# elsewhere.
with cd("/"):
postgres("pg_dump -Fc %s > %s" % (env.proj_name, tmp_file))
run("cp %s ." % tmp_fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def python(code, show=True):
""" Runs Python code in the project's virtual environment, with Django loaded. """ |
setup = "import os;" \
"os.environ[\'DJANGO_SETTINGS_MODULE\']=\'%s.settings\';" \
"import django;" \
"django.setup();" % env.proj_app
full_code = 'python -c "%s%s"' % (setup, code.replace("`", "\\\`"))
with project():
if show:
print_command(code)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install():
""" Installs the base system and Python requirements for the entire server. """ |
# Install system requirements
sudo("apt-get update -y -q")
apt("nginx libjpeg-dev python-dev python-setuptools git-core "
"postgresql libpq-dev memcached supervisor python-pip")
run("mkdir -p /home/%s/logs" % env.user)
# Install Python requirements
sudo("pip install -U pip virtualenv v... |
<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():
""" Blow away the current project. """ |
if exists(env.venv_path):
run("rm -rf %s" % env.venv_path)
if exists(env.proj_path):
run("rm -rf %s" % env.proj_path)
for template in get_templates().values():
remote_path = template["remote_path"]
if exists(remote_path):
sudo("rm %s" % remote_path)
if exists... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy():
""" Deploy latest version of the project. Backup current version of the project, push latest version of the project via version control or rsync, i... |
if not exists(env.proj_path):
if confirm("Project does not exist in host server: %s"
"\nWould you like to create it?" % env.proj_name):
create()
else:
abort()
# Backup current version of the project
with cd(env.proj_path):
backup("last.db"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback():
""" Reverts project state to the last deploy. When a deploy is performed, the current state of the project is backed up. This includes the projec... |
with update_changed_requirements():
if env.deploy_tool in env.vcs_tools:
with cd(env.repo_path):
if env.deploy_tool == "git":
run("GIT_WORK_TREE={0} git checkout -f "
"`cat {0}/last.commit`".format(env.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 delete_single(site, domain, delete_code=False, no_prompt=False):
""" Delete a single site @type site: Site @type domain: Domain @type delete_code: bool @type... |
click.secho('Deleting installation "{sn}" hosted on the domain {dn}'.format(sn=site.name, dn=domain.name),
fg='yellow', bold=True)
if not no_prompt:
if delete_code:
warn_text = click.style('WARNING! THIS WILL PERMANENTLY DELETE THIS SITE AND ALL OF THE ASSOCIATED '
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.