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 __singleIntersect(self, e):
""" Get a list of GenomicRegions produced by subtracting e from self. :return: a list of regions that represent the result of sub... |
if e.chrom != self.chrom or e.end < self.start or e.start > self.end:
# no intersection
return [copy.copy(self)]
if e.start <= self.start and e.end >= self.end:
# whole self is removed.
return []
if e.start > self.start and e.end < self.end:
# splits self in two
r1 = cop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subtract(self, es):
""" Subtract the BED elements in es from self. :param es: a list of BED elements (or anything with chrom, start, end) :return: a list of ... |
workingSet = [self]
for e in es:
newWorkingSet = []
for w in workingSet:
newWorkingSet += w.__singleIntersect(e)
workingSet = newWorkingSet
return workingSet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sizeOfOverlap(self, e):
""" Get the size of the overlap between self and e. :return: the number of bases that are shared in common between self and e. """ |
# no overlap
if not self.intersects(e):
return 0
# complete inclusion..
if e.start >= self.start and e.end <= self.end:
return len(e)
if self.start >= e.start and self.end <= e.end:
return len(self)
# partial overlap
if e.start > self.start:
return (self.end - e.st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersects(self, e):
""" Check whether e intersects self. :return: true if this elements intersects the element e """ |
if self.chrom != e.chrom:
return False
if e.start >= self.start and e.start < self.end:
return True
if e.end > self.start and e.end <= self.end:
return True
if e.start < self.start and e.end > self.end:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isPositiveStrand(self):
""" Check if this genomic region is on the positive strand. :return: True if this element is on the positive strand """ |
if self.strand is None and self.DEFAULT_STRAND == self.POSITIVE_STRAND:
return True
return self.strand == self.POSITIVE_STRAND |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isNegativeStrand(self):
""" Check if this genomic interval is on the negative strand. :return: True if this element is on the negative strand """ |
if self.strand is None and self.DEFAULT_STRAND == self.NEGATIVE_STRAND:
return True
return self.strand == self.NEGATIVE_STRAND |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_center(self, size):
""" Tranform self so it is centered on the same spot, but has new size. If the region grows, the extra nucleotides will be dist... |
if size < 1:
raise GenomicIntervalError("Cannot resize genomic interval to " +
str(size) + " bases; must be at least 1 " +
"base in length")
if size == len(self):
return
elif size > len(self):
extra = size - len(self)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_model(self, request, obj, form, change):
""" If the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``, send a notification email to the user being save... |
must_send_verification_mail_after_save = False
if change and settings.ACCOUNTS_APPROVAL_REQUIRED:
if obj.is_active and not User.objects.get(id=obj.id).is_active:
if settings.ACCOUNTS_VERIFICATION_REQUIRED:
# Accounts verification requires an inactive acco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy(self, machine):
"""Deploy service.""" |
log.debug("machine id: %s." % machine)
path = self.path + "/machines"
value, metadata = yield self.client.get(path)
machines = json.loads(value)
machines.append(machine)
yield self.client.set(path, json.dumps(machines)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self):
"""Add service definition to hierarchy.""" |
yield self.client.create(self.path)
yield self.client.create(self.path + "/type", self.name)
yield self.client.create(self.path + "/state")
yield self.client.create(self.path + "/machines", "[]")
log.debug("registered service '%s' at %s." % (self.name, self.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 _insert_cache(self, key, val, read):
'''
Does an insert into the cache such that the cache
will have an updated entry for the key,value,read
tuple. Any changes to those values will both update
the local cache and queue any required writes to the
database.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _sync_writes(self):
'''
Flushes the write queue
'''
for key in self._wqueue:
val = self._cache[key]
self._database[key] = val
del self._wqueue
self._wqueue = set()
self._database.sync() |
<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_cache(self):
'''
Drops all changes in the cache.
'''
del self._cache
self._cache = {}
del self._wqueue
self._wqueue = set()
self._cur_size = 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(self, *args, **kwargs):
'''
Updates the set to include all arguments passed in. If the keyword
argument preprocess is passed, then each element is preprocessed
before being added.
'''
preprocess = kwargs.get('preprocess')
for s in 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 get_episode_number(episode: Episode) -> int: """Get the episode number. The episode number is unique for an anime and episode type, but not across episode typ... |
match = _NUMBER_SUFFIX.search(episode.epno)
return int(match.group(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 get_episode_title(episode: Episode) -> int: """Get the episode title. Japanese title is prioritized. """ |
for title in episode.titles:
if title.lang == 'ja':
return title.title
else:
return episode.titles[0].title |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_element_text(element, match, default=None):
"""Find a matching subelement and return its text. If default is given, return it if a matching subelement ... |
child = element.find(match)
try:
return child.text
except AttributeError:
if default is not None:
return default
else:
raise MissingElementError(element, match) |
<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_episode(element: ET.Element):
"""Unpack Episode from episode XML element.""" |
return Episode(
epno=element.find('epno').text,
type=int(element.find('epno').get('type')),
length=int(element.find('length').text),
titles=tuple(_unpack_episode_title(title)
for title in element.iterfind('title')),
) |
<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_episode_title(element: ET.Element):
"""Unpack EpisodeTitle from title XML element.""" |
return EpisodeTitle(title=element.text,
lang=element.get(f'{XML}lang')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self):
"""Validate the resource using its voluptuous schema""" |
try:
# update _resource to have default values from the schema
self._resource = self.schema(self._resource)
except MultipleInvalid as e:
errors = [format_error(err, self.resource_type) for err in e.errors]
raise exceptions.ValidationError({'errors': error... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save(self):
""" Save the resource It's better to use the create, updated & delete methods intsead of modifying an instance and calling save, because then we... |
yield self.validate()
db = self.db_client()
saved = yield db.save_doc(self._resource)
# Allow couch to create Document IDs
if '_id' not in self._resource:
self._resource['_id'] = saved['id'] |
<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_subresource(self, subresource):
""" Save the sub-resource NOTE: Currently assumes subresources are stored within a dictionary, keyed with the subresourc... |
data = deepcopy(subresource._resource)
data.pop('id', None)
data.pop(self.resource_type + '_id', None)
subresources = getattr(self, subresource.parent_key, {})
subresources[subresource.id] = data
setattr(self, subresource.parent_key, subresources)
yield self._s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, user):
"""Delete a resource""" |
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
doc = {
'_id': self.id,
'_deleted': True
}
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_subresource(self, subresource):
""" Delete the sub-resource NOTE: Currently assumes subresources are stored within a dictionary, keyed with the subres... |
subresources = getattr(self, subresource.parent_key, {})
del subresources[subresource.id]
yield 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 state(self):
"""Get the Document's state""" |
state = self._resource.get('state', self.default_state)
if state in State:
return state
else:
return getattr(State, state) |
<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_parent(self):
""" Get the parent resource from the database The get, create & update methods will populate the parent for you. Use this method in the cas... |
if not self._parent:
self._parent = yield self.parent_resource.get(self.parent_id)
raise Return(self._parent) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parent_resources(cls):
"""Get a list of parent resources, starting from the Document""" |
parent = cls.parent_resource
parents = [parent]
try:
while True:
parent = parent.parent_resource
parents.append(parent)
except AttributeError:
pass
parents.reverse()
return parents |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, user, **kwargs):
"""If parent resource is not an editable state, should not be able to create.""" |
parent_id = kwargs.get(cls.parent_resource.resource_type + '_id')
try:
parent = yield cls.parent_resource.get(parent_id)
except couch.NotFound:
msg = 'Parent {} with id {} not found'.format(
cls.parent_resource.resource_type,
parent_id)
... |
<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(self, user, **kwargs):
"""If parent resource is not an editable state, should not be able to update""" |
yield self.get_parent()
if not self.parent.editable:
err = 'Cannot update child of {} resource'.format(self.parent.state.name)
raise exceptions.Unauthorized(err)
yield super(SubResource, self).update(user, **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 _save(self):
"""Save the sub-resource within the parent resource""" |
yield self.validate()
try:
self._parent = yield self.parent_resource.get(self.parent_id)
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.Validation... |
<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, user):
"""Delete a sub-resource""" |
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
try:
parent = yield self.get_parent()
except couch.NotFound:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def state(self):
""" Get the SubResource state If the parents state has a higher priority, then it overrides the SubResource state ..note:: This assumes that sel... |
state = self._resource.get('state', self.default_state)
if state not in State:
state = getattr(State, state)
if not self.parent:
raise Exception('Unable to check the parent state')
parent_state = self.parent.state
return max([state, parent_state], key=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_tasks(self):
""" Get all the tasks for a release. :param release_id: int, release id number. :returns: deferred that when fired returns a list of Mu... |
url = 'api/v6/releases/%d/schedule-tasks' % self.id
tasks = yield self.connection._get(url)
defer.returnValue(munchify(tasks)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def task_date(self, task_re):
""" Get a datetime.date object for the last task that matches a regex. :param task_re: regex, eg re.compile('Development Freeze'). ... |
tasks = yield self.schedule_tasks()
task_date = None
for task in tasks:
if task_re.match(task['name']):
(y, m, d) = task['date_finish'].split('-')
task_date = date(int(y), int(m), int(d))
if task_date:
defer.returnValue(task_date)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, event = None):
"""Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.""" |
for section in self.config.sections():
# Run through the sections to check all the option values:
for option, o in self.config.config[section].items():
# Check the actual values against the validators and complain if necessary:
if not o['include']:
continue # This value is hidden, so there's... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _detect_notebook():
""" This isn't 100% correct but seems good enough Returns ------- bool True if it detects this is a notebook, otherwise False. """ |
try:
from IPython import get_ipython
from ipykernel import zmqshell
except ImportError:
return False
kernel = get_ipython()
return isinstance(kernel, zmqshell.ZMQInteractiveShell) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xlim(self, low, high):
"""Set xaxis limits Parameters low : number high : number Returns ------- Chart """ |
self.chart['xAxis'][0]['min'] = low
self.chart['xAxis'][0]['max'] = high
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ylim(self, low, high):
"""Set yaxis limits Parameters low : number high : number index : int, optional Returns ------- Chart """ |
self.chart['yAxis'][0]['min'] = low
self.chart['yAxis'][0]['max'] = high
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_val(source, extract=None, transform=None):
"""Extract a value from a source, transform and return it.""" |
if extract is None:
raw_value = source
else:
raw_value = extract(source)
if transform is None:
return raw_value
else:
return transform(raw_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 get_obj(source, extract=None, child_transform=None, transform=None):
"""Maps an object based on a key->extractor child_transform dict.""" |
if extract is None:
obj = source
else:
obj = extract(source)
if child_transform is None:
data = obj
else:
data = dict()
for k, v in child_transform.items():
try:
data[k] = v(obj)
except Exception as ex:
raise Exception("An error occurred with child {0}".format(k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_lst(source, extract=None, transform=None):
"""Extract a list from a source, transform each item, and return the result.""" |
if extract is None:
raw_list = source
else:
raw_list = extract(source)
if transform is None:
return raw_list
else:
tlist = []
for idx, item in enumerate(raw_list):
try:
tlist.append(transform(item))
except Exception as ex:
raise Exception("An error occurred with... |
<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_composition(source, *fxns):
"""Compose several extractors together, on a source.""" |
val = source
for fxn in fxns:
val = fxn(val)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_flattened(dct, names, path_joiner="_"):
"""Flatten a child dicts, whose resulting keys are joined by path_joiner. E.G. { "valuation": { "currency": "USD"... |
new_dct = dict()
for key, val in dct.items():
if key in names:
child = {path_joiner.join(k): v for k, v in flatten_dict(val, (key, ))}
new_dct.update(child)
else:
new_dct[key] = dct[key]
return new_dct |
<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_hoisted(dct, child_name):
"""Pulls all of a child's keys up to the parent, with the names unchanged.""" |
child = dct[child_name]
del dct[child_name]
dct.update(child)
return dct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def obj(extract=None, child_transform=None, transform=None):
"""Returns a partial of get_obj that only needs a source argument.""" |
return lambda source: get_obj(source, extract, child_transform, transform) |
<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_xml_attr(source, name, path=None):
"""Get the XML attribute with name from source. If path is not Mone, it will instead get the XML attribute with name f... |
if path is None:
return source.attrib[name]
else:
return get_xml_attr(get_xml_child(source, path), name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_xml_text(source, path=None):
"""Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path. ""... |
if path is None:
return source.text
else:
return get_xml_text(get_xml_child(source, 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_xml_child(source, path):
"""Get the first descendant of source identified by path. Path must be either a an xpath string, or a 2-tuple of (xpath, namespa... |
if isinstance(path, (tuple, list)):
return source.find(*path)
else:
return source.find(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_xml_children(source, path):
"""Get all the descendants of source identified by path. Path must be either a an xpath string, or a 2-tuple of (xpath, names... |
if isinstance(path, (tuple, list)):
return source.findall(*path)
else:
return source.findall(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_json_val(source, path, *, ignore_bad_path=False):
"""Get the nested value identified by the json path, rooted at source.""" |
try:
return JP.find(source, path)
except JP.JSONPathError as ex:
if ignore_bad_path:
return None
else:
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 json_val(path, *, ignore_bad_path=False):
"""Returns a partial of get_json_val that only needs a source argument.""" |
return lambda source: get_json_val(source, path, ignore_bad_path=ignore_bad_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 register_defs(self, def_list, **kwargs):
""" Registers a list of Rml defintions objects Args: ----- def_list: list of objects defining the rml definitons """ |
for item in def_list:
if isinstance(item, tuple):
self.register_rml_def(*item, **kwargs)
elif isinstance(item, dict):
cp_kwargs = kwargs.copy()
item.update(kwargs)
self.register_rml_def(**item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_rml_def(self, location_type, location, filename=None, **kwargs):
""" Registers the rml file locations for easy access Args: ----- location_type: ['p... |
if location_type == 'directory':
self.register_directory(location, **kwargs)
elif location_type == 'filepath':
if not os.path.exists(location):
raise OSError("File not found", location)
if os.path.isfile(location):
self.register_rml(lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_rml(self, filepath, **kwargs):
""" Registers the filepath for an rml mapping Args: ----- filepath: the path the rml file """ |
name = os.path.split(filepath)[-1]
if name in self.rml_maps and self.rml_maps[name] != filepath:
raise Exception("RML name already registered. Filenames must be "
"unique.",
(self.rml_maps[name], filepath))
self.rml_maps[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 register_directory(self, dirpath, **kwargs):
""" Registers all of the files in the the directory path """ |
kwargs['file_extensions'] = kwargs.get("file_extensions",
self.rdf_formats)
files = list_files(file_directory=dirpath, **kwargs)
for fileinfo in files:
self.register_rml(fileinfo[-1], **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 make_processor(self, name, mappings, processor_type, **kwargs):
""" Instantiates a RmlProcessor and registers it in the manager Args: ----- name: the name to... |
from .processor import Processor
if self.processors.get(name):
raise LookupError("processor has already been created")
if isinstance(mappings, list):
mappings = [self.get_rml(item) for item in mappings]
else:
mappings = [self.get_rml(mappings)]
... |
<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_processor(self, name, mappings=None, processor_type=None, **kwargs):
""" Returns the specified RML Processor """ |
try:
return self.processors[name]
except KeyError:
return self.make_processor(name,
mappings,
processor_type,
**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_rml(self, rml_name, rtn_format="filepath"):
""" returns the rml mapping filepath rml_name(str):
Name of the rml mapping to retrieve rtn_format: ['filepa... |
try:
rml_path = self.rml_maps[rml_name]
except KeyError:
if rml_name in self.rml_maps.values() or os.path.exists(rml_name):
rml_path = rml_name
else:
raise LookupError("rml_name '%s' is not registered" % rml_name)
if rtn_forma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filename(self, index):
'''
Get the absolute filename corresponding to a key; run the
key_transformer on the key and do a few other small things.
:raises TypeError: if the key_transformer returns something other than
a :py:class:`tuple` of :py:class:`strings <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 from_filename(self, filename):
'''
Convert an absolute filename into key.
'''
i = len(self.base_directory)
if filename[:i] != self.base_directory:
raise ValueError('Filename needs to start with "%s";\nyou passed "%s".' % (self.base_directory, filename))
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(self, spin, data):
""" The function which uses irc rfc regex to extract the basic arguments from the msg. """ |
data = data.decode(self.encoding)
field = re.match(RFC_REG, data)
if not field:
return
prefix = self.extract_prefix(field.group('prefix'))
command = field.group('command').upper()
args = self.extract_args(field.group('arguments'))
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_prefix(self, prefix):
""" It extracts an irc msg prefix chunk """ |
field = re.match(PREFIX_REG, prefix if prefix else '')
return (prefix,) if not field else field.group(1, 2, 3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_args(self, data):
""" It extracts irc msg arguments. """ |
args = []
data = data.strip(' ')
if ':' in data:
lhs, rhs = data.split(':', 1)
if lhs: args.extend(lhs.rstrip(' ').split(' '))
args.append(rhs)
else:
args.extend(data.split(' '))
return tuple(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 extract_ctcp(self, spin, nick, user, host, target, msg):
""" it is used to extract ctcp requests into pieces. """ |
# The ctcp delimiter token.
DELIM = '\001'
if not msg.startswith(DELIM) or not msg.endswith(DELIM):
return
ctcp_args = msg.strip(DELIM).split(' ')
spawn(spin, ctcp_args[0], (nick, user, host, target, msg), *ctcp_args[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 patch(self, spin, header, *args):
""" It spawns DCC TYPE as event. """ |
spawn(spin, 'DCC %s' % args[0], header, *args[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 print_commands(self, out=sys.stdout):
'''
utility method to print commands
and descriptions for @BotFather
'''
cmds = self.list_commands()
for ck in cmds:
if ck.printable:
out.write('%s\n' % ck) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, uri, **kw):
""" The money maker. """ |
expect = kw.pop("expect", [])
mime_body = kw.pop("mime_body", None)
headers = kw.pop("headers", {})
data = kw.pop("data", None)
if mime_body:
mimevalues = self.mimeobjects.get(mime_body.__class__)
if not mimevalues:
raise ClientExceptio... |
<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_user(self, username, profile, owner_privkey):
""" Update profile_hash on blockchain """ |
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'profile': profile,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer_user(self, username, transfer_address, owner_privkey):
""" Transfer name on blockchain """ |
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'transfer_address': transfer_address,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
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 create(controller_id, name):
"""Turn class into a kervi controller""" |
def _decorator(cls):
class _ControllerClass(cls, Controller):
def __init__(self):
Controller.__init__(self, controller_id, name)
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinst... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def input(input_id, name, value_class=NumberValue):
"""Add input to controller""" |
def _init():
return value_class(
name,
input_id=input_id,
is_input=True,
index=-1
)
def _decorator(cls):
setattr(cls, input_id, _init())
return cls
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 output(output_id, name, value_class=NumberValue):
"""Add output to controller""" |
def _init():
return value_class(
name,
input_id=output_id,
is_input=False,
index=-1
)
def _decorator(cls):
setattr(cls, output_id, _init())
return cls
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 _subset(subset, superset):
"""True if subset is a subset of superset. :param dict subset: subset to compare. :param dict superset: superset to compare. :retu... |
result = True
for k in subset:
result = k in superset and subset[k] == superset[k]
if not result:
break
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def button_with_image(size='medium', icon=None, text=None, title=None, button=False, name=None, target=False, disabled=False, extra_css=None, modal=None, data_tar... |
html = '<div class="button-std'
if disabled:
html += ' disabled'
html += '">'
if button:
html += '<button type="submit" name="%s" value="%s" class="%s">' % (name, title, icon)
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_parser():
""" Initialize the arguments parser. """ |
parser = argparse.ArgumentParser(
description="Automated development environment initialization")
parser.add_argument('--version', action='version',
version='%(prog)s ' + __version__)
subparsers = parser.add_subparsers(title="commands")
# List command
parser_list = subparsers.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 new_env(environment):
""" Create a new environment in the configuration and ask the user for the commands for this specific environment. """ |
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if environment in parser.sections():
print("Environment '%s' already exists" % environment)
return
print("Please introduce (in order) the commands for '%s'\n" % environme... |
<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_env(environment):
""" Remove an environment from the configuration. """ |
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if not parser.remove_section(environment):
print("Unknown environment type '%s'" % environment)
return
write_config(parser)
print("Removed environment '%s'" % enviro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_env(environment):
""" Show the commands for a given environment. """ |
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
try:
commands = parser.get(environment, "cmd").split("\n")
except KeyError:
print("Unknown environment type '%s'" % environment)
return
print("Environment: %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_env(environment, path):
""" Initialize a new environment in specified directory. If path does not exist, will try to create the directory structure rec... |
parser = read_config()
if environment not in parser.sections():
print("Unknown environment type '%s'" % environment)
return
if path and not os.path.isdir(path):
try:
os.makedirs(path)
except os.error:
print("Could not create directory structure")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_config():
""" Read the configuration file and parse the different environments. Returns: ConfigParser object """ |
if not os.path.isfile(CONFIG):
with open(CONFIG, "w"):
pass
parser = ConfigParser()
parser.read(CONFIG)
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 parse_action(action, parsed):
""" Parse the action to execute. """ |
if action == "list":
list_env()
elif action == "new":
new_env(parsed.environment)
elif action == "remove":
remove_env(parsed.environment)
elif action == "show":
show_env(parsed.environment)
elif action == "start":
start_env(parsed.environment, parsed.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 gen_pdf(rst_content, style_text, header=None, footer=FOOTER):
""" Create PDF file from `rst_content` using `style_text` as style. Optinally, add `header` or ... |
out_file_obj = StringIO()
with NamedTemporaryFile() as f:
f.write(style_text)
f.flush()
pdf = _init_pdf(f.name, header, footer)
# create PDF
pdf.createPdf(text=rst_content, output=out_file_obj, compressed=True)
# rewind file pointer to begin
out_file_obj.seek(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 define_parameters(**parameters):
"""Get a list of parameters to pass to AWS boto call.""" |
params = []
for key, value in parameters.items():
param = dict(ParameterKey=key, ParameterValue=value)
params.append(param)
return 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 create(self):
"""Deploy a cluster on Amazon's EKS Service configured for Jupyterhub Deployments. """ |
steps = [
(self.create_role, (), {}),
(self.create_vpc, (), {}),
(self.create_cluster, (), {}),
(self.create_node_group, (), {}),
(self.create_spot_nodes, (), {}),
(self.create_utilities, (), {}),
]
# Execute creation.
... |
<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):
"""Delete a running cluster.""" |
stacks = [
self.utilities_name,
self.spot_nodes_name,
self.node_group_name,
self.cluster_name,
self.vpc_name,
self.role_name
]
# Execute creation.
for stack in tqdm.tqdm(stacks, ncols=70):
self.delete_st... |
<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_template(self, template_name, **parameters):
"""Pull templates from the AWS templates folder""" |
template_path = pathlib.Path(self.template_dir).joinpath(template_name)
return get_template(template_path, **parameters) |
<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_stack(self, stack_name):
"""Teardown a stack.""" |
get_stack(stack_name)
CLIENT.delete_stack(
StackName=stack_name
)
DELETE_WAITER.wait(StackName=stack_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 create_stack( self, stack_name, stack_template_name, parameters=None, capabilities=None ):
"""Create a stack using Amazon's Cloud formation""" |
# Build template_path
stack_template_path = pathlib.Path(
self.template_dir).joinpath(stack_template_name)
# Create stack
create_stack(
stack_name,
stack_template_path,
parameters=parameters,
capabilities=capabilities
... |
<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_vpc(self):
"""Create a virtual private cloud on Amazon's Web services configured for deploying JupyterHubs. """ |
self.create_stack(
self.vpc_name,
'amazon-eks-vpc.yaml',
parameters=define_parameters(
VpcBlock="10.42.0.0/16",
Subnet01Block="10.42.1.0/24",
Subnet02Block="10.42.2.0/24",
Subnet03Block="10.42.3.0/24"
... |
<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_cluster(self):
"""Creates a cluster on Amazon EKS . """ |
self.create_stack(
self.cluster_name,
'amazon-eks-cluster.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
ControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_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 create_node_group(self):
"""Create on-demand node group on Amazon EKS. """ |
self.create_stack(
self.node_group_name,
'amazon-eks-nodegroup.yaml',
capabilities=['CAPABILITY_IAM'],
parameters=define_parameters(
ClusterName=self.cluster_name,
ClusterControlPlaneSecurityGroup=self.security_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 create_spot_nodes(self):
"""Create spot nodes. """ |
self.create_stack(
self.spot_nodes_name,
'amazon-spot-nodes.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
Subnets=self.subnet_ids,
NodeInstanceProfile=self.node_instance_profile,
NodeInstan... |
<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_utilities(self):
"""Create utitilies stack. """ |
self.create_stack(
self.utilities_name,
'amazon-utilities.yaml',
parameters=define_parameters(
Subnets=self.subnet_ids,
NodeSecurityGroup=self.node_security_group
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debugtoolbar_middleware_factory(app, handler):
"""Setup Debug middleware.""" |
dbtb = app.ps.debugtoolbar
@asyncio.coroutine
def debugtoolbar_middleware(request):
"""Integrate to application."""
# Check for debugtoolbar is enabled for the request
if not dbtb.cfg.enabled or any(map(request.path.startswith, dbtb.cfg.exclude)):
return (yield from ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self, app):
"""Setup the plugin and prepare application.""" |
super(Plugin, self).setup(app)
if 'jinja2' not in app.plugins:
raise PluginException('The plugin requires Muffin-Jinja2 plugin installed.')
self.cfg.prefix = self.cfg.prefix.rstrip('/') + '/'
self.cfg.exclude.append(self.cfg.prefix)
# Setup debugtoolbar templates
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject(self, state, response):
""" Inject Debug Toolbar code to response body. """ |
html = yield from self.app.ps.jinja2.render(
'debugtoolbar/inject.html',
static_path=self.cfg.prefix + 'static',
toolbar_url=self.cfg.prefix + state.id,
)
html = html.encode(state.request.charset or 'utf-8')
response.body = RE_BODY.sub(html + b'</body... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view(self, request):
""" Debug Toolbar. """ |
auth = yield from self.authorize(request)
if not auth:
raise HTTPForbidden()
request_id = request.match_info.get('request_id')
state = self.history.get(request_id, None)
response = yield from self.app.ps.jinja2.render(
'debugtoolbar/toolbar.html',
... |
<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_dict(self, info_dict):
"""Replaces empty content with 'NA's""" |
for key, value in info_dict.items():
if not value:
info_dict[key] = "NA"
return info_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 split_addresses(email_string_list):
""" Converts a string containing comma separated email addresses into a list of email addresses. """ |
return [f for f in [s.strip() for s in email_string_list.split(",")] if 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 subject_template(template, context):
""" Loads and renders an email subject template, returning the subject string. """ |
subject = loader.get_template(template).render(Context(context))
return " ".join(subject.splitlines()).strip() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.