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 visit_Compound(self, node):
"""Visitor for `Compound` AST node.""" |
self.memory.append_scope()
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_UnaryOperation(self, node):
"""Visitor for `UnaryOperation` AST node.""" |
if node.op.nature == Nature.PLUS:
return +self.visit(node.right)
elif node.op.nature == Nature.MINUS:
return -self.visit(node.right)
elif node.op.nature == Nature.NOT:
return Bool(not self.visit(node.right)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Boolean(self, node):
"""Visitor for `Boolean` AST node.""" |
if node.value == 'true':
return Bool(True)
elif node.value == 'false':
return Bool(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 interpret(self):
"""Generic entrypoint of `Interpreter` class.""" |
self.load_builtins()
self.load_functions(self.tree)
self.visit(self.tree) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def up(name, debug=False):
'''
Create servers and containers as required to meet the configuration
specified in _name_.
Args:
* name: The name of the yaml config file (you can omit the .yml extension for convenience)
Example:
fab ensemble.up:wordpress
'''
if debug:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(name, file=sys.stderr):
""" Stop a profiling timer. Arguments: name (str):
The name of the timer to stop. If no name is given, stop the global anonymou... |
if is_enabled():
elapsed = (time() - __TIMERS[name])
if elapsed > 60:
elapsed_str = '{:.1f} m'.format(elapsed / 60)
elif elapsed > 1:
elapsed_str = '{:.1f} s'.format(elapsed)
else:
elapsed_str = '{:.1f} ms'.format(elapsed * 1000)
del __TI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(fun, *args, **kwargs):
""" Profile a function. """ |
timer_name = kwargs.pop("prof_name", None)
if not timer_name:
module = inspect.getmodule(fun)
c = [module.__name__]
parentclass = labtypes.get_class_that_defined_method(fun)
if parentclass:
c.append(parentclass.__name__)
c.append(fun.__name__)
timer_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geh(m, c):
"""Error function for hourly traffic flow measures after Geoffrey E. Havers""" |
if m + c == 0:
return 0
else:
return math.sqrt(2 * (m - c) * (m - c) / (m + c)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def avg(self):
"""return the mean value""" |
# XXX rename this method
if len(self.values) > 0:
return sum(self.values) / float(len(self.values))
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 avg_abs(self):
"""return the mean of absolute values""" |
# XXX rename this method
if len(self.values) > 0:
return sum(map(abs, self.values)) / float(len(self.values))
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 meanAndStdDev(self, limit=None):
"""return the mean and the standard deviation optionally limited to the last limit values""" |
if limit is None or len(self.values) < limit:
limit = len(self.values)
if limit > 0:
mean = sum(self.values[-limit:]) / float(limit)
sumSq = 0.
for v in self.values[-limit:]:
sumSq += (v - mean) * (v - mean)
return mean, math.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 relStdDev(self, limit=None):
"""return the relative standard deviation optionally limited to the last limit values""" |
moments = self.meanAndStdDev(limit)
if moments is None:
return None
return moments[1] / moments[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 mean(self):
"""return the median value""" |
# XXX rename this method
if len(self.values) > 0:
return sorted(self.values)[len(self.values) / 2]
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 mean_abs(self):
"""return the median of absolute values""" |
# XXX rename this method
if len(self.values) > 0:
return sorted(map(abs, self.values))[len(self.values) / 2]
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 copy_resources_to_log_dir(log_dir):
"""Copies the necessary static assets to the log_dir and returns the path of the main css file.""" |
css_path = resource_filename(Requirement.parse("egat"), "/egat/data/default.css")
header_path = resource_filename(Requirement.parse("egat"), "/egat/data/egat_header.png")
shutil.copyfile(css_path, log_dir + "/style.css")
shutil.copyfile(header_path, log_dir + "/egat_header.png")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_queue(queue):
""" Empties all pending items in a queue and returns them in a list. """ |
result = []
try:
while True:
item = queue.get_nowait()
result.append(item)
except: Empty
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 execute(command, cwd=os.path.curdir, **options):
""" Run the system command with optional options. Args: * command: system command. * cwd: current working di... |
process = subprocess.Popen(shlex.split(command), cwd=cwd, **options)
stdout, stderr = process.communicate()
return process, stdout, stderr |
<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_dict(self, copy=False):
"""Convert the struct to a dictionary. If `copy == True`, returns a deep copy of the values. """ |
new_dict = {}
for attr, value in self:
if copy:
value = deepcopy(value)
new_dict[attr] = value
return new_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 start(self):
"""Start the process, essentially forks and calls target function.""" |
logger.info("starting process")
process = os.fork()
time.sleep(0.01)
if process != 0:
logger.debug('starting child watcher')
self.loop.reset()
self.child_pid = process
self.watcher = pyev.Child(self.child_pid, False, self.loop, self._chil... |
<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(settings):
""" Setup the database connection. """ |
connector = settings.get('db_connector')
if connector == 'postgres':
from playhouse.pool import PooledPostgresqlExtDatabase
return PooledPostgresqlExtDatabase(settings['db_name'],
user=settings['db_user'],
password=settings['db_password'],
... |
<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(module, db):
""" Initialize the models. """ |
for model in farine.discovery.import_models(module):
model._meta.database = db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self, extras=None):
""" Convert a model into a json using the playhouse shortcut. """ |
extras = extras or {}
to_dict = model_to_dict(self)
to_dict.update(extras)
return json.dumps(to_dict, cls=sel.serializers.JsonEncoder) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy(func):
""" Decorator, which can be used for lazy imports @lazy def yaml():
import yaml return yaml """ |
try:
frame = sys._getframe(1)
except Exception:
_locals = None
else:
_locals = frame.f_locals
func_name = func.func_name if six.PY2 else func.__name__
return LazyStub(func_name, func, _locals) |
<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_reftrack(self, reftrack):
"""Add a reftrack object to the root. This will not handle row insertion in the model! It is automatically done when setting th... |
self._reftracks.add(reftrack)
refobj = reftrack.get_refobj()
if refobj:
self._parentsearchdict[refobj] = reftrack |
<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_reftrack(self, reftrack):
"""Remove the reftrack from the root. This will not handle row deletion in the model! It is automatically done when calling ... |
self._reftracks.remove(reftrack)
refobj = reftrack.get_refobj()
if refobj and refobj in self._parentsearchdict:
del self._parentsearchdict[refobj] |
<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_refobj(self, old, new, reftrack):
"""Update the parent search dict so that the reftrack can be found with the new refobj and delete the entry for the ... |
if old:
del self._parentsearchdict[old]
if new:
self._parentsearchdict[new] = reftrack |
<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_scene_suggestions(self, refobjinter):
"""Return a list of suggested Reftracks for the current scene, that are not already in this root. A suggestion is a... |
sugs = []
cur = refobjinter.get_current_element()
if not cur:
return sugs
for typ in refobjinter.types:
inter = refobjinter.get_typ_interface(typ)
elements = inter.get_scene_suggestions(cur)
for e in elements:
for r in 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_unwrapped(self, root, refobjinter):
"""Return a set with all refobjects in the scene that are not in already wrapped in root. :param root: the root that ... |
all_refobjs = set(refobjinter.get_all_refobjs())
wrapped = set(root._parentsearchdict.keys())
return all_refobjs - wrapped |
<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_refobj(self, refobj, setParent=True):
"""Set the reftrack object. The reftrack object interface will determine typ, element, taskfileinfo, status and par... |
root = self.get_root()
old = self._refobj
self._refobj = refobj
refobjinter = self.get_refobjinter()
if self._refobj:
self.set_typ(refobjinter.get_typ(self._refobj))
self.set_taskfileinfo(refobjinter.get_taskfileinfo(self._refobj))
self.set_el... |
<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_typ(self, typ):
"""Set the type of the entity Make sure the type is registered in the :class:`RefobjInterface`. :param typ: the type of the entity :type ... |
if typ not in self._refobjinter.types:
raise ValueError("The given typ is not supported by RefobjInterface. Given %s, supported: %s" %
(typ, self._refobjinter.types.keys()))
self._typ = typ
self._typicon = self.get_refobjinter().get_typ_icon(typ) |
<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_parent(self, parent):
"""Set the parent reftrack object If a parent gets deleted, the children will be deleted too. .. Note:: Once the parent is set, it ... |
assert self._parent is None or self._parent is parent,\
"Cannot change the parent. Can only set from None."
if parent and self._parent is parent:
return
self._parent = parent
if parent:
refobjinter = self.get_refobjinter()
refobj = self.ge... |
<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_id(self, identifier):
"""Set the id of the given reftrack This will set the id on the refobject :param identifier: the identifier number :type identifier... |
self._id = identifier
refobj = self.get_refobj()
if refobj:
self.get_refobjinter().set_id(refobj, identifier) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_new_id(self, ):
"""Return a new id for the given reftrack to be set on the refobject The id can identify reftracks that share the same parent, type and... |
parent = self.get_parent()
if parent:
others = parent._children
else:
others = [r for r in self.get_root()._reftracks if r.get_parent() is None]
others = [r for r in others
if r != self
and r.get_typ() == self.get_typ()
... |
<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_treeitem(self, ):
"""Create a new treeitem for this reftrack instance. .. Note:: Parent should be set, Parent should already have a treeitem. If there... |
p = self.get_parent()
root = self.get_root()
if p:
pitem = p.get_treeitem()
else:
pitem = root.get_rootitem()
idata = root.create_itemdata(self)
item = TreeItem(idata, parent=pitem)
return 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 fetch_options(self, ):
"""Set and return the options for possible files to load, replace etc. The stored element will determine the options. The refobjinterf... |
self._options, self._taskfileinfo_options = self.get_refobjinter().fetch_options(self.get_typ(), self.get_element())
return self._options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_uptodate(self, ):
"""Set and return whether the currently loaded entity is the newest version in the department. :returns: True, if newest version. Fal... |
tfi = self.get_taskfileinfo()
if tfi:
self._uptodate = tfi.is_latest()
else:
self._uptodate = None
return self._uptodate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_alien(self, ):
"""Set and return, if the reftrack element is linked to the current scene. Askes the refobj interface for the current scene. If there is... |
parent = self.get_parent()
if parent:
parentelement = parent.get_element()
else:
parentelement = self.get_refobjinter().get_current_element()
if not parentelement:
self._alien = True
return self._alien
element = self.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference(self, taskfileinfo):
"""Reference the entity into the scene. Only possible if the current status is None. This will create a new refobject, then ca... |
assert self.status() is None,\
"Can only reference, if the entity is not already referenced/imported. Use replace instead."
refobj = self.create_refobject()
with self.set_parent_on_new(refobj):
self.get_refobjinter().reference(taskfileinfo, refobj)
self.set_refob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, ):
"""If the reference is in the scene but unloaded, load it. .. Note:: Do not confuse this with reference or import. Load means that it is alread... |
assert self.status() == self.UNLOADED,\
"Cannot load if there is no unloaded reference. Use reference instead."
self.get_refobjinter().load(self._refobj)
self.set_status(self.LOADED)
self.fetch_new_children()
self.update_restrictions()
self.emit_data_changed(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unload(self, ):
"""If the reference is loaded, unload it. .. Note:: Do not confuse this with a delete. This means, that the reference stays in the scene, but... |
assert self.status() == self.LOADED,\
"Cannot unload if there is no loaded reference. \
Use delete if you want to get rid of a reference or import."
childrentodelete = self.get_children_to_delete()
if childrentodelete:
raise ReftrackIntegrityError("Cannot unload because ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_file(self, taskfileinfo):
"""Import the file for the given taskfileinfo This will also update the status to :data:`Reftrack.IMPORTED`. This will also ... |
assert self.status() is None,\
"Entity is already in scene. Use replace instead."
refobjinter = self.get_refobjinter()
refobj = self.create_refobject()
with self.set_parent_on_new(refobj):
refobjinter.import_taskfile(refobj, taskfileinfo)
self.set_refobj(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_reference(self, ):
"""Import the currently loaded reference This will also update the status to :data:`Reftrack.IMPORTED`. :returns: None :rtype: None... |
assert self.status() in (self.LOADED, self.UNLOADED),\
"There is no reference for this entity."
refobjinter = self.get_refobjinter()
refobjinter.import_reference(self.get_refobj())
self.set_status(self.IMPORTED)
self.update_restrictions()
for c in self.get_al... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, taskfileinfo):
"""Replace the current reference or imported entity. If the given refobj is not replaceable, e.g. it might be imported or it is ... |
assert self.status() is not None,\
"Can only replace entities that are already in the scene."
refobjinter = self.get_refobjinter()
refobj = self.get_refobj()
if self.status() in (self.LOADED, self.UNLOADED) and refobjinter.is_replaceable(refobj):
# possible orpha... |
<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, ):
"""Internal implementation for deleting a reftrack. This will just delete the reftrack, set the children to None, update the status, and the... |
refobjinter = self.get_refobjinter()
refobjinter.delete(self.get_refobj())
self.set_refobj(None, setParent=False)
if self.alien():
# it should not be in the scene
# so also remove it from the model
# so we cannot load it again
parent = sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_children(self):
"""Get all children including children of children :returns: all children including children of children :rtype: list of :class:`Reft... |
children = self._children[:]
oldlen = 0
newlen = len(children)
while oldlen != newlen:
start = oldlen
oldlen = len(children)
for i in range(start, len(children)):
children.extend(children[i]._children)
newlen = len(children... |
<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_children_to_delete(self):
"""Return all children that are not referenced :returns: list or :class:`Reftrack` :rtype: list :raises: None """ |
refobjinter = self.get_refobjinter()
children = self.get_all_children()
todelete = []
for c in children:
if c.status() is None:
# if child is not in scene we do not have to delete it
continue
rby = refobjinter.referenced_by(c.get_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_new_children(self, ):
"""Collect all new children and add the suggestions to the children as well When an entity is loaded, referenced, imported etc th... |
root = self.get_root()
refobjinter = self.get_refobjinter()
unwrapped = self.get_unwrapped(root, refobjinter)
self.wrap(self.get_root(), self.get_refobjinter(), unwrapped)
suggestions = self.get_suggestions()
for typ, element in suggestions:
for c in self._c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_parent_on_new(self, parentrefobj):
"""Contextmanager that on close will get all new unwrapped refobjects, and for every refobject with no parent sets is ... |
refobjinter = self.get_refobjinter()
# to make sure we only get the new one
# we get all current unwrapped first
old = self.get_unwrapped(self.get_root(), refobjinter)
yield
new = self.get_unwrapped(self.get_root(), refobjinter) - old
for refobj in new:
... |
<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_restricted(self, obj, restricted):
"""Set the restriction on the given object. You can use this to signal that a certain function is restricted. Then you... |
if restricted:
self._restricted.add(obj)
elif obj in self._restricted:
self._restricted.remove(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_reference_restriction(self, ):
"""Fetch whether referencing is restricted :returns: True, if referencing is restricted :rtype: :class:`bool` :raises: N... |
inter = self.get_refobjinter()
restricted = self.status() is not None
return restricted or inter.fetch_action_restriction(self, 'reference') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_load_restriction(self, ):
"""Fetch whether loading is restricted :returns: True, if loading is restricted :rtype: :class:`bool` :raises: None """ |
inter = self.get_refobjinter()
restricted = self.status() != self.UNLOADED
return restricted or inter.fetch_action_restriction(self, 'load') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_import_ref_restriction(self,):
"""Fetch whether importing the reference is restricted :returns: True, if importing the reference is restricted :rtype: ... |
inter = self.get_refobjinter()
restricted = self.status() not in (self.LOADED, self.UNLOADED)
return restricted or inter.fetch_action_restriction(self, 'import_reference') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_import_f_restriction(self,):
"""Fetch whether importing a file is restricted :returns: True, if import is restricted :rtype: :class:`bool` :raises: Non... |
inter = self.get_refobjinter()
restricted = self.status() is not None
return restricted or inter.fetch_action_restriction(self, 'import_taskfile') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit_data_changed(self):
"""Emit the data changed signal on the model of the treeitem if the treeitem has a model. :returns: None :rtype: None :raises: None ... |
item = self.get_treeitem()
m = item.get_model()
if m:
start = m.index_of_item(item)
parent = start.parent()
end = m.index(start.row(), item.column_count()-1, parent)
m.dataChanged.emit(start, end) |
<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, typ, identifier, parent=None):
"""Create a new refobj with the given typ and parent :param typ: the entity type :type typ: str :param identifier... |
refobj = self.create_refobj()
self.set_typ(refobj, typ)
self.set_id(refobj, identifier)
if parent:
self.set_parent(refobj, parent)
return refobj |
<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, refobj):
"""Delete the given refobj and the contents of the entity :param refobj: the refobj to delete :type refobj: refobj :returns: None :rtyp... |
i = self.get_typ_interface(self.get_typ(refobj))
i.delete(refobj)
self.delete_refobj(refobj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference(self, taskfileinfo, refobj):
"""Reference the given taskfile info and set the created reference on the refobj This will call :meth:`ReftypeInterfac... |
inter = self.get_typ_interface(self.get_typ(refobj))
ref = inter.reference(refobj, taskfileinfo)
self.set_reference(refobj, ref) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, refobj, taskfileinfo):
"""Replace the given refobjs reference with the taskfileinfo This will call :meth:`ReftypeInterface.replace`. :param ref... |
inter = self.get_typ_interface(self.get_typ(refobj))
ref = self.get_reference(refobj)
inter.replace(refobj, ref, taskfileinfo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_replaceable(self, refobj):
"""Return whether the given reference of the refobject is replaceable or if it should just get deleted and loaded again. This w... |
inter = self.get_typ_interface(self.get_typ(refobj))
return inter.is_replaceable(refobj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_reference(self, refobj):
"""Import the reference of the given refobj Here we assume, that the reference is already in the scene and we break the encap... |
inter = self.get_typ_interface(self.get_typ(refobj))
ref = self.get_reference(refobj)
inter.import_reference(refobj, ref)
self.set_reference(refobj, 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_element(self, refobj):
"""Return the element the refobj represents. The element is either an Asset or a Shot. :param refobj: the refobject to query :type... |
tf = self.get_taskfile(refobj)
return tf.task.element |
<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_labels(self, typ, element):
"""Return labels for each level of the option model. The options returned by :meth:`RefobjInterface.fetch_options` is ... |
inter = self.get_typ_interface(typ)
return inter.get_option_labels(element) |
<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_columns(self, typ, element):
"""Return the column of the model to show for each level Because each level might be displayed in a combobox. So you ... |
inter = self.get_typ_interface(typ)
return inter.get_option_columns(element) |
<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_suggestions(self, reftrack):
"""Return a list with possible children for this reftrack Each Reftrack may want different children. E.g. a Asset wants to s... |
inter = self.get_typ_interface(reftrack.get_typ())
return inter.get_suggestions(reftrack) |
<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_available_types_for_scene(self, element):
"""Return a list of types that can be used in combination with the given element to add new reftracks to the sc... |
available = []
for typ, inter in self.types.items():
if inter(self).is_available_for_scene(element):
available.append(typ)
return available |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pre_process_call(self, name="Unknown", endpoint_params=None):
""" This is called by the method_decorator within the Endpoint. The point is to capture a slot... |
call_temps = self._call_temps.get(self._get_thread_id(), None)
call_params = call_temps and call_temps.pop() or {}
default_params = dict(name=name,
label='ID_' + str(self._count),
base_uri=self.base_uri,
t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def function(fname):
""" Make a function to Function class """ |
def _f(func):
class WrapFunction(Function):
name = fname
def __call__(self, *args, **kwargs):
return func(*args, **kwargs)
return WrapFunction
return _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 parse_cookie(header, charset='utf-8', errors='ignore'):
"""Parse a cookie. :param header: the header to be used to parse the cookie. :param charset: the char... |
cookie = _ExtendedCookie()
if header:
cookie.load(header)
result = {}
# decode to unicode and skip broken items. Our extended morsel
# and extended cookie will catch CookieErrors and convert them to
# `None` items which we have to skip here.
for key, value in cookie.iteritems():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equals_as(self, value_type, other):
""" Compares this object value to specified specified value. When direct comparison gives negative results it converts va... |
if other == None and self.value == None:
return True
if other == None or self.value == None:
return False
if isinstance(other, AnyValue):
other = other._value
if other == self.value:
return True
value1 = TypeConverter.to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _collect_images(self, content: str, md_file_path: Path) -> str:
'''Find images outside the source directory, copy them into the source directory,
and replace the paths in the source.
This is necessary because MkDocs can't deal with images outside the project's doc_dir.
:param conte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_prop_attribute(cls, prop_name):
# @NoSelf """This methods returns True if there exists a class attribute for the given property. The attribute is searche... |
return (prop_name in cls.__dict__ and
not isinstance(cls.__dict__[prop_name], types.FunctionType)) |
<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_value_change(cls, old, new):
# @NoSelf """Checks whether the value of the property changed in type or if the instance has been changed to a different i... |
return (type(old) != type(new) or
isinstance(old, wrappers.ObsWrapperBase) and old != new) |
<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_getter(cls, prop_name, # @NoSelf user_getter=None, getter_takes_name=False):
"""Returns a function wich is a getter for a property. prop_name is the name... |
if user_getter:
if getter_takes_name: # wraps the property name
_deps = type(cls)._get_old_style_getter_deps(cls, prop_name,
user_getter)
def _getter(self, deps=_deps):
return user_get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25):
'''
Run a cone search of the GALEX archive
'''
self.magnitudelimit = magnitudelimit
# run the query
self.speak('querying GALEX, centered on {} with radius {}'.format(center, radius, magnitudelimit))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_nginx_site_conf(site_name, template_name=None, context=None, enable=True):
"""Upload Nginx site configuration from a template.""" |
template_name = template_name or [u'nginx/%s.conf' % site_name, u'nginx/site.conf']
site_available = u'/etc/nginx/sites-available/%s' % site_name
upload_template(template_name, site_available, context=context, use_sudo=True)
if enable:
enable_site(site_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 enable_site(site_name):
"""Enable an available Nginx site.""" |
site_available = u'/etc/nginx/sites-available/%s' % site_name
site_enabled = u'/etc/nginx/sites-enabled/%s' % site_name
if files.exists(site_available):
sudo(u'ln -s -f %s %s' % (site_available, site_enabled))
restart_service(u'nginx')
else:
abort(u'%s site configuration is not... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_site(site_name):
"""Disables Nginx site configuration.""" |
site = u'/etc/nginx/sites-enabled/%s' % site_name
if files.exists(site):
sudo(u'rm %s' % site)
restart_service(u'nginx') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def suppressConsoleOut(meth):
"""Disable console output during the method is run.""" |
@wraps(meth)
def decorate(*args, **kwargs):
"""Decorate"""
# Disable ansible console output
_stdout = sys.stdout
fptr = open(os.devnull, 'w')
sys.stdout = fptr
try:
return meth(*args, **kwargs)
except Exception as e:
raise e
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None):
"""Execute the mount. This requires root""" |
ensure_directories(mount_point, lower_dir, upper_dir)
# Load the mount table if it isn't given
if not mount_table:
mount_table = MountTable.load()
# Check if the mount_point is in use
if mount_table.is_mounted(mount_point):
# Throw an error if it is
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_opened(components):
""" Checks if all components are opened. To be checked components must implement [[IOpenable]] interface. If they don't the call to th... |
if components == None:
return True
result = True
for component in components:
result = result and Opener.is_opened_one(component)
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 open(correlation_id, components):
""" Opens multiple components. To be opened components must implement [[IOpenable]] interface. If they don't the call to th... |
if components == None:
return
for component in components:
Opener.open_one(correlation_id, component) |
<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_temperature(self):
"""Gets the compensated temperature in degrees celsius.""" |
UT = self.read_raw_temp()
# Datasheet value for debugging:
#UT = 27898
# Calculations below are taken straight from section 3.5 of the datasheet.
X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15
X2 = (self.cal_MC << 11) // (X1 + self.cal_MD)
B5 = X1 + X2
t... |
<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_pressure(self):
"""Gets the compensated pressure in Pascals.""" |
UT = self.read_raw_temp()
UP = self.read_raw_pressure()
# Datasheet values for debugging:
#UT = 27898
#UP = 23843
# Calculations below are taken straight from section 3.5 of the datasheet.
# Calculate true temperature coefficient B5.
X1 = ((UT - self.cal_... |
<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_rendition_url(request, image_id, target_width=0, target_height=0):
'''
get a rendition url
if the rendition does nto exist it will be created in the storage
if dimensions do not fit master's aspect ratio
then image will be cropped with a centered anchor
if one dimensions is omitted (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 get_master_url(request, image_id):
'''
get image's master url
...
:param request: http GET request /renderer/master/url/<image_id>/
:param image_id: the master image primary key
:return: master url in a json dictionary
'''
im = get_object_or_404(MasterImage, pk=image_id)
retur... |
<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_results(self,results):
""" The resolve server responds with some basic HTML formatting, where the actual results are listed as an HTML list. The regu... |
reslist = []
cursor = 0
match = RE_RESULTS.search(results,cursor)
while match:
doc = {}
doc['bibcode'] = match.group('bibcode')
doc['confidence'] = self.__get_confidence_level(match.group('confidence'))
doc['refstring'] = match.group('ref... |
<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_domain_config(self, domain):
"""Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: Domai... |
domain_root = self.identify_domain_root(domain)
host = ''
if len(domain_root) != len(domain):
host = domain.replace('.' + domain_root, '')
domain_connect_api = self._identify_domain_connect_api(domain_root)
ret = self._get_domain_config_for_root(domain_root, domai... |
<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_domain_connect_template_sync_url(self, domain, provider_id, service_id, redirect_uri=None, params=None, state=None, group_ids=None):
"""Makes full Domain... |
# TODO: support for signatures
# TODO: support for provider_name (for shared templates)
if params is None:
params = {}
config = self.get_domain_config(domain)
self.check_template_supported(config, provider_id, service_id)
if config.urlSyncUX is 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_domain_connect_template_async_context(self, domain, provider_id, service_id, redirect_uri, params=None, state=None, service_id_in_path=False):
"""Makes f... |
if params is None:
params = {}
config = self.get_domain_config(domain)
self.check_template_supported(config, provider_id, service_id)
if config.urlAsyncUX is None:
raise InvalidDomainConnectSettingsException("No asynch UX URL in config")
if service_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 get_async_token(self, context, credentials):
"""Gets access_token in async process :param context: DomainConnectAsyncContext :param credentials: DomainConnec... |
params = {'code': context.code, 'grant_type': 'authorization_code'}
if getattr(context, 'iat', None) and getattr(context, 'access_token_expires_in', None) and \
getattr(context, 'refresh_token', None):
now = int(time.time()) + 60
if now > context.iat + context.ac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def httpretty_callback(request, uri, headers):
"""httpretty request handler. converts a call intercepted by httpretty to the stack-in-a-box infrastructure :param... |
method = request.method
response_headers = CaseInsensitiveDict()
response_headers.update(headers)
request_headers = CaseInsensitiveDict()
request_headers.update(request.headers)
request.headers = request_headers
return StackInABox.call_into(method,
request,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def registration(uri):
"""httpretty handler registration. registers a handler for a given uri with httpretty so that it can be intercepted and handed to stack-in... |
# add the stack-in-a-box specific response codes to
# http's status information
status_data = {
595: 'StackInABoxService - Unknown Route',
596: 'StackInABox - Exception in Service Handler',
597: 'StackInABox - Unknown Service'
}
for k, v in six.iteritems(status_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 value(self):
""" Return the value of the redirect response """ |
user = self.trigger.agentml.request_log.most_recent().user
groups = self.trigger.agentml.request_log.most_recent().groups
# Does the redirect statement have tags to parse?
if len(self._element):
message = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, 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 onHello(self, realm, details):
""" Callback fired when client wants to attach session. """ |
log.msg("onHello: {} {}".format(realm, details))
self._pending_auth = None
if details.authmethods:
for authmethod in details.authmethods:
if authmethod == u"wampcra":
## lookup user in user DB
salt, key, role, uid = yield se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onAuthenticate(self, signature, extra):
""" Callback fired when a client responds to an authentication challenge. """ |
log.msg("onAuthenticate: {} {}".format(signature, extra))
## if there is a pending auth, and the signature provided by client matches ..
if self._pending_auth:
if signature == self._pending_auth.signature:
## accept the client
return types.Accept(a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_stdout_logger(log_level=logging.DEBUG):
"""Configures logging to use STDOUT""" |
root = logging.getLogger()
root.setLevel(log_level)
handler = logging.StreamHandler()
handler.setLevel(log_level)
handler.setFormatter(logging.Formatter(LOG_FORMAT_ESCAPED))
root.addHandler(handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def silence_logging(method):
"""Disables logging for the duration of what is being wrapped. This is particularly useful when testing if a test method is supposed... |
@wraps(method)
def wrapper(*args, **kwargs):
logging.disable(logging.ERROR)
result = method(*args, **kwargs)
logging.disable(logging.NOTSET)
return result
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 do_create_tool_item(self):
"""This is called by the UIManager when it is time to instantiate the proxy""" |
proxy = SpinToolItem(*self._args_for_toolitem)
self.connect_proxy(proxy)
return proxy |
<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_value(self, value):
"""Set value to action.""" |
self._value = value
for proxy in self.get_proxies():
proxy.handler_block(self._changed_handlers[proxy])
proxy.set_value(self._value)
proxy.handler_unblock(self._changed_handlers[proxy])
pass
self.emit('changed')
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(ctx):
""" clean generated project files """ |
os.chdir(PROJECT_DIR)
patterns = ['.cache',
'.coverage',
'.eggs',
'build',
'dist']
ctx.run('rm -vrf {0}'.format(' '.join(patterns)))
ctx.run('''find . \( -name '*,cover' -o -name '__pycache__' -o -name '*.py[co]' -o -name '_work' \) '''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.