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 by_lookup(self, style_key, style_value):
"""Return a processor that extracts the style from `mapping`. Parameters style_key : str A style key. style_value : ... |
style_attr = style_key if self.style_types[style_key] is bool else None
mapping = style_value["lookup"]
def proc(value, result):
try:
lookup_value = mapping[value]
except (KeyError, TypeError):
# ^ TypeError is included in case the user 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 by_re_lookup(self, style_key, style_value, re_flags=0):
"""Return a processor for a "re_lookup" style value. Parameters style_key : str A style key. style_va... |
style_attr = style_key if self.style_types[style_key] is bool else None
regexps = [(re.compile(r, flags=re_flags), v)
for r, v in style_value["re_lookup"]]
def proc(value, result):
if not isinstance(value, six.string_types):
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 by_interval_lookup(self, style_key, style_value):
"""Return a processor for an "interval" style value. Parameters style_key : str A style key. style_value : ... |
style_attr = style_key if self.style_types[style_key] is bool else None
intervals = style_value["interval"]
def proc(value, result):
try:
value = float(value)
except TypeError:
return result
for start, end, lookup_value in in... |
<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_from_style(self, column_style):
"""Yield post-format processors based on `column_style`. Parameters column_style : dict A style where the top-level keys... |
flanks = Flanks()
yield flanks.split_flanks
fns = {"simple": self.by_key,
"lookup": self.by_lookup,
"re_lookup": self.by_re_lookup,
"interval": self.by_interval_lookup}
for key in self.style_types:
if key not in column_style:
... |
<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_flanks(self, _, result):
"""Return `result` without flanking whitespace. """ |
if not result.strip():
self.left, self.right = "", ""
return result
match = self.flank_re.match(result)
assert match, "This regexp should always match"
self.left, self.right = match.group(1), match.group(3)
return match.group(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 render(self, style_attr, value):
"""Prepend terminal code for `key` to `value`. Parameters style_attr : str A style attribute (e.g., "bold" or "blue"). value... |
if not value.strip():
# We've got an empty string. Don't bother adding any
# codes.
return value
return six.text_type(getattr(self.term, style_attr)) + 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 post_from_style(self, column_style):
"""A Terminal-specific reset to StyleProcessors.post_from_style. """ |
for proc in super(TermProcessors, self).post_from_style(column_style):
if proc.__name__ == "join_flanks":
# Reset any codes before adding back whitespace.
yield self._maybe_reset()
yield proc |
<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_subscribers(self):
"""Get per-instance subscribers from the signal. """ |
data = self.signal.instance_subscribers
if self.instance not in data:
data[self.instance] = MethodAwareWeakList()
return data[self.instance] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, cback, subscribers=None, instance=None):
"""Add a function or a method as an handler of this signal. Any handler added can be a coroutine. :par... |
if subscribers is None:
subscribers = self.subscribers
# wrapper
if self._fconnect is not None:
def _connect(cback):
self._connect(subscribers, cback)
notify = partial(self._notify_one, instance)
if instance 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 disconnect(self, cback, subscribers=None, instance=None):
"""Remove a previously added function or method from the set of the signal's handlers. :param cback... |
if subscribers is None:
subscribers = self.subscribers
# wrapper
if self._fdisconnect is not None:
def _disconnect(cback):
self._disconnect(subscribers, cback)
notify = partial(self._notify_one, instance)
if instance 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 ext_publish(self, instance, loop, *args, **kwargs):
"""If 'external_signaller' is defined, calls it's publish method to notify external event systems. This i... |
if self.external_signaller is not None:
# Assumes that the loop is managed by the external handler
return self.external_signaller.publish_signal(self, instance, loop,
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 configure_logging( filename=None, filemode="a", datefmt=FMT_DATE, fmt=FMT, stdout_fmt=FMT_STDOUT, level=logging.DEBUG, stdout_level=logging.WARNING, initial_f... |
logger = logging.getLogger()
logger.level = logging.NOTSET
# Remove all handlers
if remove_handlers:
while len(logger.handlers) > 0:
hdlr = logger.handlers[0]
hdlr.close()
logger.removeHandler(hdlr)
# Create stdout handler
if stdout_level 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 create_plan(existing_users=None, proposed_users=None, purge_undefined=None, protected_users=None, allow_non_unique_id=None, manage_home=True, manage_keys=True... |
plan = list()
proposed_usernames = list()
if not purge_undefined:
purge_undefined = constants.PURGE_UNDEFINED
if not protected_users:
protected_users = constants.PROTECTED_USERS
if not allow_non_unique_id:
allow_non_unique_id = constants.ALLOW_NON_UNIQUE_ID
# Create l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_plan(plan=None):
"""Create, Modify or Delete, depending on plan item.""" |
execution_result = list()
for task in plan:
action = task['action']
if action == 'delete':
command = generate_delete_user_command(username=task.get('username'), manage_home=task['manage_home'])
command_output = execute_command(command)
execution_result.append... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs):
"... |
var_name = self.get_env_var_name(variable_path)
val = self.env.get(var_name, self.sentinel)
if val is self.sentinel:
return default
# coerce to bool with default env coercer if no coercer specified
if coerce_type and coerce_type is bool and not coercer:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unzip(archive, destination, filenames=None):
"""Unzip a zip archive into destination directory. It unzips either the whole archive or specific file(s) from t... |
close = False
try:
if not isinstance(archive, zipfile.ZipFile):
archive = zipfile.ZipFile(archive, "r", allowZip64=True)
close = True
logger.info("Extracting: %s -> %s" % (archive.filename, destination))
if isinstance(filenames, str):
filenames = [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 mkzip(archive, items, mode="w", save_full_paths=False):
"""Recursively zip a directory. Args: archive (zipfile.ZipFile or str):
ZipFile object add to or pat... |
close = False
try:
if not isinstance(archive, zipfile.ZipFile):
archive = zipfile.ZipFile(archive, mode, allowZip64=True)
close = True
logger.info("mkdzip: Creating %s, from: %s", archive.filename, items)
if isinstance(items, str):
items = [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 seven_zip(archive, items, self_extracting=False):
"""Create a 7z archive.""" |
if not isinstance(items, (list, tuple)):
items = [items]
if self_extracting:
return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items)
else:
return er(_get_sz(), "a", "-ssw", archive, *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 migrate(*argv) -> bool: """ Runs Django migrate command. :return: always ``True`` """ |
wf('Applying migrations... ', False)
execute_from_command_line(['./manage.py', 'migrate'] + list(argv))
wf('[+]\n')
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 output(self, output, accepts, set_http_code, set_content_type):
""" Formats a response from a WSGI app to handle any RDF graphs If a view function retur... |
graph = Decorator._get_graph(output)
if graph is not None:
# decide the format
output_mimetype, output_format = self.format_selector.decide(accepts, graph.context_aware)
# requested content couldn't find anything
if output_mimetype is None:
set_http_code("406 Not Acceptable")
return ['406 Not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorate(self, app):
""" Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred... |
from functools import wraps
@wraps(app)
def decorated(environ, start_response):
# capture any start_response from the app
app_response = {}
app_response['status'] = "200 OK"
app_response['headers'] = []
app_response['written'] = BytesIO()
def custom_start_response(status, headers, *args, **kwa... |
<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_handler(cls, name, value):
"""Detect an handler and return its wanted signal name.""" |
signal_name = False
config = None
if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME):
spec = getattr(value, SPEC_CONTAINER_MEMBER_NAME)
if spec['kind'] == 'handler':
signal_name = spec['name']
config = spec['... |
<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_inheritance_chain(cls, bases, *names, merge=False):
"""For all of the names build a ChainMap containing a map for every base class.""" |
result = []
for name in names:
maps = []
for base in bases:
bmap = getattr(base, name, None)
if bmap is not None:
assert isinstance(bmap, (dict, ChainMap))
if len(bmap):
if isinstance... |
<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_instance_handler_mapping(cls, instance, handle_d):
"""For every unbound handler, get the bound version.""" |
res = {}
for member_name, sig_name in handle_d.items():
if sig_name in res:
sig_handlers = res[sig_name]
else:
sig_handlers = res[sig_name] = []
sig_handlers.append(getattr(instance, member_name))
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 _check_local_handlers(cls, signals, handlers, namespace, configs):
"""For every marked handler, see if there is a suitable signal. If not, raise an error.""" |
for aname, sig_name in handlers.items():
# WARN: this code doesn't take in account the case where a new
# method with the same name of an handler in a base class is
# present in this class but it isn't an handler (so the handler
# with the same name should be rem... |
<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_class_handlers(cls, signal_name, instance):
"""Returns the handlers registered at class level. """ |
handlers = cls._signal_handlers_sorted[signal_name]
return [getattr(instance, hname) for hname in handlers] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sort_handlers(cls, signals, handlers, configs):
"""Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain t... |
def macro_precedence_sorter(flags, hname):
"""The default is to sort 'bottom_up', with lower level getting
executed first, but sometimes you need them reversed."""
data = configs[hname]
topdown_sort = SignalOptions.SORT_TOPDOWN in flags
if topdown_sor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance_signals_and_handlers(cls, instance):
"""Calculate per-instance signals and handlers.""" |
isignals = cls._signals.copy()
ihandlers = cls._build_instance_handler_mapping(
instance,
cls._signal_handlers
)
return isignals, ihandlers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def __insert(self, key, value):
'''
Insert a new key to database
'''
if key in self:
getLogger().warning("Cache entry exists, cannot insert a new entry with key='{key}'".format(key=key))
return False
with self.get_conn() as conn:
try:
... |
<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(self, key):
''' Delete file key from database
'''
with self.get_conn() as conn:
try:
c = conn.cursor()
c.execute("DELETE FROM cache_entries WHERE key = ?", (key,))
conn.commit()
except:
getLogger... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize(self, rows):
"""Return summary rows for `rows`. Parameters rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary row... |
columns = list(rows[0].keys())
agg_styles = {c: self.style[c]["aggregate"]
for c in columns if "aggregate" in self.style[c]}
summaries = {}
for col, agg_fn in agg_styles.items():
lgr.debug("Summarizing column %r with %r", col, agg_fn)
colva... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init(self, style, streamer, processors=None):
"""Do writer-specific setup. Parameters style : dict Style, as passed to __init__. streamer : interface.Stream... |
self._stream = streamer
if streamer.interactive:
if streamer.supports_updates:
self.mode = "update"
else:
self.mode = "incremental"
else:
self.mode = "final"
if style and "width_" not in style and self._stream.width:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ids(self):
"""A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name. """ |
if self._ids is None:
if self._columns:
if isinstance(self._columns, OrderedDict):
return [list(self._columns.keys())[0]]
return [self._columns[0]]
else:
return self._ids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait(self):
"""Wait for asynchronous calls to return. """ |
if self._pool is None:
return
self._pool.close()
self._pool.join() |
<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_lock(self):
"""Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that m... |
if self._lock:
lgr.debug("Acquiring write lock")
self._lock.acquire()
try:
yield
finally:
if self._lock:
lgr.debug("Releasing write lock")
self._lock.release() |
<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_callables(self, row, callables):
"""Start running `callables` asynchronously. """ |
id_vals = {c: row[c] for c in self.ids}
def callback(tab, cols, result):
if isinstance(result, Mapping):
pass
elif isinstance(result, tuple):
result = dict(zip(cols, result))
elif len(cols) == 1:
# Don't bother raising... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tables(self):
""" Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on conn... |
if self.schema:
return self.tables_in_schema(self.schema)
else:
tables = []
for schema in self.schemas:
tables = tables + [
schema + "." + t for t in self.tables_in_schema(schema)
]
return tables |
<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_query(self, sql, lookup):
""" Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it m... |
for key, val in six.iteritems(lookup):
sql = sql.replace("$" + key, val)
return sql |
<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_table_name(self, table):
"""Parse schema qualified table name """ |
if "." in table:
schema, table = table.split(".")
else:
schema = None
return (schema, table) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_table(self, table):
"""Loads a table. Returns None if the table does not already exist in db """ |
table = self._valid_table_name(table)
schema, table = self.parse_table_name(table)
if not schema:
schema = self.schema
tables = self.tables
else:
tables = self.tables_in_schema(schema)
if table in tables:
return Table(self, schema,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mogrify(self, sql, params):
"""Return the query string with parameters added """ |
conn = self.engine.raw_connection()
cursor = conn.cursor()
return cursor.mogrify(sql, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, sql, params=None):
"""Just a pointer to engine.execute """ |
# wrap in a transaction to ensure things are committed
# https://github.com/smnorris/pgdata/issues/3
with self.engine.begin() as conn:
result = conn.execute(sql, params)
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 query_one(self, sql, params=None):
"""Grab just one record """ |
r = self.engine.execute(sql, params)
return r.fetchone() |
<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_schema(self, schema):
"""Create specified schema if it does not already exist """ |
if schema not in self.schemas:
sql = "CREATE SCHEMA " + schema
self.execute(sql) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_schema(self, schema, cascade=False):
"""Drop specified schema """ |
if schema in self.schemas:
sql = "DROP SCHEMA " + schema
if cascade:
sql = sql + " CASCADE"
self.execute(sql) |
<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_table(self, table, columns):
"""Creates a table """ |
schema, table = self.parse_table_name(table)
table = self._valid_table_name(table)
if not schema:
schema = self.schema
if table in self.tables:
return Table(self, schema, table)
else:
return Table(self, schema, table, columns) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ogr2pg( self, in_file, in_layer=None, out_layer=None, schema="public", s_srs=None, t_srs="EPSG:3005", sql=None, dim=2, cmd_only=False, index=True ):
""" Load... |
# if not provided a layer name, use the name of the input file
if not in_layer:
in_layer = os.path.splitext(os.path.basename(in_file))[0]
if not out_layer:
out_layer = in_layer.lower()
command = [
"ogr2ogr",
"-t_srs",
t_srs,
... |
<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_logging(filename, log_dir=None, force_setup=False):
''' Try to load logging configuration from a file. Set level to INFO if failed.
'''
if not force_setup and ChirpCLI.SETUP_COMPLETED:
logging.debug("Master logging has been setup. This call will be ignored.")
return
if log_dir ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def config_logging(args):
''' Override root logger's level '''
if args.quiet:
logging.getLogger().setLevel(logging.CRITICAL)
elif args.verbose:
logging.getLogger().setLevel(logging.DEBUG) |
<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_task(self, task, func=None, **kwargs):
''' Add a task parser '''
if not self.__tasks:
raise Exception("Tasks subparsers is disabled")
if 'help' not in kwargs:
if func.__doc__:
kwargs['help'] = func.__doc__
task_parser = self.__tasks.add_par... |
<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_vq(self, parser):
''' Add verbose & quiet options '''
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_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 run(self, func=None):
''' Run the app '''
args = self.parser.parse_args()
if self.__add_vq is not None and self.__config_logging:
self.__config_logging(args)
if self.__show_version_func and args.version and callable(self.__show_version_func):
self.__show_versi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def header(*msg, level='h1', separator=" ", print_out=print):
''' Print header block in text mode
'''
out_string = separator.join(str(x) for x in msg)
if level == 'h0':
# box_len = 80 if len(msg) < 80 else len(msg)
box_len = 80
print_out('+' + '-' * (box_len + 2))
print_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 fetch(self, value_obj=None):
''' Fetch the next two values '''
val = None
try:
val = next(self.__iterable)
except StopIteration:
return None
if value_obj is None:
value_obj = Value(value=val)
else:
value_obj.value = 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 content(self):
''' Return report content as a string if mode == STRINGIO else an empty string '''
if isinstance(self.__report_file, io.StringIO):
return self.__report_file.getvalue()
else:
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 format(self):
''' Format table to print out
'''
self.max_lengths = []
for row in self.rows:
if len(self.max_lengths) < len(row):
self.max_lengths += [0] * (len(row) - len(self.max_lengths))
for idx, val in enumerate(row):
len_ce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def replace_name(file_path, new_name):
''' Change the file name in a path but keep the extension '''
if not file_path:
raise Exception("File path cannot be empty")
elif not new_name:
raise Exception("New name cannot be empty")
dirname = os.path.dirname(file_path)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_child_folders(path):
''' Get all child folders of a folder '''
path = FileHelper.abspath(path)
return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))] |
<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_child_files(path):
''' Get all child files of a folder '''
path = FileHelper.abspath(path)
return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))] |
<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_file(filepath):
''' Delete a file '''
try:
os.remove(os.path.abspath(os.path.expanduser(filepath)))
except OSError as e:
if e.errno != errno.ENOENT:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _ptn2fn(self, pattern):
''' Pattern to filename '''
return [pattern.format(wd=self.working_dir, n=self.__name, mode=self.__mode),
pattern.format(wd=self.working_dir, n='{}.{}'.format(self.__name, self.__mode), mode=self.__mode)] |
<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_potential(self, *patterns):
''' Add a potential config file pattern '''
for ptn in patterns:
self.__potential.extend(self._ptn2fn(ptn)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def locate_config(self):
''' Locate config file '''
for f in self.__potential:
f = FileHelper.abspath(f)
if os.path.isfile(f):
return f
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 config(self):
''' Read config automatically if required '''
if self.__config is None:
config_path = self.locate_config()
if config_path:
self.__config = self.read_file(config_path)
self.__config_path = config_path
return self.__config |
<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_file(self, file_path):
''' Read a configuration file and return configuration data '''
getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path))
if self.__mode == AppConfig.JSON:
return json.loads(FileHelper.read(file_path), object_pairs_hook=Ord... |
<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, file_path):
''' Load configuration from a specific file '''
self.clear()
self.__config = self.read_file(file_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_and_report(command, *args, **kwargs):
"""Execute a command with arguments and wait for output.
If execution was successful function will return T... |
logging.info("Execute: %s %s" % (command, " ".join(args)))
try:
status, out, err = execute(command, *args, **kwargs)
if status == 0:
logging.info(
"%s Finished successfully. Exit Code: 0.",
os.path.basename(command),
)
... |
<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_authorized_keys(username=None):
"""Read public keys from specified user's authorized_keys file. args: username (str):
username. returns: list: Authoris... |
authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.format(username)))
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(username, rnd_chars)
authorized_keys = list()
copy_result = execute_command... |
<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_authorized_keys(user=None):
"""Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User):
I... |
authorized_keys = list()
authorized_keys_dir = '{0}/.ssh'.format(os.path.expanduser('~{0}'.format(user.name)))
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
authorized_keys_path = '{0}/authorized_keys'.format(authorized_keys_dir)
tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def b64encoded(self):
"""Return a base64 encoding of the key. returns: str: base64 encoding of the public key """ |
if self._b64encoded:
return text_type(self._b64encoded).strip("\r\n")
else:
return base64encode(self.raw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw(self):
"""Return raw key. returns: str: raw key """ |
if self._raw:
return text_type(self._raw).strip("\r\n")
else:
return text_type(base64decode(self._b64encoded)).strip("\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 get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs):
"... |
return self.inner_parser.get(
variable_path,
default=default,
coerce_type=coerce_type,
coercer=coercer,
**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_default_mimetype(self):
""" Returns the default mimetype """ |
mimetype = self.default_mimetype
if mimetype is None: # class inherits from module default
mimetype = DEFAULT_MIMETYPE
if mimetype is None: # module is set to None?
mimetype = 'application/rdf+xml'
return mimetype |
<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_serialize_format(self, mimetype):
""" Get the serialization format for the given mimetype """ |
format = self.formats.get(mimetype, None)
if format is None:
format = formats.get(mimetype, None)
return format |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wants_rdf(self, accepts):
""" Returns whether this client's Accept header indicates that the client wants to receive RDF """ |
mimetype = mimeparse.best_match(all_mimetypes + self.all_mimetypes + [WILDCARD], accepts)
return mimetype and mimetype != WILDCARD |
<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 send_http(session, method, url, *, retries=1, interval=1, backoff=2, http_status_codes_to_retry=HTTP_STATUS_CODES_TO_RETRY, fn=lambda x:x, **kwargs):
"... |
backoff_interval = interval
raised_exc = None
attempt = 0
if method not in ['get', 'patch', 'post']:
raise ValueError
if retries == -1: # -1 means retry indefinitely
attempt = -1
elif retries == 0: # Zero means don't retry
attempt = 1
else: # any other value mea... |
<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_missing_commands(_platform):
"""Check I can identify the necessary commands for managing users.""" |
missing = list()
if _platform in ('Linux', 'OpenBSD'):
if not LINUX_CMD_USERADD:
missing.append('useradd')
if not LINUX_CMD_USERMOD:
missing.append('usermod')
if not LINUX_CMD_USERDEL:
missing.append('userdel')
if not LINUX_CMD_GROUP_ADD:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_command(command=None):
"""Execute a command and return the stdout and stderr.""" |
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stdin = process.communicate()
process.wait()
return (stdout, stdin), process.returncode |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base64encode(_input=None):
"""Return base64 encoded representation of a string.""" |
if PY2: # pragma: no cover
return base64.b64encode(_input)
elif PY3: # pragma: no cover
if isinstance(_input, bytes):
return base64.b64encode(_input).decode('UTF-8')
elif isinstance(_input, str):
return base64.b64encode(bytearray(_input, encoding='UTF-8')).deco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base64decode(_input=None):
"""Take a base64 encoded string and return the decoded string.""" |
missing_padding = 4 - len(_input) % 4
if missing_padding:
_input += '=' * missing_padding
if PY2: # pragma: no cover
return base64.decodestring(_input)
elif PY3: # pragma: no cover
if isinstance(_input, bytes):
return base64.b64decode(_input).decode('UTF-8')
... |
<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_sudoers():
""" Read the sudoers entry for the specified user. args: username (str):
username. returns:`r str: sudoers entry for the specified user. """ |
sudoers_path = '/etc/sudoers'
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
tmp_sudoers_path = '/tmp/sudoers_{0}'.format(rnd_chars)
sudoers_entries = list()
copy_result = execute_command(
shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), sudoers_path, tmp_sudoers_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 write_sudoers_entry(username=None, sudoers_entry=None):
"""Write sudoers entry. args: user (User):
Instance of User containing sudoers entry. returns: str: ... |
sudoers_path = '/etc/sudoers'
rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
tmp_sudoers_path = '/tmp/sudoers_{0}'.format(rnd_chars)
execute_command(
shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), sudoers_path, tmp_sudoers_path))))
execute_command(
shlex.split(str(... |
<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_sudoers_entry(username=None, sudoers_entries=None):
""" Find the sudoers entry in the sudoers file for the specified user. args: username (str):
usernam... |
for entry in sudoers_entries:
if entry.startswith(username):
return entry.replace(username, '').strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def docstring(documentation, prepend=False, join=""):
r"""Prepend or append a string to the current documentation of the function. This decorator should be robus... |
def decorator(func):
current = (func.__doc__ if func.__doc__ else "").strip()
doc = documentation.strip()
new = "\n".join(
[doc, join, current] if prepend else [current, join, doc]
)
lines = len(new.strip().splitlines())
if lines == 1:
# 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 run_gunicorn(application: WSGIHandler, gunicorn_module_name: str = 'gunicorn_prod'):
""" Runs gunicorn with a specified config. :param application: Django uw... |
from gunicorn.app.base import Application
class DjangoApplication(Application):
def init(self, parser, opts, args):
cfg = self.get_config_from_module_name(gunicorn_module_name)
clean_cfg = {}
for k, v in cfg.items():
# Ignore unknown names
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _colorize_single_line(line, regexp, color_def):
"""Print single line to console with ability to colorize parts of it.""" |
match = regexp.match(line)
groupdict = match.groupdict()
groups = match.groups()
if not groupdict:
# no named groups, just colorize whole line
color = color_def[0]
dark = color_def[1]
cprint("%s\n" % line, color, fg_dark=dark)
else:
rev_groups = {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 height(self):
"""Terminal height. """ |
if self.interactive:
if self._height is None:
self._height = self.term.height
return self._height |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_last_lines(self, n):
"""Clear last N lines of terminal output. """ |
self.term.stream.write(
self.term.move_up * n + self.term.clear_eos)
self.term.stream.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def overwrite_line(self, n, text):
"""Move back N lines and overwrite line with `text`. """ |
with self._moveback(n):
self.term.stream.write(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 move_to(self, n):
"""Move back N lines in terminal. """ |
self.term.stream.write(self.term.move_up * n) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, required: boo... |
for p in self.parsers:
try:
val = p.get(
variable_path, default=self.sentinel,
coerce_type=coerce_type, coercer=coercer,
**kwargs
)
if val != self.sentinel:
self.enqueue(... |
<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_config_read_queue(self, use_color: bool = False, max_col_width: int = 50) -> str: """ Prepares a string with pretty printed config read queue. :param u... |
try:
from terminaltables import SingleTable
except ImportError:
import warnings
warnings.warn('Cannot display config read queue. Install terminaltables first.')
return ''
col_names_order = ['path', 'value', 'type', 'parser']
pretty_bundle... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_graph(cls, response):
""" Given a Flask response, find the rdflib Graph """ |
if cls.is_graph(response): # single graph object
return response
if hasattr(response, '__getitem__'): # indexable tuple
if len(response) > 0 and \
cls.is_graph(response[0]): # graph object
return response[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 replace_graph(cls, response, serialized):
""" Replace the rdflib Graph in a Flask response """ |
if cls.is_graph(response): # single graph object
return serialized
if hasattr(response, '__getitem__'): # indexable tuple
if len(response) > 0 and \
cls.is_graph(response[0]): # graph object
return (serialized,) + response[1:]
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_hex_digest(digest):
"""Convert hex digest to sequence of bytes.""" |
return "".join(
[chr(int(digest[x : x + 2], 16)) for x in range(0, len(digest), 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 encrypt(data, digest=True):
"""Perform encryption of provided data.""" |
alg = get_best_algorithm()
enc = implementations["encryption"][alg](
data, implementations["get_key"]()
)
return "%s$%s" % (alg, (_to_hex_digest(enc) if digest else enc)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(data, digest=True):
"""Decrypt provided data.""" |
alg, _, data = data.rpartition("$")
if not alg:
return data
data = _from_hex_digest(data) if digest else data
try:
return implementations["decryption"][alg](
data, implementations["get_key"]()
)
except KeyError:
raise CryptError("Can not decrypt key for 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 gen_vocab(cli, args):
''' Generate vocabulary list from a tokenized file '''
if args.topk and args.topk <= 0:
topk = None
cli.logger.warning("Invalid k will be ignored (k should be greater than or equal to 1)")
else:
topk = args.topk
if args.stopwords:
with open(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 main():
''' ChirpText Tools main function '''
app = CLIApp(desc='ChirpText Tools', logger=__name__, show_version=show_version)
# add tasks
vocab_task = app.add_task('vocab', func=gen_vocab)
vocab_task.add_argument('input', help='Input file')
vocab_task.add_argument('--output', help='Output 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 add_attachment(message, attachment, rfc2231=True):
'''Attach an attachment to a message as a side effect.
Arguments:
message: MIMEMultipart instance.
attachment: Attachment instance.
'''
data = attachment.read()
part = MIMEBase('application', 'octet-stream')
part.set_payloa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.