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 loads(astring):
"""Decompress and deserialize string into a Python object via pickle.""" |
try:
return pickle.loads(lzma.decompress(astring))
except lzma.LZMAError as e:
raise SerializerError(
'Cannot decompress object ("{}")'.format(str(e))
)
except pickle.UnpicklingError as e:
raise SerializerError(
'Ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, path_expression, mode=UXP, values=None, ifunc=lambda x: x):
""" find matches for the given path expression in the data :param path_expression: p... |
# keys = path_expression if isinstance(path_expression, six.string_types) else path_expression[-1]
path_and_value_list = iterutils.search(
self.data,
path_expression=path_expression,
required_values=values,
exact=(mode[1] == "x"))
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 __visit_index_path(self, src, p, k, v):
""" Called during processing of source data """ |
cp = p + (k,)
self.path_index[cp] = self.indexed_obj_factory(p, k, v, self.path_index.get(cp))
if cp in self.path_index:
# if self.path_index[cp].assert_val_equals(v):
# raise ValueError('unexpected value change at path_index[{}]'.format(cp))
self.path_in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_default_data_path(*args, module=None, class_=None, flag_raise=True):
""" Returns path to default data directory Arguments 'module' and 'class' give the c... |
if module is None:
module = __get_filetypes_module()
if class_ is not None:
pkgname = class_.__module__
mseq = pkgname.split(".")
if len(mseq) < 2 or mseq[1] != "filetypes":
raise ValueError("Invalid module name for class '{}': '{}' "
"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_default_data_file(filename, module=None):
"""Copies file from default data directory to local directory.""" |
if module is None:
module = __get_filetypes_module()
fullpath = get_default_data_path(filename, module=module)
shutil.copy(fullpath, ".") |
<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_display(self):
""" Find a usable display, which doesn't have an existing Xvfb file """ |
self.display_num = 2
while os.path.isdir(XVFB_PATH % (self.display_num,)):
self.display_num += 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 comments(recid):
"""Display comments.""" |
from invenio_access.local_config import VIEWRESTRCOLL
from invenio_access.mailcookie import \
mail_cookie_create_authorize_action
from .api import check_user_can_view_comments
auth_code, auth_msg = check_user_can_view_comments(current_user, recid)
if auth_code and current_user.is_guest:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getattr(self, key, default=None, callback=None):
u"""Getting the attribute of an element. 'text' 'TEXT' 'default' """ |
value = self._xml.text if key == 'text' else self._xml.get(key, default)
return callback(value) if callback else 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 setattr(self, key, value):
u"""Sets an attribute on a node. 'text2' 'val' """ |
if key == 'text':
self._xml.text = str(value)
else:
self._xml.set(key, str(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(self, default=None, callback=None):
u"""Returns leaf's value.""" |
value = self._xml.text if self._xml.text else default
return callback(value) if callback else 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 to_str(self, pretty_print=False, encoding=None, **kw):
u"""Converts a node with all of it's children to a string. Remaining arguments are passed to etree.tos... |
if kw.get('without_comments') and not kw.get('method'):
kw.pop('without_comments')
kw['method'] = 'c14n'
kw['with_comments'] = False
return etree.tostring(
self._xml,
pretty_print=pretty_print,
encoding=encoding,
**kw
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_children(self, key=None):
u"""Iterates over children. :param key: A key for filtering children by tagname. """ |
tag = None
if key:
tag = self._get_aliases().get(key)
if not tag:
raise KeyError(key)
for child in self._xml.iterchildren(tag=tag):
if len(child):
yield self.__class__(child)
else:
yield Literal(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 update(self, **kwargs):
u"""Updating or creation of new simple nodes. Each dict key is used as a tagname and value as text. """ |
for key, value in kwargs.items():
helper = helpers.CAST_DICT.get(type(value), str)
tag = self._get_aliases().get(key, key)
elements = list(self._xml.iterchildren(tag=tag))
if elements:
for element in elements:
element.text = h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sget(self, path, default=NONE_NODE):
u"""Enables access to nodes if one or more of them don't exist. Example: text value 'attr text' 'text value' NONE_NODE A... |
attrs = str(path).split(".")
text_or_attr = None
last_attr = attrs[-1]
# Case of getting text or attribute
if last_attr == '#text' or last_attr.startswith('@'):
# #text => text, @attr => attr
text_or_attr = last_attr[1:]
attrs = attrs[:-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 create(self, tag, value):
u"""Creates a node, if it doesn't exist yet. Unlike attribute access, this allows to pass a node's name with hyphens. Those hyphens... |
child_tags = {child.tag for child in self._xml}
if tag in child_tags:
raise KeyError('Node {} already exists in XML tree.'.format(tag))
self.set(tag, 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 set(self, name, value):
u"""Assigns a new XML structure to the node. A literal value, dict or list can be passed in. Works for all nested levels. Dictionary:... |
try:
# Searches for a node to assign to.
element = next(self._xml.iterchildren(tag=name))
except StopIteration:
# There is no such node in the XML tree. We create a new one
# with current root as parent (self._xml).
element = etree.SubElement(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign_dict(self, node, xml_dict):
"""Assigns a Python dict to a ``lxml`` node. :param node: A node to assign the dict to. :param xml_dict: The dict with att... |
new_node = etree.Element(node.tag)
# Replaces the previous node with the new one
self._xml.replace(node, new_node)
# Copies #text and @attrs from the xml_dict
helpers.dict_to_etree(xml_dict, new_node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign_literal(element, value):
u"""Assigns a literal. If a given node doesn't exist, it will be created. :param etree.Element element: element to which we a... |
# Searches for a conversion method specific to the type of value.
helper = helpers.CAST_DICT.get(type(value), str)
# Removes all children and attributes.
element.clear()
element.text = helper(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 to_dict(self, **kw):
u"""Converts the lxml object to a dict. possible kwargs: without_comments: bool """ |
_, value = helpers.etree_to_dict(self._xml, **kw).popitem()
return 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_aliases(self):
u"""Creates a dict with aliases. The key is a normalized tagname, value the original tagname. """ |
if self._aliases is None:
self._aliases = {}
if self._xml is not None:
for child in self._xml.iterchildren():
self._aliases[helpers.normalize_tag(child.tag)] = child.tag
return self._aliases |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xpath( self, path, namespaces=None, regexp=False, smart_strings=True, single_use=False, ):
u"""Executes XPath query on the ``lxml`` object and returns a corr... |
if (
namespaces in ['exslt', 're'] or
(regexp and not namespaces)
):
namespaces = {'re': "http://exslt.org/regular-expressions"}
if single_use:
node = self._xml.xpath(path)
else:
xpe = self.xpath_evaluator(
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 xpath_evaluator(self, namespaces=None, regexp=False, smart_strings=True):
u"""Creates an XPathEvaluator instance for an ElementTree or an Element. :returns: ... |
return etree.XPathEvaluator(
self._xml,
namespaces=namespaces,
regexp=regexp,
smart_strings=smart_strings
) |
<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_last_modified_date(*args, **kwargs):
"""Returns the date of the last modified Note or Release. For use with Django's last_modified decorator. """ |
try:
latest_note = Note.objects.latest()
latest_release = Release.objects.latest()
except ObjectDoesNotExist:
return None
return max(latest_note.modified, latest_release.modified) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def using_ios_stash():
''' returns true if sys path hints the install is running on ios '''
print('detected install path:')
print(os.path.dirname(__file__))
module_names = set(sys.modules.keys())
return 'stash' in module_names or 'stash.system' in module_names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_partition_scores(image, min_w=1, min_h=1):
"""Return list of best to worst binary splits along the x and y axis.
""" |
h, w = image.shape[:2]
if w == 0 or h == 0:
return []
area = h * w
cnz = numpy.count_nonzero
total = cnz(image)
if total == 0 or area == total:
return []
if h < min_h * 2:
y_c = []
else:
y_c = [(-abs((count / ((h - y) * w)) - ((total - count) ... |
<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_defaults(self, config):
"""Initializes the default connection settings.""" |
provider = self.__provider
if provider == 'sqlite':
config.setdefault('dbname', ':memory:')
config.setdefault('create_db', True)
elif provider == 'mysql':
config.setdefault('port', 3306)
config.setdefault('charset', 'utf8')
elif provide... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def newnations(self, root):
"""Most recently founded nations, from newest. Returns ------- an :class:`ApiQuery` of a list of :class:`Nation` """ |
return [aionationstates.Nation(n)
for n in root.find('NEWNATIONS').text.split(',')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def regions(self, root):
"""List of all the regions, seemingly in order of creation. Returns ------- an :class:`ApiQuery` of a list of :class:`Region` """ |
return [aionationstates.Region(r)
for r in root.find('REGIONS').text.split(',')] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regionsbytag(self, *tags):
"""All regions with any of the named tags. Parameters *tags : str Regional tags. Can be preceded by a ``-`` to select regions with... |
if len(tags) > 10:
raise ValueError('You can specify up to 10 tags')
if not tags:
raise ValueError('No tags specified')
# We don't check for invalid tags here because the behaviour is
# fairly intuitive - quering for a non-existent tag returns no
# regio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, id):
"""Dispatch by id. Parameters id : int Dispatch id. Returns ------- an :class:`ApiQuery` of :class:`Dispatch` Raises ------ :class:`NotFo... |
@api_query('dispatch', dispatchid=str(id))
async def result(_, root):
elem = root.find('DISPATCH')
if not elem:
raise NotFound(f'No dispatch found with id {id}')
return Dispatch(elem)
return result(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 dispatchlist(self, *, author=None, category=None, subcategory=None, sort='new'):
"""Find dispatches by certain criteria. Parameters author : str Name of the ... |
params = {'sort': sort}
if author:
params['dispatchauthor'] = author
# Here we do need to ensure that our categories are valid, cause
# NS just ignores the categories it doesn't recognise and returns
# whatever it feels like.
if category and subcategory:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def poll(self, id):
"""Poll with a given id. Parameters id : int Poll id. Returns ------- an :class:`ApiQuery` of :class:`Poll` Raises ------ :class:`NotFound` I... |
@api_query('poll', pollid=str(id))
async def result(_, root):
elem = root.find('POLL')
if not elem:
raise NotFound(f'No poll found with id {id}')
return Poll(elem)
return result(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 banner(self, *ids, _expand_macros=None):
"""Get data about banners by their ids. Macros in banners' names and descriptions are not expanded. Parameters *ids ... |
async def noop(s):
return s
_expand_macros = _expand_macros or noop
@api_query('banner', banner=','.join(ids))
async def result(_, root):
banners = [await Banner(elem, _expand_macros)
for elem in root.find('BANNERS')]
if not l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_telegram(self, *, client_key, telegram_id, telegram_key, recepient):
"""A basic interface to the Telegrams API. Parameters client_key : str Telegr... |
params = {
'a': 'sendTG',
'client': client_key,
'tgid': str(telegram_id),
'key': telegram_key,
'to': recepient
}
return await self._call_api(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def happenings(self, *, nations=None, regions=None, filters=None, beforeid=None, beforetime=None):
"""Iterate through happenings from newest to oldest. Par... |
while True:
happening_bunch = await self._get_happenings(
nations=nations, regions=regions, filters=filters,
beforeid=beforeid, beforetime=beforetime
)
for happening in happening_bunch:
yield happening
if len(happen... |
<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_potential_match_regions(template, transformed_array, method='correlation', raw_tolerance=0.666):
"""To prevent prohibitively slow calculation of normali... |
if method == 'correlation':
match_value = np.sum(template**2) # this will be the value of the match in the
elif method == 'squared difference':
match_value = 0
elif method == 'correlation coefficient':
temp_minus_mean = template - np.mean(template)
match_value = np.sum(temp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalise_correlation(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""Calculates the normalisation coefficients of potential match posi... |
template_norm = np.linalg.norm(template)
image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)])*template_norm for (x,y) in image_tile_dict.keys()}
match_points = image_tile_dict.keys()
# for correlation, then need to transofrm back to get correct value for division
h, w = template.shape
#p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalise_correlation_coefficient(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""As above, but for when the correlation coefficient ma... |
template_mean = np.mean(template)
template_minus_mean = template - template_mean
template_norm = np.linalg.norm(template_minus_mean)
image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)]- np.mean(image_tile_dict[(x,y)]))*template_norm for (x,y) in image_tile_dict.keys()}
match_points = image_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 calculate_squared_differences(image_tile_dict, transformed_array, template, sq_diff_tolerance=0.1):
"""As above, but for when the squared differences matchin... |
template_norm_squared = np.sum(template**2)
image_norms_squared = {(x,y):np.sum(image_tile_dict[(x,y)]**2) for (x,y) in image_tile_dict.keys()}
match_points = image_tile_dict.keys()
# for correlation, then need to transofrm back to get correct value for division
h, w = template.shape
image_matc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def post(self):
"""Get the message lodged. Returns ------- an :class:`aionationstates.ApiQuery` of :class:`aionationstates.Post` """ |
post = (await self.region._get_messages(
fromid=self._post_id, limit=1))[0]
assert post.id == self._post_id
return post |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def resolution(self):
"""Get the resolution voted on. Returns ------- awaitable of :class:`aionationstates.ResolutionAtVote` The resolution voted for. Rais... |
resolutions = await asyncio.gather(
aionationstates.ga.resolution_at_vote,
aionationstates.sc.resolution_at_vote,
)
for resolution in resolutions:
if (resolution is not None
and resolution.name == self.resolution_name):
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def proposal(self):
"""Get the proposal in question. Actually just the first proposal with the same name, but the chance of a collision is tiny. Returns --... |
proposals = await aionationstates.wa.proposals()
for proposal in proposals:
if (proposal.name == self.proposal_name):
return proposal
raise aionationstates.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 append(self, electrode_id):
'''
Append the specified electrode to the route.
The route is not modified (i.e., electrode is not appended) if
electrode is not connected to the last electrode in the existing route.
Parameters
----------
electrode_id : 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 insert_surface(self, position, name, surface, alpha=1.):
'''
Insert Cairo surface as new layer.
Args
----
position (int) : Index position to insert layer at.
name (str) : Name of layer.
surface (cairo.Context) : Surface to render.
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 append_surface(self, name, surface, alpha=1.):
'''
Append Cairo surface as new layer on top of existing layers.
Args
----
name (str) : Name of layer.
surface (cairo.ImageSurface) : Surface to render.
alpha (float) : Alpha/transparency level in th... |
<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_surface(self, name):
'''
Remove layer from rendering stack and flatten remaining layers.
Args
----
name (str) : Name of layer.
'''
self.df_surfaces.drop(name, axis=0, inplace=True)
# Order of layers may have changed after removing a layer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clone_surface(self, source_name, target_name, target_position=-1,
alpha=1.):
'''
Clone surface from existing layer to a new name, inserting new surface
at specified position.
By default, new surface is appended as the top surface layer.
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 render_electrode_shapes(self, df_shapes=None, shape_scale=0.8,
fill=(1, 1, 1)):
'''
Render electrode state shapes.
By default, draw each electrode shape filled white.
See also :meth:`render_shapes()`.
Parameters
----------
df... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def render_registration(self):
'''
Render pinned points on video frame as red rectangle.
'''
surface = self.get_surface()
if self.canvas is None or self.df_canvas_corners.shape[0] == 0:
return surface
corners = self.df_canvas_corners.copy()
corners['w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def draw_route(self, df_route, cr, color=None, line_width=None):
'''
Draw a line between electrodes listed in a route.
Arguments
---------
- `df_route`:
* A `pandas.DataFrame` containing a column named `electrode_i`.
* For each row, `electrode_i` corr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_widget__button_press_event(self, widget, event):
'''
Called when any mouse button is pressed.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed.
'''
if self.mode == 'register_video' and event.button == 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 on_widget__button_release_event(self, widget, event):
'''
Called when any mouse button is released.
.. versionchanged:: 0.11.3
Always reset pending route, regardless of whether a route was
completed. This includes a) removing temporary routes from routes
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_widget__motion_notify_event(self, widget, event):
'''
Called when mouse pointer is moved within drawing area.
.. versionchanged:: 0.11
Do not trigger `route-electrode-added` event if `ALT` key is
pressed.
'''
if self.canvas 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 register_electrode_command(self, command, title=None, group=None):
'''
Register electrode command.
Add electrode plugin command to context menu.
'''
commands = self.electrode_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[: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 register_route_command(self, command, title=None, group=None):
'''
Register route command.
Add route plugin command to context menu.
'''
commands = self.route_commands.setdefault(group, OrderedDict())
if title is None:
title = (command[:1].upper() + comma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def after(self):
""" Return a deferred that will fire after the request is finished. Returns: Deferred: a new deferred that will fire appropriately """ |
d = Deferred()
self._after_deferreds.append(d)
return d.chain |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def after_response(self, request, fn, *args, **kwargs):
""" Call the given callable after the given request has its response. Arguments: request: the request to ... |
self._requests[id(request)]["callbacks"].append((fn, args, kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_degbandshalffill():
"""Plot of Quasiparticle weight for degenerate half-filled bands, showing the Mott transition""" |
ulim = [3.45, 5.15, 6.85, 8.55]
bands = range(1, 5)
for band, u_int in zip(bands, ulim):
name = 'Z_half_'+str(band)+'band'
dop = [0.5]
data = ssplt.calc_z(band, dop, np.arange(0, u_int, 0.1),0., name)
plt.plot(data['u_int'], data['zeta'][0, :, 0], label='$N={}$'.format(str(b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_dop(bands, int_max, dop, hund_cu, name):
"""Plot of Quasiparticle weight for N degenerate bands under selected doping shows transition only at half-fill... |
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.plot_curves_z(data, 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 plot_dop_phase(bands, int_max, hund_cu):
"""Phase plot of Quasiparticle weight for N degenerate bands under doping shows transition only at interger filling ... |
name = 'Z_dop_phase_'+str(bands)+'bands_U'+str(int_max)+'J'+str(hund_cu)
dop = np.sort(np.hstack((np.linspace(0.01,0.99,50),
np.arange(1./2./bands, 1, 1/2/bands))))
data = ssplt.calc_z(bands, dop, np.arange(0, int_max, 0.1), hund_cu, name)
ssplt.imshow_z(data, name)
ssplt.surf_... |
<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_extensions(self, namespace):
"""Register any extensions under the given namespace.""" |
# Register any extension classes for this class.
extmanager = ExtensionManager(
'extensions.classes.{}'.format(namespace),
propagate_map_exceptions=True
)
if extmanager.extensions:
extmanager.map(util.register_extension_class, base=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 acls(self):
"""The instance bound ACLs operations layer.""" |
if self._acls is None:
self._acls = InstanceAcls(instance=self)
return self._acls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
"""Get all ACLs for this instance.""" |
return self._instance._client.acls.all(self._instance.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(self, cidr_mask, description, **kwargs):
"""Create an ACL for this instance. See :py:meth:`Acls.create` for call signature. """ |
return self._instance._client.acls.create(
self._instance.name,
cidr_mask,
description,
**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(self, acl):
"""Get the ACL specified by ID belonging to this instance. See :py:meth:`Acls.get` for call signature. """ |
return self._instance._client.acls.get(self._instance.name, acl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _VarintEncoder():
"""Return an encoder for a basic varint value.""" |
local_chr = chr
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeVarint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value.""" |
local_chr = chr
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeSignedVarint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(value, query):
""" Determine whether a value satisfies a query. """ |
if type(query) in [str, int, float, type(None)]:
return value == query
elif type(query) == dict and len(query.keys()) == 1:
for op in query:
if op == "$eq": return value == query[op]
elif op == "$lt": return value < query[op]
elif op == "$lte": return 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 features_tags_parse_str_to_dict(obj):
""" Parse tag strings of all features in the collection into a Python dictionary, if possible. """ |
features = obj['features']
for i in tqdm(range(len(features))):
tags = features[i]['properties'].get('tags')
if tags is not None:
try:
tags = json.loads("{" + tags.replace("=>", ":") + "}")
except:
try:
tags = eval("{" ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features_keep_by_property(obj, query):
""" Filter all features in a collection by retaining only those that satisfy the provided query. """ |
features_keep = []
for feature in tqdm(obj['features']):
if all([match(feature['properties'].get(prop), qry) for (prop, qry) in query.items()]):
features_keep.append(feature)
obj['features'] = features_keep
return 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 features_keep_within_radius(obj, center, radius, units):
""" Filter all features in a collection by retaining only those that fall within the specified radiu... |
features_keep = []
for feature in tqdm(obj['features']):
if all([getattr(geopy.distance.vincenty((lat,lon), center), units) < radius for (lon,lat) in geojson.utils.coords(feature)]):
features_keep.append(feature)
obj['features'] = features_keep
return 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 features_keep_using_features(obj, bounds):
""" Filter all features in a collection by retaining only those that fall within the features in the second collec... |
# Build an R-tree index of bound features and their shapes.
bounds_shapes = [
(feature, shapely.geometry.shape(feature['geometry']))
for feature in tqdm(bounds['features'])
if feature['geometry'] is not None
]
index = rtree.index.Index()
for i in tqdm(range(len(bounds_sha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features_node_edge_graph(obj):
""" Transform the features into a more graph-like structure by appropriately splitting LineString features into two-point "edg... |
points = {}
features = obj['features']
for feature in tqdm(obj['features']):
for (lon, lat) in geojson.utils.coords(feature):
points.setdefault((lon, lat), 0)
points[(lon, lat)] += 1
points = [p for (p, c) in points.items() if c > 1]
features = [geojson.Point(p) for ... |
<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_table_info(conn, tablename):
"""Returns TableInfo object""" |
r = conn.execute("pragma table_info('{}')".format(tablename))
ret = TableInfo(((row["name"], row) for row in r))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def early_warning(iterable, name='this generator'):
''' This function logs an early warning that the generator is empty.
This is handy for times when you're manually playing with generators and
would appreciate the console warning you ahead of time that your generator
is now empty, instead of being sur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, data, request, id):
""" Create a new resource using POST """ |
if id:
# can't post to individual user
raise errors.MethodNotAllowed()
user = self._dict_to_model(data)
user.save()
# according to REST, return 201 and Location header
return Response(201, None, {
'Location': '%s%d' % (reverse('user'), user.pk... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, request, id):
""" Get one user or all users """ |
if id:
return self._get_one(id)
else:
return self._get_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, data, request, id):
""" Update a single user. """ |
if not id:
# can't update the whole container
raise errors.MethodNotAllowed()
userdata = self._dict_to_model(data)
userdata.pk = id
try:
userdata.save(force_update=True)
except DatabaseError:
# can't udpate non-existing user
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, request, id):
""" Delete a single user. """ |
if not id:
# can't delete the whole container
raise errors.MethodNotAllowed()
try:
models.User.objects.get(pk=id).delete()
except models.User.DoesNotExist:
# we never had it, so it's definitely deleted
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_one(self, id):
""" Get one user from db and turn into dict """ |
try:
return self._to_dict(models.User.objects.get(pk=id))
except models.User.DoesNotExist:
raise errors.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 _get_all(self):
""" Get all users from db and turn into list of dicts """ |
return [self._to_dict(row) for row in models.User.objects.all()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dict_to_model(self, data):
""" Create new user model instance based on the received data. Note that the created user is not saved into database. """ |
try:
# we can do this because we have same fields
# in the representation and in the model:
user = models.User(**data)
except TypeError:
# client sent bad data
raise errors.BadRequest()
else:
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def captures(self, uuid, withTitles=False):
"""Return the captures for a given uuid optional value withTitles=yes""" |
picker = lambda x: x.get('capture', [])
return self._get((uuid,), picker, withTitles='yes' if withTitles else 'no') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uuid(self, type, val):
"""Return the item-uuid for a identifier""" |
picker = lambda x: x.get('uuid', x)
return self._get((type, val), picker) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mods(self, uuid):
"""Return a mods record for a given uuid""" |
picker = lambda x: x.get('mods', {})
return self._get(('mods', uuid), picker) |
<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_i18n_day_name(day_nb, display='short', ln=None):
"""Get the string representation of a weekday, internationalized @param day_nb: number of weekday UNIX l... |
ln = default_ln(ln)
_ = gettext_set_language(ln)
if display == 'short':
days = {0: _("Sun"),
1: _("Mon"),
2: _("Tue"),
3: _("Wed"),
4: _("Thu"),
5: _("Fri"),
6: _("Sat")}
else:
days = {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_i18n_month_name(month_nb, display='short', ln=None):
"""Get a non-numeric representation of a month, internationalized. @param month_nb: number of month,... |
ln = default_ln(ln)
_ = gettext_set_language(ln)
if display == 'short':
months = {0: _("Month"),
1: _("Jan"),
2: _("Feb"),
3: _("Mar"),
4: _("Apr"),
5: _("May"),
6: _("Jun"),
... |
<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_month_selectbox(name, selected_month=0, ln=None):
"""Creates an HTML menu for month selection. Value of selected field is numeric. @param selected_mon... |
ln = default_ln(ln)
out = "<select name=\"%s\">\n" % name
for i in range(0, 13):
out += "<option value=\"%i\"" % i
if (i == selected_month):
out += " selected=\"selected\""
out += ">%s</option>\n" % get_i18n_month_name(i, ln)
out += "</select>\n"
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_runtime_limit(value, now=None):
"""Parsing CLI option for runtime limit, supplied as VALUE. Value could be something like: Sunday 23:00-05:00, the form... |
def extract_time(value):
value = _RE_RUNTIMELIMIT_HOUR.search(value).groupdict()
return timedelta(hours=int(value['hours']),
minutes=int(value['minutes']))
def extract_weekday(value):
key = value[:3].lower()
try:
return {
'm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_datetime(datetime_string):
"""Try to guess the datetime contained in a string of unknow format. @param datetime_string: the datetime representation. @t... |
if CFG_HAS_EGENIX_DATETIME:
try:
return Parser.DateTimeFromString(datetime_string).timetuple()
except ValueError:
pass
else:
for format in (None, '%x %X', '%X %x', '%Y-%M-%dT%h:%m:%sZ'):
try:
return time.strptime(datetime_string, 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 get_dst(date_obj):
"""Determine if dst is locally enabled at this time""" |
dst = 0
if date_obj.year >= 1900:
tmp_date = time.mktime(date_obj.timetuple())
# DST is 1 so reduce time with 1 hour.
dst = time.localtime(tmp_date)[-1]
return dst |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def utc_to_localtime( date_str, fmt="%Y-%m-%d %H:%M:%S", input_fmt="%Y-%m-%dT%H:%M:%SZ"):
""" Convert UTC to localtime Reference: - (1) http://www.openarchives.o... |
date_struct = datetime.strptime(date_str, input_fmt)
date_struct += timedelta(hours=get_dst(date_struct))
date_struct -= timedelta(seconds=time.timezone)
return strftime(fmt, date_struct) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_call(self, actual_call, stubbed_call):
"""Extends Stub call handling behavior to be callable by default.""" |
self._actual_calls.append(actual_call)
use_call = stubbed_call or actual_call
return use_call.return_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 formatted_args(self):
"""Format call arguments as a string. This is used to make test failure messages more helpful by referring to calls using a string that... |
arg_reprs = list(map(repr, self.args))
kwarg_reprs = ['%s=%s' % (k, repr(v)) for k, v in self.kwargs.items()]
return '(%s)' % ', '.join(arg_reprs + kwarg_reprs) |
<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(self):
""" Check if data and third party tools are available :raises: RuntimeError """ |
#for path in self.path.values():
# if not os.path.exists(path):
# raise RuntimeError("File '{}' is missing".format(path))
for tool in ('cd-hit', 'prank', 'hmmbuild', 'hmmpress', 'hmmscan', 'phmmer', 'mafft', 'meme'):
if not self.pathfinder.exists(tool):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_non_rabs(self):
""" Shrink the non-Rab DB size by reducing sequence redundancy. """ |
logging.info('Building non-Rab DB')
run_cmd([self.pathfinder['cd-hit'], '-i', self.path['non_rab_db'], '-o', self.output['non_rab_db'],
'-d', '100', '-c', str(config['param']['non_rab_db_identity_threshold']), '-g', '1', '-T', self.cpu])
os.remove(self.output['non_rab_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 parse_duration(duration):
"""Attepmts to parse an ISO8601 formatted ``duration``. Returns a ``datetime.timedelta`` object. """ |
duration = str(duration).upper().strip()
elements = ELEMENTS.copy()
for pattern in (SIMPLE_DURATION, COMBINED_DURATION):
if pattern.match(duration):
found = pattern.match(duration).groupdict()
del found['time']
elements.update(dict((k, int(v or 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 skin_details(skin_id, lang="en"):
"""This resource returns details about a single skin. :param skin_id: The skin to query for. :param lang: The language to d... |
params = {"skin_id": skin_id, "lang": lang}
cache_name = "skin_details.%(skin_id)s.%(lang)s.json" % params
return get_cached("skin_details.json", cache_name, params=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 bubble_to_gexf(bblfile:str, gexffile:str=None, oriented:bool=False):
"""Write in bblfile a graph equivalent to those depicted in bubble file""" |
tree = BubbleTree.from_bubble_file(bblfile, oriented=bool(oriented))
gexf_converter.tree_to_file(tree, gexffile)
return gexffile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bubble_to_js(bblfile:str, jsdir:str=None, oriented:bool=False, **style):
"""Write in jsdir a graph equivalent to those depicted in bubble file""" |
js_converter.bubble_to_dir(bblfile, jsdir, oriented=bool(oriented), **style)
return jsdir |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.