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 get_work_unit_status(self, work_spec_name, work_unit_key):
'''Get a high-level status for some work unit.
The return value is a dictionary. The only required key is
``status``, which could be any of:
``missing``
The work unit does not exist anywhere
``available``
The work unit is available for new workers; additional
keys include ``expiration`` (may be 0)
``pending``
The work unit is being worked on; additional keys include
``expiration`` and ``worker_id`` (usually)
``blocked``
The work unit is waiting for some other work units to finish;
additional keys include ``depends_on``
``finished``
The work unit has completed
``failed``
The work unit failed; additional keys include ``traceback``
:param str work_spec_name: name of the work spec
:param str work_unit_name: name of the work unit
:return: dictionary description of summary status
'''
with self.registry.lock(identifier=self.worker_id) as session:
# In the available list?
(unit,priority) = session.get(WORK_UNITS_ + work_spec_name,
work_unit_key, include_priority=True)
if unit:
result = {}
if priority < time.time():
result['status'] = 'available'
else:
result['status'] = 'pending'
result['expiration'] = priority
# ...is anyone working on it?
worker = session.get(WORK_UNITS_ + work_spec_name + "_locks",
work_unit_key)
if worker:
result['worker_id'] = worker
return result
# In the finished list?
unit = session.get(WORK_UNITS_ + work_spec_name + _FINISHED,
work_unit_key)
if unit:
return { 'status': 'finished' }
# In the failed list?
unit = session.get(WORK_UNITS_ + work_spec_name + _FAILED,
work_unit_key)
if unit:
result = { 'status': 'failed' }
if 'traceback' in unit:
result['traceback'] = unit['traceback']
return result
# In the blocked list?
unit = session.get(WORK_UNITS_ + work_spec_name + _BLOCKED,
work_unit_key)
if unit:
# This should always have *something*, right?
deps = session.get(WORK_UNITS_ + work_spec_name + _DEPENDS,
work_unit_key, default=[])
result = { 'status': 'blocked',
'depends_on': deps }
return result
return { 'status': 'missing' } |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inspect_work_unit(self, work_spec_name, work_unit_key):
'''Get the data for some work unit.
Returns the data for that work unit, or `None` if it really
can't be found.
:param str work_spec_name: name of the work spec
:param str work_unit_key: name of the work unit
:return: definition of the work unit, or `None`
'''
with self.registry.lock(identifier=self.worker_id) as session:
work_unit_data = session.get(
WORK_UNITS_ + work_spec_name, work_unit_key)
if not work_unit_data:
work_unit_data = session.get(
WORK_UNITS_ + work_spec_name + _BLOCKED, work_unit_key)
if not work_unit_data:
work_unit_data = session.get(
WORK_UNITS_ + work_spec_name + _FINISHED, work_unit_key)
if not work_unit_data:
work_unit_data = session.get(
WORK_UNITS_ + work_spec_name + _FAILED, work_unit_key)
return work_unit_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 reset_all(self, work_spec_name):
'''Restart a work spec.
This calls :meth:`idle_all_workers`, then moves all finished
jobs back into the available queue.
.. deprecated:: 0.4.5
See :meth:`idle_all_workers` for problems with that method.
This also ignores failed jobs and work unit dependencies.
In practice, whatever generated a set of work units
initially can recreate them easily enough.
'''
self.idle_all_workers()
with self.registry.lock(identifier=self.worker_id) as session:
session.move_all(WORK_UNITS_ + work_spec_name + _FINISHED,
WORK_UNITS_ + work_spec_name)
session.reset_priorities(WORK_UNITS_ + work_spec_name, 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 add_dependent_work_units(self, work_unit, depends_on, hard=True):
"""Add work units, where one prevents execution of the other. The two work units may be attached to different work specs, but both must be in this task master's namespace. `work_unit` and `depends_on` are both tuples of (work spec name, work unit name, work unit dictionary). The work specs must already exist; they may be created with :meth:`update_bundle` with an empty work unit dictionary. If a work unit dictionary is provided with either work unit, then this defines that work unit, and any existing definition is replaced. Either or both work unit dictionaries may be :const:`None`, in which case the work unit is not created if it does not already exist. In this last case, the other work unit will be added if specified, but the dependency will not be added, and this function will return :const:`False`. In all other cases, this dependency is added in addition to all existing dependencies on either or both work units, even if the work unit dictionary is replaced. `work_unit` will not be executed or reported as available via :meth:`get_work` until `depends_on` finishes execution. If the `depends_on` task fails, then the `hard` parameter describes what happens: if `hard` is :const:`True` then `work_unit` will also fail, but if `hard` is :const:`False` then `work_unit` will be able to execute even if `depends_on` fails, it just must have completed some execution attempt. Calling this function with ``hard=True`` suggests an ordered sequence of tasks where the later task depends on the output of the earlier tasks. Calling this function with ``hard=False`` suggests a cleanup task that must run after this task (and, likely, several others) are done, but doesn't specifically depend on its result being available. :param work_unit: "Later" work unit to execute :paramtype work_unit: tuple of (str,str,dict) :param depends_on: "Earlier" work unit to execute :paramtype depends_on: tuple of (str,str,dict) :param bool hard: if True, then `work_unit` automatically fails if `depends_on` fails :return: :const:`True`, unless one or both of the work units didn't exist and weren't specified, in which case, :const:`False` :raise rejester.exceptions.NoSuchWorkSpecError: if a work spec was named that doesn't exist """ |
# There's no good, not-confusing terminology here.
# I'll call work_unit "later" and depends_on "earlier"
# consistently, because that at least makes the time flow
# correct.
later_spec, later_unit, later_unitdef = work_unit
earlier_spec, earlier_unit, earlier_unitdef = depends_on
with self.registry.lock(identifier=self.worker_id) as session:
# Bail if either work spec doesn't already exist
if session.get(WORK_SPECS, later_spec) is None:
raise NoSuchWorkSpecError(later_spec)
if session.get(WORK_SPECS, earlier_spec) is None:
raise NoSuchWorkSpecError(earlier_spec)
# Cause both work units to exist (if possible)
# Note that if "earlier" is already finished, we may be
# able to make "later" available immediately
earlier_done = False
earlier_successful = False
if earlier_unitdef is not None:
session.update(WORK_UNITS_ + earlier_spec,
{ earlier_unit: earlier_unitdef })
else:
earlier_unitdef = session.get(
WORK_UNITS_ + earlier_spec, earlier_unit)
if earlier_unitdef is None:
earlier_unitdef = session.get(
WORK_UNITS_ + earlier_spec + _BLOCKED, earlier_unit)
if earlier_unitdef is None:
earlier_unitdef = session.get(
WORK_UNITS_ + earlier_spec + _FINISHED, earlier_unit)
if earlier_unitdef is not None:
earlier_done = True
earlier_successful = True
if earlier_unitdef is None:
earlier_unitdef = session.get(
WORK_UNITS_ + earlier_spec + _FAILED, earlier_unit)
if earlier_unitdef is not None:
earlier_done = True
later_failed = earlier_done and hard and not earlier_successful
later_unblocked = ((earlier_done and not later_failed) or
(earlier_unitdef is None))
if later_failed:
later_destination = WORK_UNITS_ + later_spec + _FAILED
elif later_unblocked:
later_destination = WORK_UNITS_ + later_spec
else:
later_destination = WORK_UNITS_ + later_spec + _BLOCKED
if later_unitdef is not None:
for suffix in ['', _FINISHED, _FAILED, _BLOCKED]:
k = WORK_UNITS_ + later_spec + suffix
if k != later_destination:
session.popmany(k, later_unit)
session.update(later_destination,
{ later_unit: later_unitdef })
elif earlier_unitdef is not None:
later_unitdef = session.get(
WORK_UNITS_ + later_spec, later_unit)
if later_unitdef is not None:
session.move(
WORK_UNITS_ + later_spec,
WORK_UNITS_ + later_spec + _BLOCKED,
{ later_unit: later_unitdef })
else:
later_unitdef = session.get(
WORK_UNITS_ + later_spec + _BLOCKED, later_unit)
if later_unitdef is None or earlier_unitdef is None:
return False
# Now both units exist and are in the right place;
# record the dependency
blocks = session.get(WORK_UNITS_ + earlier_spec + _BLOCKS,
earlier_unit)
if blocks is None: blocks = []
blocks.append([later_spec, later_unit, hard])
session.set(WORK_UNITS_ + earlier_spec + _BLOCKS,
earlier_unit, blocks)
depends = session.get(WORK_UNITS_ + later_spec + _DEPENDS,
later_unit)
if depends is None: depends = []
depends.append([earlier_spec, earlier_unit])
session.set(WORK_UNITS_ + later_spec + _DEPENDS,
later_unit, depends)
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 nice(self, work_spec_name, nice):
'''Change the priority of an existing work spec.'''
with self.registry.lock(identifier=self.worker_id) as session:
session.update(NICE_LEVELS, dict(work_spec_name=nice)) |
<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_assigned_work_unit(self, worker_id, work_spec_name,
work_unit_key):
'''get a specific WorkUnit that has already been assigned to a
particular worker_id
'''
with self.registry.lock(identifier=self.worker_id) as session:
assigned_work_unit_key = session.get(
WORK_UNITS_ + work_spec_name + '_locks', worker_id)
if not assigned_work_unit_key == work_unit_key:
# raise LostLease instead of EnvironmentError, so
# users of TaskMaster can have a single type of
# expected exception, rather than two
raise LostLease(
'assigned_work_unit_key=%r != %r'
% (assigned_work_unit_key, work_unit_key))
# could trap EnvironmentError and raise LostLease instead
work_unit_data = session.get(WORK_UNITS_ + work_spec_name,
work_unit_key)
return WorkUnit(
self.registry, work_spec_name,
work_unit_key, work_unit_data,
worker_id=worker_id,
default_lifetime=self.default_lifetime,
) |
<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_work_units(self, worker_id):
'''Get work units assigned to a worker's children.
Returns a dictionary mapping worker ID to :class:`WorkUnit`.
If a child exists but is idle, that worker ID will map to
:const:`None`. The work unit may already be expired or
assigned to a different worker; this will be reflected in
the returned :class:`WorkUnit`.
This may write back to the underlying data store to clean up
stale children that have not unregistered themselves but
no longer exist in any form.
'''
result = {}
with self.registry.lock(identifier=worker_id) as session:
all_children = session.pull(WORKER_CHILDREN_ + worker_id)
# The data stored in Redis isn't actually conducive to
# this specific query; we will need to scan each work spec
# for each work unit
work_specs = session.pull(WORK_SPECS)
for child in all_children.iterkeys():
work_spec_name = None
for spec in work_specs.iterkeys():
work_unit_key = session.get(
WORK_UNITS_ + spec + '_locks', child)
if work_unit_key:
work_spec_name = spec
break
if work_spec_name:
assigned = session.get(
WORK_UNITS_ + work_spec_name + '_locks',
work_unit_key)
(data, expires) = session.get(
WORK_UNITS_ + work_spec_name, work_unit_key,
include_priority=True)
if data is None:
# The work unit is probably already finished
result[child] = None
else:
result[child] = WorkUnit(
self.registry, work_spec_name, work_unit_key,
data, expires=expires, worker_id=assigned)
else:
# The child isn't doing anything. Does it still
# exist?
heartbeat = session.get(WORKER_OBSERVED_MODE, child)
if heartbeat:
result[child] = None
else:
session.popmany(WORKER_CHILDREN_ + worker_id,
child)
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 plotPlainImg(sim, cam, rawdata, t, odir):
""" No subplots, just a plan http://stackoverflow.com/questions/22408237/named-colors-in-matplotlib """ |
for R, C in zip(rawdata, cam):
fg = figure()
ax = fg.gca()
ax.set_axis_off() # no ticks
ax.imshow(R[t, :, :],
origin='lower',
vmin=max(C.clim[0], 1), vmax=C.clim[1],
cmap='gray')
ax.text(0.05, 0.075, datetime.utcfromtimestamp(C.tKeo[t]).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3],
ha='left',
va='top',
transform=ax.transAxes,
color='limegreen',
# weight='bold',
size=24
)
writeplots(fg, 'cam{}rawFrame'.format(C.name), t, odir) |
<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_nodes(api_url=None, verify=False, cert=list()):
""" Returns info for all Nodes :param api_url: Base PuppetDB API url """ |
return utils._make_api_request(api_url, '/nodes', verify, cert) |
<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_node(api_url=None, node_name=None, verify=False, cert=list()):
""" Returns info for a Node :param api_url: Base PuppetDB API url :param node_name: Name of node """ |
return utils._make_api_request(api_url, '/nodes/{0}'.format(node_name), verify, cert) |
<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_node_fact_by_name(api_url=None, node_name=None, fact_name=None, verify=False, cert=list()):
""" Returns specified fact for a Node :param api_url: Base PuppetDB API url :param node_name: Name of node :param fact_name: Name of fact """ |
return utils._make_api_request(api_url, '/nodes/{0}/facts/{1}'.format(node_name,
fact_name), verify, cert) |
<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_node_resource_by_type(api_url=None, node_name=None, type_name=None, verify=False, cert=list()):
""" Returns specified resource for a Node :param api_url: Base PuppetDB API url :param node_name: Name of node :param type_name: Type of resource """ |
return utils._make_api_request(api_url, '/nodes/{0}/resources/{1}'.format(node_name,
type_name), verify, cert) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, request=None, *args, **kwargs):
""" Calls multiple time - with retry. :param request: :return: response """ |
if request is not None:
self.request = request
retry = self.request.configuration.retry
if not isinstance(retry, SimpleRetry):
raise Error('Currently only the fast retry strategy is supported')
last_exception = None
for i in range(0, retry.max_retry):
try:
if i > 0:
retry.sleep_jitter()
self.call_once()
return self.response
except Exception as ex:
last_exception = RequestFailed(message='Request failed', cause=ex)
logger.debug("Request %d failed, exception: %s" % (i, ex))
# Last exception - throw it here to have a stack
if i+1 == retry.max_retry:
raise last_exception
raise last_exception |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def field_to_long(value):
""" Converts given value to long if possible, otherwise None is returned. :param value: :return: """ |
if isinstance(value, (int, long)):
return long(value)
elif isinstance(value, basestring):
return bytes_to_long(from_hex(value))
else:
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 call_once(self, request=None, *args, **kwargs):
""" Performs one API request. Raises exception on failure. :param request: :param args: :param kwargs: :return: response """ |
if request is not None:
self.request = request
config = self.request.configuration
if config.http_method != EBConsts.HTTP_METHOD_POST or config.method != EBConsts.METHOD_REST:
raise Error('Not implemented yet, only REST POST method is allowed')
url = self.request.url if self.request.url is not None else self.build_url()
logger.debug("URL to call: %s", url)
# Do the request
resp = requests.post(url, json=self.request.body, timeout=config.timeout, headers=self.request.headers)
self.last_resp = resp
return self.check_response(resp) |
<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_response(self, resp):
""" Checks response after request was made. Checks status of the response, mainly :param resp: :return: """ |
# For successful API call, response code will be 200 (OK)
if resp.ok:
json = resp.json()
self.response = ResponseHolder()
self.response.response = json
# Check the code
if 'status' not in json:
raise InvalidResponse('No status field')
self.response.status = self.field_to_long(json['status'])
if self.response.status != EBConsts.STATUS_OK:
txt_status = self.get_text_status(json)
raise InvalidStatus('Status is %s (%04X)'
% (txt_status if txt_status is not None else "", self.response.status))
if self.response_checker is not None:
self.response_checker(self.response)
return self.response
else:
# If response code is not ok (200), print the resulting http error code with description
resp.raise_for_status()
pass |
<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_email(filepaths, collection_name):
"""Create an email message object which implements the email.message.Message interface and which has the files to be shared uploaded to min.us and links placed in the message body. """ |
gallery = minus.CreateGallery()
if collection_name is not None:
gallery.SaveGallery(collection_name)
interface = TerminalInterface()
interface.new_section()
interface.message(\
'Uploading files to http://min.us/m%s...' % (gallery.reader_id,))
item_map = { }
for path in filepaths:
interface.message('Uploading %s...' % (os.path.basename(path),))
interface.start_progress()
item = minus.UploadItem(path, gallery,
os.path.basename(path), interface.update_progress)
interface.end_progress()
item_map[item.id] = os.path.basename(path)
msg_str = ''
msg_str += "I've shared some files with you. They are viewable as a "
msg_str += "gallery at the following link:\n\n - http://min.us/m%s\n\n" %\
(gallery.reader_id,)
msg_str += "The individual files can be downloaded from the following "
msg_str += "links:\n\n"
for item, name in item_map.items():
msg_str += ' - http://i.min.us/j%s%s %s\n' % \
(item, os.path.splitext(name)[1], name)
msg = MIMEText(msg_str)
msg.add_header('Format', 'Flowed')
return 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 account_overview(object):
"""Create layout for user profile""" |
return Layout(
Container(
Row(
Column2(
Panel(
'Avatar',
Img(src="{}{}".format(settings.MEDIA_URL, object.avatar)),
collapse=True,
),
),
Column10(
Panel(
'Account information',
DescriptionList(
'email',
'first_name',
'last_name',
),
)
),
)
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_exp_key(self, key, value, ex):
"Expired in seconds"
return self.c.set(key, value, ex) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack(iterable, count, fill=None):
""" The iter data unpack function. Example 1: In[1]: source = 'abc' In[2]: a, b = safe_unpack(source, 2) In[3]: print(a, b) a b Example 2: In[1]: source = 'abc' In[2]: a, b, c, d = safe_unpack(source, 4) In[3]: print(a, b, c, d) a b None None """ |
iterable = list(enumerate(iterable))
cnt = count if count <= len(iterable) else len(iterable)
results = [iterable[i][1] for i in range(cnt)]
# results[len(results):len(results)] = [fill for i in range(count-cnt)]
results = merge(results, [fill for i in range(count-cnt)])
return tuple(results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transpose_list(list_of_dicts):
"""Transpose a list of dicts to a dict of lists :param list_of_dicts: to transpose, as in the output from a parse call :return: Dict of lists """ |
res = {}
for d in list_of_dicts:
for k, v in d.items():
if k in res:
res[k].append(v)
else:
res[k] = [v]
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 noisy_wrap(__func: Callable) -> Callable: """Decorator to enable DebugPrint for a given function. Args: __func: Function to wrap Returns: Wrapped function """ |
# pylint: disable=missing-docstring
def wrapper(*args, **kwargs):
DebugPrint.enable()
try:
__func(*args, **kwargs)
finally:
DebugPrint.disable()
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_enter(__msg: Optional[Union[Callable, str]] = None) -> Callable: """Decorator to display a message when entering a function. Args: __msg: Message to display Returns: Wrapped function """ |
# pylint: disable=missing-docstring
def decorator(__func):
@wraps(__func)
def wrapper(*args, **kwargs):
if __msg:
print(__msg)
else:
print('Entering {!r}({!r})'.format(__func.__name__, __func))
return __func(*args, **kwargs)
return wrapper
if callable(__msg):
return on_enter()(__msg)
return decorator |
<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(self, __text: str) -> None: """Write text to the debug stream. Args: __text: Text to write """ |
if __text == os.linesep:
self.handle.write(__text)
else:
frame = inspect.currentframe()
if frame is None:
filename = 'unknown'
lineno = 0
else:
outer = frame.f_back
filename = outer.f_code.co_filename.split(os.sep)[-1]
lineno = outer.f_lineno
self.handle.write('[{:>15s}:{:03d}] {}'.format(filename[-15:],
lineno, __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 enable() -> None: """Patch ``sys.stdout`` to use ``DebugPrint``.""" |
if not isinstance(sys.stdout, DebugPrint):
sys.stdout = DebugPrint(sys.stdout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def starting(self):
""" Prints a startup message to stdout. """ |
ident = self.ident()
print('{} starting & consuming "{}".'.format(ident, self.to_consume))
if self.max_tasks:
print('{} will die after {} tasks.'.format(ident, self.max_tasks))
else:
print('{} will never die.'.format(ident)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interrupt(self):
""" Prints an interrupt message to stdout. """ |
ident = self.ident()
print('{} for "{}" saw interrupt. Finishing in-progress task.'.format(
ident,
self.to_consume
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stopping(self):
""" Prints a shutdown message to stdout. """ |
ident = self.ident()
print('{} for "{}" shutting down. Consumed {} tasks.'.format(
ident,
self.to_consume,
self.tasks_complete
)) |
<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_forever(self):
""" Causes the worker to run either forever or until the ``Worker.max_tasks`` are reached. """ |
self.starting()
self.keep_running = True
def handle(signum, frame):
self.interrupt()
self.keep_running = False
signal.signal(signal.SIGINT, handle)
while self.keep_running:
if self.max_tasks and self.tasks_complete >= self.max_tasks:
self.stopping()
if self.gator.len():
result = self.gator.pop()
self.tasks_complete += 1
self.result(result)
if self.nap_time >= 0:
time.sleep(self.nap_time)
return 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 chdir(path):
"""Change the working directory to `path` for the duration of this context manager. :param str path: The path to change to """ |
cur_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cur_cwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def temp_file():
"""Create a temporary file for the duration of this context manager, deleting it afterwards. Yields: str - path to the file """ |
fd, path = tempfile.mkstemp()
os.close(fd)
try:
yield path
finally:
os.remove(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 skip_pickle_inject(app, what, name, obj, skip, options):
"""skip global wrapper._raw_slave names used only for pickle support""" |
if name.endswith('._raw_slave'):
return True
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 wraplet_signature(app, what, name, obj, options, signature, return_annotation):
"""have wrapplets use the signature of the slave""" |
try:
wrapped = obj._raw_slave
except AttributeError:
return None
else:
slave_argspec = autodoc.getargspec(wrapped)
slave_signature = autodoc.formatargspec(obj, *slave_argspec)
return (slave_signature, return_annotation) |
<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_users(path=settings.LOGIN_FILE):
""" Read passwd file and return dict with users and all their settings. Args: path (str, default settings.LOGIN_FILE):
path of the file, which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`). Returns: (dict):
username: {pass_hash, uid, gid, full_name, home, shell} Example of returned data:: { "xex": { "pass_hash": "$asd$aiosjdaiosjdásghwasdjo", "uid": "2000", "gid": "2000", "full_name": "ftftf", "home": "/home/ftp/xex", "shell": "/bin/false" } } """ |
if not os.path.exists(path):
return {}
data = ""
with open(path) as f:
data = f.read().splitlines()
users = {}
cnt = 1
for line in data:
line = line.split(":")
assert len(line) == 7, "Bad number of fields in '%s', at line %d!" % (
path,
cnt
)
users[line[0]] = {
"pass_hash": line[1],
"uid": line[2],
"gid": line[3],
"full_name": line[4],
"home": line[5],
"shell": line[6]
}
cnt += 1
return users |
<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_permissions(filename, uid=None, gid=None, mode=0775):
""" Set pemissions for given `filename`. Args: filename (str):
name of the file/directory uid (int, default proftpd):
user ID - if not set, user ID of `proftpd` is used gid (int):
group ID, if not set, it is not changed mode (int, default 0775):
unix access mode """ |
if uid is None:
uid = get_ftp_uid()
if gid is None:
gid = -1
os.chown(filename, uid, gid)
os.chmod(filename, 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 _decode_config(conf_str):
""" Decode string to configuration dict. Only values defined in settings._ALLOWED_MERGES can be redefined. """ |
conf_str = conf_str.strip()
# convert "tttff" -> [True, True, True, False, False]
conf = map(
lambda x: True if x.upper() == "T" else False,
list(conf_str)
)
return dict(zip(settings._ALLOWED_MERGES, conf)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _encode_config(conf_dict):
"""Encode `conf_dict` to string.""" |
out = []
# get variables in order defined in settings._ALLOWED_MERGES
for var in settings._ALLOWED_MERGES:
out.append(conf_dict[var])
# convert bools to chars
out = map(
lambda x: "t" if x else "f",
out
)
return "".join(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 read_user_config(username, path=settings.LOGIN_FILE):
""" Read user's configuration from otherwise unused field ``full_name`` in passwd file. Configuration is stored in string as list of t/f characters. """ |
return _decode_config(load_users(path=path)[username]["full_name"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_user_config(username, conf_dict, path=settings.LOGIN_FILE):
""" Save user's configuration to otherwise unused field ``full_name`` in passwd file. """ |
users = load_users(path=path)
users[username]["full_name"] = _encode_config(conf_dict)
save_users(users, path=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 create_ecdsap256_key_pair():
""" Create a new ECDSAP256 key pair. :returns: a tuple of the public and private keys """ |
pub = ECDSAP256PublicKey()
priv = ECDSAP256PrivateKey()
rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native)
if rc == RC.SUCCESS:
return (pub, priv)
else:
raise error_from_code(rc) |
<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_option_default(option):
""" Given an optparse.Option, returns a two-tuple of the option's variable name and default value. """ |
return (
option.dest,
None if option.default is optparse.NO_DEFAULT else option.default,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_command_class_from_apps(name, apps, exclude_packages=None, exclude_command_class=None):
""" Searches through the given apps to find the named command class. Skips over any packages specified by exclude_packages and any command class specified by exclude_command_class. Returns the last command class found or None if the command class could not be found. Django's command searching behavior is backwards with respect to other features like template and static file loaders. This function follows that convention. """ |
if exclude_packages is None:
exclude_packages = []
for app in reversed(
[app for app in apps if not issubpackage(app, exclude_packages)]):
try:
command_class = import_module(
"{app:s}.management.commands.{name:s}".format(
app=app, name=name)).Command
except (ImportError, AttributeError):
pass
else:
if exclude_command_class is None or \
not issubclass(command_class, exclude_command_class):
return command_class
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 get_command_class(name, exclude_packages=None, exclude_command_class=None):
""" Searches "django.core" and the apps in settings.INSTALLED_APPS to find the named command class, optionally skipping packages or a particular command class. """ |
from django.conf import settings
return get_command_class_from_apps(
name,
settings.INSTALLED_APPS \
if "django.core" in settings.INSTALLED_APPS \
else ("django.core",) + tuple(settings.INSTALLED_APPS),
exclude_packages=exclude_packages,
exclude_command_class=exclude_command_class) |
<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_program(name):
""" Uses the shell program "which" to determine whether the named program is available on the shell PATH. """ |
with open(os.devnull, "w") as null:
try:
subprocess.check_call(("which", name), stdout=null, stderr=null)
except subprocess.CalledProcessError as e:
return False
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 get_option_lists(self):
""" A hook to override the option lists used to generate option names and defaults. """ |
return [self.get_option_list()] + \
[option_list
for name, description, option_list
in self.get_option_groups()] |
<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_options(self):
""" A hook to override the flattened list of all options used to generate option names and defaults. """ |
return reduce(
list.__add__,
[list(option_list) for option_list in self.get_option_lists()],
[]) |
<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_parser(self, prog_name, subcommand):
""" Customize the parser to include option groups. """ |
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_option_list())
for name, description, option_list in self.get_option_groups():
group = optparse.OptionGroup(parser, name, description);
list(map(group.add_option, option_list))
parser.add_option_group(group)
return parser |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_command(self, name):
""" Checks whether the given Django management command exists, excluding this command from the search. """ |
if not check_command(
name,
exclude_packages=self.get_exclude_packages(),
exclude_command_class=self.__class__):
raise management.CommandError(
"The management command \"{name:s}\" is not available. "
"Please ensure that you've added the application with "
"the \"{name:s}\" command to your INSTALLED_APPS "
"setting".format(
name=name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_program(self, name):
""" Checks whether a program is available on the shell PATH. """ |
if not check_program(name):
raise management.CommandError(
"The program \"{name:s}\" is not available in the shell. "
"Please ensure that \"{name:s}\" is installed and reachable "
"through your PATH environment variable.".format(
name=name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_command(self, name, *arguments, **options):
""" Finds the given Django management command and default options, excluding this command, and calls it with the given arguments and override options. """ |
command, defaults = get_command_and_defaults(
name,
exclude_packages=self.get_exclude_packages(),
exclude_command_class=self.__class__)
if command is None:
raise management.CommandError(
"Unknown command: {name:s}".format(
name=name))
defaults.update(options)
return command.execute(*arguments, **defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_program(self, name, *arguments):
""" Calls the shell program on the PATH with the given arguments. """ |
verbosity = self.options.get("verbosity", 1)
with self.devnull as null:
try:
subprocess.check_call((name,) + tuple(arguments),
stdout=null if verbosity == 0 else self.stdout,
stderr=null if verbosity == 0 else self.stderr)
except subprocess.CalledProcessError as error:
raise management.CommandError(
"{name:s} failed with exit code {code:d}".format(
name=name, code=error.returncode))
return 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 update_score(self):
"""Update the relevance score for this thread. The score is calculated with the following variables: * vote_weight: 100 - (minus) 1 for each 3 days since voted with minimum of 5. * replies_weight: 300 - (minus) 1 for each 3 days since replied with minimum of 5. * page_view_weight: 10. * vote_score: sum(vote_weight) * replies_score: sum(replies_weight) * page_view_score: sum(page_view_weight) * score = (vote_score + replies_score + page_view_score) // 10 with minimum of 0 and maximum of 5000 """ |
if not self.subject_token:
return
vote_score = 0
replies_score = 0
for msg in self.message_set.all():
# Calculate replies_score
replies_score += self._get_score(300, msg.received_time)
# Calculate vote_score
for vote in msg.vote_set.all():
vote_score += self._get_score(100, vote.created)
# Calculate page_view_score
page_view_score = self.hits * 10
self.score = (page_view_score + vote_score + replies_score) // 10
self.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self):
"""Shortcut to get thread url""" |
return reverse('archives:thread_view',
args=[self.mailinglist.name,
self.thread.subject_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 print_config():
# pragma: no cover """Print config entry function.""" |
description = """\
Print the deployment settings for a Pyramid application. Example:
'psettings deployment.ini'
"""
parser = argparse.ArgumentParser(
description=textwrap.dedent(description)
)
parser.add_argument(
'config_uri', type=str, help='an integer for the accumulator'
)
parser.add_argument(
'-k', '--key',
dest='key',
metavar='PREFIX',
type=str,
action='store',
help=(
"Tells script to print only specified"
" config tree provided by dotted name"
)
)
args = parser.parse_args(sys.argv[1:])
config_uri = args.config_uri
env = bootstrap(config_uri)
config, closer = env['registry']['config'], env['closer']
try:
print(printer(slice_config(config, args.key)))
except KeyError:
print(
'Sorry, but the key path {0}, does not exists in Your config!'
.format(args.key)
)
finally:
closer() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printer(data, depth=0):
""" Prepare data for printing. :param data: a data value that will be processed by method :param int depth: recurrency indicator, to maintain proper indent :returns: string with formatted config :rtype: str """ |
indent = _INDENT * depth
config_string = '' if not depth else ':\n'
if isinstance(data, dict):
for key, val in data.items():
line = '{0}{1}'.format(indent, key)
values = printer(val, depth + 1)
if not values.count('\n'):
values = ': {0}'.format(values.lstrip())
line = '{line}{values}'.format(line=line, values=values)
config_string += '{0}\n'.format(line)
elif isinstance(data, list):
for elem in data:
config_string += '{0} - {1}\n'.format(indent, elem)
else:
config_string = '{0}{1} ({2})'.format(
indent, data, data.__class__.__name__
)
return config_string.rstrip('\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 slice_config(config, key):
""" Slice config for printing as defined in key. :param ConfigManager config: configuration dictionary :param str key: dotted key, by which config should be sliced for printing :returns: sliced config :rtype: dict """ |
if key:
keys = key.split('.')
for k in keys:
config = config[k]
return 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 split_size(size):
'''Split the file size into several chunks.'''
rem = size % CHUNK_SIZE
if rem == 0:
cnt = size // CHUNK_SIZE
else:
cnt = size // CHUNK_SIZE + 1
chunks = []
for i in range(cnt):
pos = i * CHUNK_SIZE
if i == cnt - 1:
disp = size - pos
else:
disp = CHUNK_SIZE
chunks.append((pos, disp))
return chunks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reverse_fd(inf, outf):
'''Reverse the content of inf, write to outf.
Both inf and outf are file objects.
inf must be seekable.
'''
inf.seek(0, 2)
size = inf.tell()
if not size:
return
chunks = split_size(size)
for chunk in reversed(chunks):
inf.seek(chunk[0], 0)
data = inf.read(chunk[1])
if len(data) != chunk[1]:
raise IOError('incomplete I/O operation')
outf.write(data[::-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 reverse_file(infile, outfile):
'''Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths.
'''
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
reverse_fd(inf, outf) |
<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(self, *objects, **kwargs):
"""Micmic print interface""" |
file = kwargs.get("file")
if file is not None and file is not sys.stdout:
PRINT(*objects, **kwargs)
else:
sep = STR(kwargs.get("sep", " "))
end = STR(kwargs.get("end", "\n"))
text = sep.join(STR(o) for o in objects)
self.imp_print(text, end)
for callback in self.listeners:
callback(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 imp_print(self, text, end):
"""Directly send utf8 bytes to stdout""" |
sys.stdout.write((text + end).encode("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 restore(cdiff, a):
"""Restores the full text of either the edited text using the compressed diff. Args: cdiff (dict):
compressed diff returned by :func:`~acorn.logging.diff.compress`. a (str or list):
*original* string or list of strings to use as a reference to restore the edited version. """ |
left = a.splitlines(1) if isinstance(a, string_types) else a
lrest = []
iline = 0
for i, line in enumerate(left):
if iline not in cdiff:
lrest.append(" " + line)
iline += 1
else:
cs = [l[0] for l in cdiff[iline]]
add = cs.count('+') - cs.count('-')
lrest.extend(cdiff[iline])
iline += add + 1
for i in sorted(cdiff.keys()):
if i >= len(left):
lrest.extend(cdiff[i])
from difflib import restore
return list(restore(lrest, 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 get_url(width, height, color=True):
""" Craft the URL for a placekitten image. By default they are in color. To retrieve a grayscale image, set the color kwarg to False. """ |
d = dict(width=width, height=height)
return URL % 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 instance():
"""Returns a global `IOLoop` instance. Most applications have a single, global `IOLoop` running on the main thread. Use this method to get this instance from another thread. To get the current thread's `IOLoop`, use `current()`. """ |
if not hasattr(IOLoop, "_instance"):
with IOLoop._instance_lock:
if not hasattr(IOLoop, "_instance"):
# New instance after double check
IOLoop._instance = IOLoop()
return IOLoop._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 create_paste(self, content):
"""Create a raw paste of the given content. Returns a URL to the paste, or raises a ``pasteraw.Error`` if something tragic happens instead. """ |
r = requests.post(
self.endpoint + '/pastes',
data={'content': content},
allow_redirects=False)
if r.status_code == 302:
return r.headers['Location']
if r.status_code == 413:
raise MaxLengthExceeded('%d bytes' % len(content))
try:
error_message = r.json()['error']
except Exception:
error_message = r.text
raise UnexpectedError(error_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 match_keys(inp, p=False):
"""Takes a comma-separated string of key ids or fingerprints and returns a list of key ids""" |
_keys = []
ssh_keys = DO.get_ssh_keys()
for k in inp.split(","):
done = False
if k.isdigit():
for _ in [s for s in ssh_keys if s["id"] == int(k)]:
done = True
_keys.append(_["fingerprint"])
else:
for _ in [s for s in ssh_keys if s["fingerprint"] == k]:
done = True
_keys.append(_["fingerprint"])
if p and not done:
print("Could not find a match for '{}', skipping".format(k), file=sys.stderr)
return _keys |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cd(cd_path, create=False):
"""cd to target dir when running in this block :param cd_path: dir to cd into :param create: create new dir if destination not there Usage:: """ |
oricwd = os.getcwd()
if create:
mkdir(cd_path)
try:
os.chdir(cd_path)
yield
finally:
os.chdir(oricwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cd_to(path, mkdir=False):
"""make a generator like cd, but use it for function Usage:: / """ |
def cd_to_decorator(func):
@functools.wraps(func)
def _cd_and_exec(*args, **kwargs):
with cd(path, mkdir):
return func(*args, **kwargs)
return _cd_and_exec
return cd_to_decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_python(minimum):
"""Require at least a minimum Python version. The version number is expressed in terms of `sys.hexversion`. E.g. to require a minimum of Python 2.6, use:: :param minimum: Minimum Python version supported. :type minimum: integer """ |
if sys.hexversion < minimum:
hversion = hex(minimum)[2:]
if len(hversion) % 2 != 0:
hversion = '0' + hversion
split = list(hversion)
parts = []
while split:
parts.append(int(''.join((split.pop(0), split.pop(0))), 16))
major, minor, micro, release = parts
if release == 0xf0:
print('Python {0}.{1}.{2} or better is required'.format(
major, minor, micro))
else:
print('Python {0}.{1}.{2} ({3}) or better is required'.format(
major, minor, micro, hex(release)[2:]))
sys.exit(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 long_description(*filenames):
"""Provide a long description.""" |
res = ['']
for filename in filenames:
with open(filename) as fp:
for line in fp:
res.append(' ' + line)
res.append('')
res.append('\n')
return EMPTYSTRING.join(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 description(filename):
"""Provide a short description.""" |
# This ends up in the Summary header for PKG-INFO and it should be a
# one-liner. It will get rendered on the package page just below the
# package version header but above the long_description, which ironically
# gets stuff into the Description header. It should not include reST, so
# pick out the first single line after the double header.
with open(filename) as fp:
for lineno, line in enumerate(fp):
if lineno < 3:
continue
line = line.strip()
if len(line) > 0:
return line |
<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 fetch_house(self, house_id):
"""Lookup details for a given house id""" |
url = "https://production.plum.technology/v2/getHouse"
data = {"hid": house_id}
return await self.__post(url, data) |
<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 fetch_room(self, room_id):
"""Lookup details for a given room id""" |
url = "https://production.plum.technology/v2/getRoom"
data = {"rid": room_id}
return await self.__post(url, data) |
<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 fetch_logical_load(self, llid):
"""Lookup details for a given logical load""" |
url = "https://production.plum.technology/v2/getLogicalLoad"
data = {"llid": llid}
return await self.__post(url, data) |
<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 fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad""" |
url = "https://production.plum.technology/v2/getLightpad"
data = {"lpid": lpid}
return await self.__post(url, 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 to_bytes(s, encoding="utf-8"):
""" Converts the string to a bytes type, if not already. :s: the string to convert to bytes :returns: `str` on Python2 and `bytes` on Python3. """ |
if isinstance(s, six.binary_type):
return s
else:
return six.text_type(s).encode(encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_text(s, encoding="utf-8"):
""" Converts the bytes to a text type, if not already. :s: the bytes to convert to text :returns: `unicode` on Python2 and `str` on Python3. """ |
if isinstance(s, six.text_type):
return s
else:
return six.binary_type(s).decode(encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_len(a, b):
""" Raises an exception if the two values do not have the same length. This is useful for validating preconditions. :a: the first value :b: the second value :raises ValueError: if the sizes do not match """ |
if len(a) != len(b):
msg = "Length must be {}. Got {}".format(len(a), len(b))
raise ValueError(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 similarity1DdiffShapedArrays(arr1, arr2, normalize=False):
""" compare two strictly monotonous increasing 1d arrays of same or different size return a similarity index-> 0=identical """ |
# assign longer and shorter here, because jit cannot do it
if len(arr1) < len(arr2):
arr1, arr2 = arr2, arr1
if not len(arr2):
out = sum(arr1)
else:
out = _calc(arr1, arr2)
if normalize:
if not len(arr2):
mn = arr1[0]
mx = arr1[-1]
else:
mn = min(arr1[0], arr2[0])
mx = max(arr1[-1], arr2[-1])
out = out/ (mx - mn)
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 get_instance( model, method="file", img_dir=None, data_dir=None, bucket=None ):
"""Return an instance of ConsumeStore.""" |
global _instances
if not isinstance(model, ConsumeModel):
raise TypeError(
"get_instance() expects a parker.ConsumeModel derivative."
)
if method == "file":
my_store = store.get_filestore_instance(
img_dir=img_dir,
data_dir=data_dir
)
elif method == "s3":
my_store = store.get_s3store_instance(
bucket=bucket
)
else:
raise ValueError("Unexpected method value, '%s'." % method)
key = "%s:%s" % (repr(model), repr(my_store))
try:
instance = _instances[key]
except KeyError:
instance = ConsumeStore(model, my_store)
_instances[key] = instance
return 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 save_media(self):
"""Store any media within model.media_list.""" |
chunk_path = fileops.get_chunk_path_from_string(
self.model.unique_field
)
for i, mediafile in enumerate(self.model.media_list):
filename = os.path.join(
self._get_prefix(),
chunk_path,
"%s_%d" % (self.model.unique_field, i)
)
self.store.store_media(filename, mediafile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_data(self):
"""Store data as a JSON dump.""" |
filename = os.path.join(
self._get_prefix(),
self.model.site
)
self.store.store_json(
filename,
self.model.get_dict()
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findloop(m):
"""Determines if the specified member of `_ast` contains any for or while loops in its body definition. """ |
from _ast import For, While, FunctionDef, ClassDef, ListComp
from _ast import DictComp
if isinstance(m, (FunctionDef, ClassDef)):
return False
elif isinstance(m, (For, While, ListComp, DictComp)):
return True
elif hasattr(m, "value"):
return findloop(m.value)
elif hasattr(m, "__iter__"):
for sm in m:
present = findloop(sm)
if present:
break
else:
present = False
return present
elif hasattr(m, "body") or hasattr(m, "orelse"):
body = hasattr(m, "body") and findloop(m.body)
orelse = hasattr(m, "orelse") and findloop(m.orelse)
return body or orelse
else:
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 record_markdown(text, cellid):
"""Records the specified markdown text to the acorn database. Args: text (str):
the *raw* markdown text entered into the cell in the ipython notebook. """ |
from acorn.logging.database import record
from time import time
ekey = "nb-{}".format(cellid)
global _cellid_map
if cellid not in _cellid_map:
from acorn.logging.database import active_db
from difflib import SequenceMatcher
from acorn.logging.diff import cascade
taskdb = active_db()
if ekey not in taskdb.entities:
#Compute a new ekey if possible with the most similar markdown cell
#in the database.
possible = [k for k in taskdb.entities if k[0:3] == "nb-"]
maxkey, maxvalue = None, 0.
for pkey in possible:
sequence = [e["c"] for e in taskdb.entities[pkey]]
state = ''.join(cascade(sequence))
matcher = SequenceMatcher(a=state, b=text)
ratio = matcher.quick_ratio()
if ratio > maxvalue and ratio > 0.5:
maxkey, maxvalue = pkey, ratio
#We expect the similarity to be at least 0.5; otherwise we decide
#that it is a new cell.
if maxkey is not None:
ekey = pkey
_cellid_map[cellid] = ekey
ekey = _cellid_map[cellid]
entry = {
"m": "md",
"a": None,
"s": time(),
"r": None,
"c": text,
}
record(ekey, entry, diff=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 load_ipython_extension(ip):
"""Loads the interacting decorator that ships with `acorn` into the ipython interactive shell. Args: ip (IPython.core.interactiveshell.InteractiveShell):
ipython shell instance for interacting with the shell variables. """ |
decor = InteractiveDecorator(ip)
ip.events.register('post_run_cell', decor.post_run_cell)
#Unfortunately, the built-in "pre-execute" and "pre-run" methods are
#triggered *before* the input from the cell has been stored to
#history. Thus, we don't have access to the actual code that is about to be
#executed. Instead, we use our own :class:`HistoryManager` that overrides
#the :meth:`store_inputs` so we can handle the loop detection.
newhist = AcornHistoryManager(ip.history_manager, decor)
ip.history_manager = newhist |
<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_decoratables(self, atype):
"""Returns a list of the objects that need to be decorated in the current user namespace based on their type. Args: atype (str):
one of the values in :attr:`atypes`. Specifies the type of object to search. """ |
result = []
defmsg = "Skipping {}; not decoratable or already decorated."
for varname in self.shell.run_line_magic("who_ls", atype):
varobj = self.shell.user_ns.get(varname, None)
decorate = False
if varobj is None: # Nothing useful can be done.
continue
if atype in ["classobj", "type"]:
#Classes are only relevant if they have no __file__
#attribute; all other classes should be decorated by the
#full acorn machinery.
if (not hasattr(varobj, "__acorn__") and
hasattr(varobj, "__module__") and
varobj.__module__ == "__main__" and
not hasattr(varobj, "__file__")):
decorate = True
else:
msg.std(defmsg.format(varname), 3)
elif atype in ["function", "staticmethod"]:
# %who_ls will only return functions from the *user*
# namespace, so we don't have a lot to worry about here.
func = None
if atype == "staticmethod" and hasattr(varobj, "__func__"):
func = varobj.__func__
elif atype == "function":
func = varobj
if (func is not None and
not hasattr(func, "__acorn__") and
hasattr(func, "__code__") and
"<ipython-input" in func.__code__.co_filename):
decorate = True
else:
msg.std(defmsg.format(varname), 3)
if decorate:
self.entities[atype][varname] = varobj
result.append((varname, varobj))
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 _logdef(self, n, o, otype):
"""Logs the definition of the object that was just auto-decorated inside the `ipython` notebook. """ |
import re
try:
#The latest input cell will be the one that this got executed
#from. TODO: actually, if acorn got imported after the fact, then
#the import would have caused all the undecorated functions to be
#decorated as soon as acorn imported. I suppose we just won't have
#any code for that case.
if otype == "classes":
cellno = max([int(k[2:]) for k in self.shell.user_ns.keys()
if re.match("_i\d+", k)])
elif otype == "functions":
cellno = int(o.__code__.co_filename.strip("<>").split('-')[2])
except:
#This must not have been an ipython notebook declaration, so we
#don't store the code.
cellno = None
pass
code = ""
if cellno is not None:
cellstr = "_i{0:d}".format(cellno)
if cellstr in self.shell.user_ns:
cellcode = self.shell.user_ns[cellstr]
import ast
astm = ast.parse(cellcode)
ab = astm.body
parts = {ab[i].name: (ab[i].lineno, None if i+1 >= len(ab)
else ab[i+1].lineno)
for i, d in enumerate(ab)}
if n in parts:
celllines = cellcode.split('\n')
start, end = parts[n]
if end is not None:
code = celllines[start-1:end-1]
else:
code = celllines[start-1:]
#Now, we actually create the entry. Since the execution for function
#definitions is almost instantaneous, we just log the pre and post
#events at the same time.
from time import time
from acorn.logging.database import record
entry = {
"m": "def",
"a": None,
"s": time(),
"r": None,
"c": code,
}
from acorn import msg
record("__main__.{}".format(n), entry, diff=True)
msg.info(entry, 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 _decorate(self, atype, n, o):
"""Decorates the specified object for automatic logging with acorn. Args: atype (str):
one of the types specified in :attr:`atypes`. varobj: object instance to decorate; no additional type checking is performed. """ |
typemap = {"function": "functions",
"classobj": "classes",
"staticmethod": "methods",
"type": "classes"}
from acorn.logging.decoration import decorate_obj
try:
otype = typemap[atype]
decorate_obj(self.shell.user_ns, n, o, otype)
#Also create a log in the database for this execution; this allows a
#user to track the changes they make in prototyping function and
#class definitions.
self._logdef(n, o, otype)
msg.okay("Auto-decorated {}: {}.".format(n, o))
except:
msg.err("Error auto-decorating {}: {}.".format(n, o))
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 post_run_cell(self):
"""Runs after the user-entered code in a cell has been executed. It detects any new, decoratable objects that haven't been decorated yet and then decorates them. """ |
#We just want to detect any new, decoratable objects that haven't been
#decorated yet.
decorlist = {k: [] for k in self.atypes}
for atype in self.atypes:
for n, o in self._get_decoratables(atype):
self._decorate(atype, n, o)
#Next, check whether we have an outstanding "loop intercept" that we
#"wrapped" with respect to acorn by enabling streamlining.
if self.pre is not None:
#Re-enable the acorn logging systems so that it gets back to normal.
from acorn.logging.decoration import set_streamlining
set_streamlining(False)
from acorn import msg
from acorn.logging.database import record
from time import time
#Determine the elapsed time for the execution of the entire cell.
entry = self.pre
entry["e"] = time() - entry["s"]
#See if we can match the executed cell's code up with one that we
#intercepted in the past..
cellid = self._find_cellid(entry["c"])
if cellid is None:
cellid = self.cellid
#Store the contents of the cell *before* they get overwritten by a
#diff.
self.cellids[cellid] = entry["c"]
record("__main__.{0:d}".format(cellid), entry, diff=True)
msg.info(entry, 1)
self.pre = None
#Finally, check whether any new variables have shown up, or have had
#their values changed.
from acorn.logging.database import tracker, active_db, Instance
varchange = self._var_changes()
taskdb = active_db()
for n, o in varchange:
otrack = tracker(o)
if isinstance(otrack, Instance):
taskdb.log_uuid(otrack.uuid)
global thumb_uuid
if thumb_uuid is not None:
self._log_images()
#Reset the image tracker list so that we don't save these images
#again next cell execution.
thumb_uuid = None
self.cellid = 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 _var_changes(self):
"""Determines the list of variables whose values have changed since the last cell execution. """ |
result = []
variables = self.shell.run_line_magic("who_ls", "")
if variables is None:
return result
import inspect
for varname in variables:
varobj = self.shell.user_ns.get(varname, None)
if varobj is None:
continue
#We need to make sure that the objects have types that make
#sense. We auto-decorate all classes and functions; also modules and
#other programming constructs are not variables.
keep = False
for ifunc in inspectors:
if getattr(inspect, ifunc)(varobj):
break
else:
keep = True
if keep:
whoid = id(varobj)
if varname not in self.who or self.who[varname] != whoid:
result.append((varname, varobj))
self.who[varname] = whoid
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 pre_run_cell(self, cellno, code):
"""Executes before the user-entered code in `ipython` is run. This intercepts loops and other problematic code that would produce lots of database entries and streamlines it to produce only a single entry. Args: cellno (int):
the cell number that is about to be executed. code (str):
python source code that is about to be executed. """ |
#First, we look for loops and list/dict comprehensions in the code. Find
#the id of the latest cell that was executed.
self.cellid = cellno
#If there is a loop somewhere in the code, it could generate millions of
#database entries and make the notebook unusable.
import ast
if findloop(ast.parse(code)):
#Disable the acorn logging systems so that we don't pollute the
#database.
from acorn.logging.decoration import set_streamlining
set_streamlining(True)
#Create the pre-execute entry for the database.
from time import time
self.pre = {
"m": "loop",
"a": None,
"s": time(),
"r": None,
"c": 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 inverseHistogram(hist, bin_range):
"""sample data from given histogram and min, max values within range Returns: np.array: data that would create the same histogram as given """ |
data = hist.astype(float) / np.min(hist[np.nonzero(hist)])
new_data = np.empty(shape=np.sum(data, dtype=int))
i = 0
xvals = np.linspace(bin_range[0], bin_range[1], len(data))
for d, x in zip(data, xvals):
new_data[i:i + d] = x
i += int(d)
return new_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 watermark_image(image, wtrmrk_path, corner=2):
'''Adds a watermark image to an instance of a PIL Image.
If the provided watermark image (wtrmrk_path) is
larger than the provided base image (image), then
the watermark image will be automatically resized to
roughly 1/8 the size of the base image.
Args:
image: An instance of a PIL Image. This is the base image.
wtrmrk_path: Path to the watermark image to use.
corner: An integer between 0 and 3 representing the corner
where the watermark image should be placed on top of the
base image. 0 is top left, 1 is top right, 2 is bottom
right and 3 is bottom left. NOTE: Right now, this is
permanently set to 2 (bottom right) but this can be
changed in the future by either creating a new cmd-line
flag or putting this in the config file.
Returns: The watermarked image
'''
padding = 2
wtrmrk_img = Image.open(wtrmrk_path)
#Need to perform size check in here rather than in options.py because this is
# the only place where we know the size of the image that the watermark is
# being placed onto
if wtrmrk_img.width > (image.width - padding * 2) or wtrmrk_img.height > (
image.height - padding * 2):
res = (int(image.width / 8.0), int(image.height / 8.0))
resize_in_place(wtrmrk_img, res)
pos = get_pos(corner, image.size, wtrmrk_img.size, padding)
was_P = image.mode == 'P'
was_L = image.mode == 'L'
# Fix PIL palette issue by converting palette images to RGBA
if image.mode not in ['RGB', 'RGBA']:
if image.format in ['JPG', 'JPEG']:
image = image.convert('RGB')
else:
image = image.convert('RGBA')
image.paste(wtrmrk_img.convert('RGBA'), pos, wtrmrk_img.convert('RGBA'))
if was_P:
image = image.convert('P', palette=Image.ADAPTIVE, colors=256)
elif was_L:
image = image.convert('L')
return image |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def watermark_text(image, text, corner=2):
'''Adds a text watermark to an instance of a PIL Image.
The text will be sized so that the height of the text is
roughly 1/20th the height of the base image. The text will
be white with a thin black outline.
Args:
image: An instance of a PIL Image. This is the base image.
text: Text to use as a watermark.
corner: An integer between 0 and 3 representing the corner
where the watermark image should be placed on top of the
base image. 0 is top left, 1 is top right, 2 is bottom
right and 3 is bottom left. NOTE: Right now, this is
permanently set to 2 (bottom right) but this can be
changed in the future by either creating a new cmd-line
flag or putting this in the config file.
Returns: The watermarked image
'''
# Load Font
FONT_PATH = ''
if resource_exists(__name__, 'resources/fonts/SourceSansPro-Regular.ttf'):
FONT_PATH = resource_filename(
__name__, 'resources/fonts/SourceSansPro-Regular.ttf')
padding = 5
was_P = image.mode == 'P'
was_L = image.mode == 'L'
# Fix PIL palette issue by converting palette images to RGBA
if image.mode not in ['RGB', 'RGBA']:
if image.format in ['JPG', 'JPEG']:
image = image.convert('RGB')
else:
image = image.convert('RGBA')
# Get drawable image
img_draw = ImageDraw.Draw(image)
fontsize = 1 # starting font size
# portion of image width you want text height to be.
# default font size will have a height that is ~1/20
# the height of the base image.
img_fraction = 0.05
# attempt to use Aperture default font. If that fails, use ImageFont default
try:
font = ImageFont.truetype(font=FONT_PATH, size=fontsize)
was_over = False
inc = 2
while True:
if font.getsize(text)[1] > img_fraction * image.height:
if not was_over:
was_over = True
inc = -1
else:
if was_over:
break
# iterate until the text size is just larger than the criteria
fontsize += inc
font = ImageFont.truetype(font=FONT_PATH, size=fontsize)
fontsize -= 1
font = ImageFont.truetype(font=FONT_PATH, size=fontsize)
except:
# replace with log message
print('Failed to load Aperture font. Using default font instead.')
font = ImageFont.load_default() # Bad because default is suuuuper small
# get position of text
pos = get_pos(corner, image.size, font.getsize(text), padding)
# draw a thin black border
img_draw.text((pos[0] - 1, pos[1]), text, font=font, fill='black')
img_draw.text((pos[0] + 1, pos[1]), text, font=font, fill='black')
img_draw.text((pos[0], pos[1] - 1), text, font=font, fill='black')
img_draw.text((pos[0], pos[1] + 1), text, font=font, fill='black')
# draw the actual text
img_draw.text(pos, text, font=font, fill='white')
# Remove cached font file
cleanup_resources()
del img_draw
if was_P:
image = image.convert('P', palette=Image.ADAPTIVE, colors=256)
elif was_L:
image = image.convert('L')
return image |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(msg, *args, **kwargs):
""" Print out a log message. """ |
if len(args) == 0 and len(kwargs) == 0:
print(msg)
else:
print(msg.format(*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 logv(msg, *args, **kwargs):
""" Print out a log message, only if verbose mode. """ |
if settings.VERBOSE:
log(msg, *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 _csv_to_nodes_dict(nodes_csv):
"""Convert CSV to a list of dicts formatted for os_cloud_config Given a CSV file in the format below, convert it into the structure expected by os_could_config JSON files. pm_type, pm_addr, pm_user, pm_password, mac """ |
data = []
for row in csv.reader(nodes_csv):
node = {
"pm_user": row[2],
"pm_addr": row[1],
"pm_password": row[3],
"pm_type": row[0],
"mac": [
row[4]
]
}
data.append(node)
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 assign(A, attr, B, lock=False):
'''Assigns B to A.attr, yields, and then assigns A.attr back to its
original value.
'''
class NoAttr(object): pass
context = threading.Lock if lock else null_context
with context():
if not hasattr(A, attr):
tmp = NoAttr
else:
tmp = getattr(A, attr)
setattr(A, attr, B)
try:
yield B
finally:
if tmp is NoAttr:
delattr(A, attr)
else:
setattr(A, attr, tmp) |
<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(*args):
'''For using then deleting objects.'''
from syn.base_utils import this_module
mod = this_module(npop=3)
yield
for arg in args:
name = arg
if not isinstance(name, STR):
name = arg.__name__
delattr(mod, name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize_job(job):
"""Return a dictionary representing the job.""" |
d = dict(
id=job.get_id(),
uri=url_for('jobs.get_job', job_id=job.get_id(), _external=True),
status=job.get_status(),
result=job.result
)
return d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.