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 _parent_queryset(self):
""" Get queryset of parent view. Generated queryset is used to run queries in the current level view. """ |
parent = self._resource.parent
if hasattr(parent, 'view'):
req = self.request.blank(self.request.path)
req.registry = self.request.registry
req.matchdict = {
parent.id_name: self.request.matchdict.get(parent.id_name)}
parent_view = parent.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_collection(self, **kwargs):
""" Get objects collection taking into account generated queryset of parent view. This method allows working with nested reso... |
self._query_params.update(kwargs)
objects = self._parent_queryset()
if objects is not None:
return self.Model.filter_objects(
objects, **self._query_params)
return self.Model.get_collection(**self._query_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 get_item(self, **kwargs):
""" Get collection item taking into account generated queryset of parent view. This method allows working with nested resources pro... |
if six.callable(self.context):
self.reload_context(es_based=False, **kwargs)
objects = self._parent_queryset()
if objects is not None and self.context not in objects:
raise JHTTPNotFound('{}({}) not found'.format(
self.Model.__name__,
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 reload_context(self, es_based, **kwargs):
""" Reload `self.context` object into a DB or ES object. A reload is performed by getting the object ID from :kwarg... |
from .acl import BaseACL
key = self._get_context_key(**kwargs)
kwargs = {'request': self.request}
if issubclass(self._factory, BaseACL):
kwargs['es_based'] = es_based
acl = self._factory(**kwargs)
if acl.item_model is None:
acl.item_model = 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_collection_es(self):
""" Get ES objects collection taking into account the generated queryset of parent view. This method allows working with nested reso... |
objects_ids = self._parent_queryset_es()
if objects_ids is not None:
objects_ids = self.get_es_object_ids(objects_ids)
if not objects_ids:
return []
self._query_params['id'] = objects_ids
return super(ESBaseView, self).get_collection_es() |
<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_item_es(self, **kwargs):
""" Get ES collection item taking into account generated queryset of parent view. This method allows working with nested resourc... |
item_id = self._get_context_key(**kwargs)
objects_ids = self._parent_queryset_es()
if objects_ids is not None:
objects_ids = self.get_es_object_ids(objects_ids)
if six.callable(self.context):
self.reload_context(es_based=True, **kwargs)
if (objects_ids ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dbcollection_with_es(self, **kwargs):
""" Get DB objects collection by first querying ES. """ |
es_objects = self.get_collection_es()
db_objects = self.Model.filter_objects(es_objects)
return db_objects |
<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_many(self, **kwargs):
""" Delete multiple objects from collection. First ES is queried, then the results are used to query the DB. This is done to mak... |
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._delete_many(db_objects, self.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 update_many(self, **kwargs):
""" Update multiple objects from collection. First ES is queried, then the results are used to query DB. This is done to make su... |
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._update_many(
db_objects, self._json_params, self.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 get_item(self, **kwargs):
""" Reload context on each access. """ |
self.reload_context(es_based=False, **kwargs)
return super(ItemSubresourceBaseView, self).get_item(**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 setup(app):
"""Allow this module to be used as sphinx extension. This attaches the Sphinx hooks. :type app: sphinx.application.Sphinx """ |
import sphinxcontrib_django.docstrings
import sphinxcontrib_django.roles
# Setup both modules at once. They can also be separately imported to
# use only fragments of this package.
sphinxcontrib_django.docstrings.setup(app)
sphinxcontrib_django.roles.setup(app) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch_django_for_autodoc():
"""Fix the appearance of some classes in autodoc. This avoids query evaluation. """ |
# Fix Django's manager appearance
ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.manager
# Stop Django from executing DB queries
models.QuerySet.__repr__ = lambda self: self.__class__.__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 autodoc_skip(app, what, name, obj, skip, options):
"""Hook that tells autodoc to include or exclude certain fields. Sadly, it doesn't give a reference to the... |
if name in config.EXCLUDE_MEMBERS:
return True
if name in config.INCLUDE_MEMBERS:
return False
return skip |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def improve_model_docstring(app, what, name, obj, options, lines):
"""Hook that improves the autodoc docstrings for Django models. :type app: sphinx.application.... |
if what == 'class':
_improve_class_docs(app, obj, lines)
elif what == 'attribute':
_improve_attribute_docs(obj, name, lines)
elif what == 'method':
_improve_method_docs(obj, name, lines)
# Return the extended docstring
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class.""" |
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclass(cls, forms.Form):
_add_form_fields(cls, lines) |
<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_model_fields_as_params(app, obj, lines):
"""Improve the documentation of a Django model subclass. This adds all model fields as parameters to the ``__in... |
for field in obj._meta.get_fields():
try:
help_text = strip_tags(force_text(field.help_text))
verbose_name = force_text(field.verbose_name).capitalize()
except AttributeError:
# e.g. ManyToOneRel
continue
# Add parameter
if help_text:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_form_fields(obj, lines):
"""Improve the documentation of a Django Form class. This highlights the available fields in the form. """ |
lines.append("**Form fields:**")
lines.append("")
for name, field in obj.base_fields.items():
field_type = "{}.{}".format(field.__class__.__module__, field.__class__.__name__)
tpl = "* ``{name}``: {label} (:class:`~{field_type}`)"
lines.append(tpl.format(
name=name,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _improve_attribute_docs(obj, name, lines):
"""Improve the documentation of various attributes. This improves the navigation between related objects. :param o... |
if obj is None:
# Happens with form attributes.
return
if isinstance(obj, DeferredAttribute):
# This only points to a field name, not a field.
# Get the field by importing the name.
cls_path, field_name = name.rsplit('.', 1)
model = import_string(cls_path)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _improve_method_docs(obj, name, lines):
"""Improve the documentation of various methods. :param obj: the instance of the method to document. :param name: ful... |
if not lines:
# Not doing obj.__module__ lookups to avoid performance issues.
if name.endswith('_display'):
match = RE_GET_FOO_DISPLAY.search(name)
if match is not None:
# Django get_..._display method
lines.append("**Autogenerated:** Shows 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 elliptic_fourier_descriptors(contour, order=10, normalize=False):
"""Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A ... |
dxy = np.diff(contour, axis=0)
dt = np.sqrt((dxy ** 2).sum(axis=1))
t = np.concatenate([([0., ]), np.cumsum(dt)])
T = t[-1]
phi = (2 * np.pi * t) / T
coeffs = np.zeros((order, 4))
for n in _range(1, order + 1):
const = T / (2 * n * n * np.pi * np.pi)
phi_n = phi * n
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_efd(coeffs, size_invariant=True):
"""Normalizes an array of Fourier coefficients. See [#a]_ and [#b]_ for details. :param numpy.ndarray coeffs: A `... |
# Make the coefficients have a zero phase shift from
# the first major axis. Theta_1 is that shift angle.
theta_1 = 0.5 * np.arctan2(
2 * ((coeffs[0, 0] * coeffs[0, 1]) + (coeffs[0, 2] * coeffs[0, 3])),
((coeffs[0, 0] ** 2) - (coeffs[0, 1] ** 2) + (coeffs[0, 2] ** 2) - (coeffs[0, 3] ** 2)))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gen_input_mask(mask):
"""Generate input mask from bytemask""" |
return input_mask(
shift=bool(mask & MOD_Shift),
lock=bool(mask & MOD_Lock),
control=bool(mask & MOD_Control),
mod1=bool(mask & MOD_Mod1),
mod2=bool(mask & MOD_Mod2),
mod3=bool(mask & MOD_Mod3),
mod4=bool(mask & MOD_Mod4),
mod5=bool(mask & MOD_Mod5)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_mouse(self, x, y, screen=0):
""" Move the mouse to a specific location. :param x: the target X coordinate on the screen in pixels. :param y: the target ... |
# todo: apparently the "screen" argument is not behaving properly
# and sometimes even making the interpreter crash..
# Figure out why (changed API / using wrong header?)
# >>> xdo.move_mouse(3000,200,1)
# X Error of failed request: BadWindow (invalid Window param... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_mouse_relative_to_window(self, window, x, y):
""" Move the mouse to a specific location relative to the top-left corner of a window. :param x: the targe... |
_libxdo.xdo_move_mouse_relative_to_window(
self._xdo, ctypes.c_ulong(window), x, y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_mouse_relative(self, x, y):
""" Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the ... |
_libxdo.xdo_move_mouse_relative(self._xdo, x, y) |
<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_window_at_mouse(self):
""" Get the window the mouse is currently over """ |
window_ret = ctypes.c_ulong(0)
_libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret))
return window_ret.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_mouse_location2(self):
""" Get all mouse location-related data. :return: a namedtuple with ``x``, ``y``, ``screen_num`` and ``window`` fields """ |
x = ctypes.c_int(0)
y = ctypes.c_int(0)
screen_num_ret = ctypes.c_ulong(0)
window_ret = ctypes.c_ulong(0)
_libxdo.xdo_get_mouse_location2(
self._xdo, ctypes.byref(x), ctypes.byref(y),
ctypes.byref(screen_num_ret), ctypes.byref(window_ret))
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 wait_for_mouse_move_from(self, origin_x, origin_y):
""" Wait for the mouse to move from a location. This function will block until the condition has been sat... |
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, origin_x, origin_y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_mouse_move_to(self, dest_x, dest_y):
""" Wait for the mouse to move to a location. This function will block until the condition has been satisified.... |
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, dest_x, dest_y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def click_window(self, window, button):
""" Send a click for a specific mouse button at the current mouse location. :param window: The window you want to send th... |
_libxdo.xdo_click_window(self._xdo, window, button) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def click_window_multiple(self, window, button, repeat=2, delay=100000):
""" Send a one or more clicks for a specific mouse button at the current mouse location.... |
_libxdo.xdo_click_window_multiple(
self._xdo, window, button, repeat, delay) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter_text_window(self, window, string, delay=12000):
""" Type a string to the specified window. If you want to send a specific key or key sequence, such as ... |
return _libxdo.xdo_enter_text_window(self._xdo, window, string, delay) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_keysequence_window(self, window, keysequence, delay=12000):
""" Send a keysequence to the specified window. This allows you to send keysequences by symb... |
_libxdo.xdo_send_keysequence_window(
self._xdo, window, keysequence, delay) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_keysequence_window_list_do( self, window, keys, pressed=1, modifier=None, delay=120000):
""" Send a series of keystrokes. :param window: The window to s... |
# todo: how to properly use charcodes_t in a nice way?
_libxdo.xdo_send_keysequence_window_list_do(
self._xdo, window, keys, len(keys), pressed, modifier, delay) |
<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_active_keys_to_keycode_list(self):
"""Get a list of active keys. Uses XQueryKeymap""" |
try:
_libxdo.xdo_get_active_keys_to_keycode_list
except AttributeError:
# Apparently, this was implemented in a later version..
raise NotImplementedError()
keys = POINTER(charcodemap_t)
nkeys = ctypes.c_int(0)
_libxdo.xdo_get_active_keys_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 wait_for_window_map_state(self, window, state):
""" Wait for a window to have a specific map state. State possibilities: IsUnmapped - window is not displayed... |
_libxdo.xdo_wait_for_window_map_state(self._xdo, window, state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_window(self, window, x, y):
""" Move a window to a specific location. The top left corner of the window will be moved to the x,y coordinate. :param wid:... |
_libxdo.xdo_move_window(self._xdo, window, x, y) |
<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_window_size(self, window, w, h, flags=0):
""" Change the window size. :param wid: the window to resize :param w: the new desired width :param h: the new ... |
_libxdo.xdo_set_window_size(self._xdo, window, w, h, flags) |
<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_window_property(self, window, name, value):
""" Change a window property. Example properties you can change are WM_NAME, WM_ICON_NAME, etc. :param wid: T... |
_libxdo.xdo_set_window_property(self._xdo, window, name, 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_window_class(self, window, name, class_):
""" Change the window's classname and or class. :param name: The new class name. If ``None``, no change. :param... |
_libxdo.xdo_set_window_class(self._xdo, window, name, 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 set_window_urgency(self, window, urgency):
"""Sets the urgency hint for a window""" |
_libxdo.xdo_set_window_urgency(self._xdo, window, urgency) |
<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_window_override_redirect(self, window, override_redirect):
""" Set the override_redirect value for a window. This generally means whether or not a window... |
_libxdo.xdo_set_window_override_redirect(
self._xdo, window, override_redirect) |
<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_focused_window(self):
""" Get the window currently having focus. :param window_ret: Pointer to a window where the currently-focused window will be stored... |
window_ret = window_t(0)
_libxdo.xdo_get_focused_window(self._xdo, ctypes.byref(window_ret))
return window_ret.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 wait_for_window_focus(self, window, want_focus):
""" Wait for a window to have or lose focus. :param window: The window to wait on :param want_focus: If 1, w... |
_libxdo.xdo_wait_for_window_focus(self._xdo, window, want_focus) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_window_active(self, window, active=1):
""" Wait for a window to be active or not active. Requires your window manager to support this. Uses _NET_ACT... |
_libxdo.xdo_wait_for_window_active(self._xdo, window, active) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reparent_window(self, window_source, window_target):
""" Reparents a window :param wid_source: the window to reparent :param wid_target: the new parent windo... |
_libxdo.xdo_reparent_window(self._xdo, window_source, window_target) |
<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_window_location(self, window):
""" Get a window's location. """ |
screen_ret = Screen()
x_ret = ctypes.c_int(0)
y_ret = ctypes.c_int(0)
_libxdo.xdo_get_window_location(
self._xdo, window, ctypes.byref(x_ret), ctypes.byref(y_ret),
ctypes.byref(screen_ret))
return window_location(x_ret.value, y_ret.value, screen_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 get_window_size(self, window):
""" Get a window's size. """ |
w_ret = ctypes.c_uint(0)
h_ret = ctypes.c_uint(0)
_libxdo.xdo_get_window_size(self._xdo, window, ctypes.byref(w_ret),
ctypes.byref(h_ret))
return window_size(w_ret.value, h_ret.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_active_window(self):
""" Get the currently-active window. Requires your window manager to support this. Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec. "... |
window_ret = window_t(0)
_libxdo.xdo_get_active_window(self._xdo, ctypes.byref(window_ret))
return window_ret.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 select_window_with_click(self):
""" Get a window ID by clicking on it. This function blocks until a selection is made. """ |
window_ret = window_t(0)
_libxdo.xdo_select_window_with_click(
self._xdo, ctypes.byref(window_ret))
return window_ret.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_number_of_desktops(self):
""" Get the current number of desktops. Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec. :param ndesktops: pointer to long wh... |
ndesktops = ctypes.c_long(0)
_libxdo.xdo_get_number_of_desktops(self._xdo, ctypes.byref(ndesktops))
return ndesktops.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_current_desktop(self):
""" Get the current desktop. Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec. """ |
desktop = ctypes.c_long(0)
_libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop))
return desktop.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_desktop_for_window(self, window, desktop):
""" Move a window to another desktop Uses _NET_WM_DESKTOP of the EWMH spec. :param wid: the window to move :pa... |
_libxdo.xdo_set_desktop_for_window(self._xdo, window, desktop) |
<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_desktop_for_window(self, window):
""" Get the desktop a window is on. Uses _NET_WM_DESKTOP of the EWMH spec. If your desktop does not support ``_NET_WM_D... |
desktop = ctypes.c_long(0)
_libxdo.xdo_get_desktop_for_window(
self._xdo, window, ctypes.byref(desktop))
return desktop.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 search_windows( self, winname=None, winclass=None, winclassname=None, pid=None, only_visible=False, screen=None, require=False, searchmask=0, desktop=None, li... |
windowlist_ret = ctypes.pointer(window_t(0))
nwindows_ret = ctypes.c_uint(0)
search = xdo_search_t(searchmask=searchmask)
if winname is not None:
search.winname = winname
search.searchmask |= SEARCH_NAME
if winclass is not None:
search.winc... |
<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_symbol_map(self):
""" If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, ... |
# todo: make sure we return a list of strings!
sm = _libxdo.xdo_get_symbol_map()
# Return value is like:
# ['alt', 'Alt_L', ..., None, None, None, ...]
# We want to return only values up to the first None.
# todo: any better solution than this?
i = 0
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 get_active_modifiers(self):
""" Get a list of active keys. Uses XQueryKeymap. :return: list of charcodemap_t instances """ |
keys = ctypes.pointer(charcodemap_t())
nkeys = ctypes.c_int(0)
_libxdo.xdo_get_active_modifiers(
self._xdo, ctypes.byref(keys), ctypes.byref(nkeys))
return [keys[i] for i in range(nkeys.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_window_name(self, win_id):
""" Get a window's name, if any. """ |
window = window_t(win_id)
name_ptr = ctypes.c_char_p()
name_len = ctypes.c_int(0)
name_type = ctypes.c_int(0)
_libxdo.xdo_get_window_name(
self._xdo, window, ctypes.byref(name_ptr),
ctypes.byref(name_len), ctypes.byref(name_type))
name = name_ptr.... |
<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_metadata(module_paths):
"""Import all the given modules""" |
cwd = os.getcwd()
if cwd not in sys.path:
sys.path.insert(0, cwd)
modules = []
try:
for path in module_paths:
modules.append(import_module(path))
except ImportError as e:
err = RuntimeError('Could not import {}: {}'.format(path, str(e)))
raise_from(err, 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 load_metadata(stream):
"""Load JSON metadata from opened stream.""" |
try:
metadata = json.load(
stream, encoding='utf8', object_pairs_hook=OrderedDict)
except json.JSONDecodeError as e:
err = RuntimeError('Error parsing {}: {}'.format(stream.name, e))
raise_from(err, e)
else:
# convert changelog keys back to ints for sorting
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def strip_punctuation_space(value):
"Strip excess whitespace prior to punctuation."
def strip_punctuation(string):
replacement_list = (
(' .', '.'),
(' :', ':'),
('( ', '('),
(' )', ')'),
)
for match, replacement in replacement_list:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def join_sentences(string1, string2, glue='.'):
"concatenate two sentences together with punctuation glue"
if not string1 or string1 == '':
return string2
if not string2 or string2 == '':
return string1
# both are strings, continue joining them together with the glue and whitespace
n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coerce_to_int(val, default=0xDEADBEEF):
"""Attempts to cast given value to an integer, return the original value if failed or the default if one provided.""" |
try:
return int(val)
except (TypeError, ValueError):
if default != 0xDEADBEEF:
return default
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nullify(function):
"Decorator. If empty list, returns None, else list."
def wrapper(*args, **kwargs):
value = function(*args, **kwargs)
if(type(value) == list and len(value) == 0):
return None
return value
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 strippen(function):
"Decorator. Strip excess whitespace from return value."
def wrapper(*args, **kwargs):
return strip_strings(function(*args, **kwargs))
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 inten(function):
"Decorator. Attempts to convert return value to int"
def wrapper(*args, **kwargs):
return coerce_to_int(function(*args, **kwargs))
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 date_struct(year, month, day, tz = "UTC"):
""" Given year, month and day numeric values and a timezone convert to structured date object """ |
ymdtz = (year, month, day, tz)
if None in ymdtz:
#logger.debug("a year, month, day or tz value was empty: %s" % str(ymdtz))
return None # return early if we have a bad value
try:
return time.strptime("%s-%s-%s %s" % ymdtz, "%Y-%m-%d %Z")
except(TypeError, ValueError):
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def date_struct_nn(year, month, day, tz="UTC"):
""" Assemble a date object but if day or month is none set them to 1 to make it easier to deal with partial dates... |
if not day:
day = 1
if not month:
month = 1
return date_struct(year, month, day, tz) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def doi_uri_to_doi(value):
"Strip the uri schema from the start of DOI URL strings"
if value is None:
return value
replace_values = ['http://dx.doi.org/', 'https://dx.doi.org/',
'http://doi.org/', 'https://doi.org/']
for replace_value in replace_values:
value = valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def orcid_uri_to_orcid(value):
"Strip the uri schema from the start of ORCID URL strings"
if value is None:
return value
replace_values = ['http://orcid.org/', 'https://orcid.org/']
for replace_value in replace_values:
value = value.replace(replace_value, '')
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 component_acting_parent_tag(parent_tag, tag):
""" Only intended for use in getting components, look for tag name of fig-group and if so, find the first fig t... |
if parent_tag.name == "fig-group":
if (len(tag.find_previous_siblings("fig")) > 0):
acting_parent_tag = first(extract_nodes(parent_tag, "fig"))
else:
# Do not return the first fig as parent of itself
return None
else:
acting_parent_tag = parent_tag
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first_parent(tag, nodename):
""" Given a beautiful soup tag, look at its parents and return the first tag name that matches nodename or the list nodename """ |
if nodename is not None and type(nodename) == str:
nodename = [nodename]
return first(list(filter(lambda tag: tag.name in nodename, tag.parents))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_fig_ordinal(tag):
""" Meant for finding the position of fig tags with respect to whether they are for a main figure or a child figure """ |
tag_count = 0
if 'specific-use' not in tag.attrs:
# Look for tags with no "specific-use" attribute
return len(list(filter(lambda tag: 'specific-use' not in tag.attrs,
tag.find_all_previous(tag.name)))) + 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 tag_limit_sibling_ordinal(tag, stop_tag_name):
""" Count previous tags of the same name until it reaches a tag name of type stop_tag, then stop counting """ |
tag_count = 1
for prev_tag in tag.previous_elements:
if prev_tag.name == tag.name:
tag_count += 1
if prev_tag.name == stop_tag_name:
break
return tag_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 tag_media_sibling_ordinal(tag):
""" Count sibling ordinal differently depending on if the mimetype is video or not """ |
if hasattr(tag, 'name') and tag.name != 'media':
return None
nodenames = ['fig','supplementary-material','sub-article']
first_parent_tag = first_parent(tag, nodenames)
sibling_ordinal = None
if first_parent_tag:
# Start counting at 0
sibling_ordinal = 0
for media_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_supplementary_material_sibling_ordinal(tag):
""" Strategy is to count the previous supplementary-material tags having the same asset value to get its sib... |
if hasattr(tag, 'name') and tag.name != 'supplementary-material':
return None
nodenames = ['fig','media','sub-article']
first_parent_tag = first_parent(tag, nodenames)
sibling_ordinal = 1
if first_parent_tag:
# Within the parent tag of interest, count the tags
# having 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 text_to_title(value):
"""when a title is required, generate one from the value""" |
title = None
if not value:
return title
words = value.split(" ")
keep_words = []
for word in words:
if word.endswith(".") or word.endswith(":"):
keep_words.append(word)
if len(word) > 1 and "<italic>" not in word and "<i>" not in word:
break
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape_ampersand(string):
""" Quick convert unicode ampersand characters not associated with a numbered entity or not starting with allowed characters to a p... |
if not string:
return string
start_with_match = r"(\#x(....);|lt;|gt;|amp;)"
# The pattern below is match & that is not immediately followed by #
string = re.sub(r"&(?!" + start_with_match + ")", '&', string)
return string |
<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(filename, return_doctype_dict=False):
""" to extract the doctype details from the file when parsed and return the data for later use, set return_doctyp... |
doctype_dict = {}
# check for python version, doctype in ElementTree is deprecated 3.2 and above
if sys.version_info < (3,2):
parser = CustomXMLParser(html=0, target=None, encoding='utf-8')
else:
# Assume greater than Python 3.2, get the doctype from the TreeBuilder
tree_builder... |
<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_tag_before(tag_name, tag_text, parent_tag, before_tag_name):
""" Helper function to refactor the adding of new tags especially for when converting text t... |
new_tag = Element(tag_name)
new_tag.text = tag_text
if get_first_element_index(parent_tag, before_tag_name):
parent_tag.insert( get_first_element_index(parent_tag, before_tag_name) - 1, new_tag)
return parent_tag |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rewrite_subject_group(root, subjects, subject_group_type, overwrite=True):
"add or rewrite subject tags inside subj-group tags"
parent_tag_name = 'subj-group'
tag_name = 'subject'
wrap_tag_name = 'article-categories'
tag_attribute = 'subj-group-type'
# the parent tag where it should be found... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_doctype(qualifiedName, publicId=None, systemId=None, internalSubset=None):
""" Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, wi... |
doctype = ElifeDocumentType(qualifiedName)
doctype._identified_mixin_init(publicId, systemId)
if internalSubset:
doctype.internalSubset = internalSubset
return doctype |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrite_json(rewrite_type, soup, json_content):
""" Due to XML content that will not conform with the strict JSON schema validation rules, for elife articles... |
if not soup:
return json_content
if not elifetools.rawJATS.doi(soup) or not elifetools.rawJATS.journal_id(soup):
return json_content
# Hook only onto elife articles for rewriting currently
journal_id_tag = elifetools.rawJATS.journal_id(soup)
doi_tag = elifetools.rawJATS.doi(soup)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrite_elife_references_json(json_content, doi):
""" this does the work of rewriting elife references json """ |
references_rewrite_json = elife_references_rewrite_json()
if doi in references_rewrite_json:
json_content = rewrite_references_json(json_content, references_rewrite_json[doi])
# Edge case delete one reference
if doi == "10.7554/eLife.12125":
for i, ref in enumerate(json_content):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrite_references_json(json_content, rewrite_json):
""" general purpose references json rewriting by matching the id value """ |
for ref in json_content:
if ref.get("id") and ref.get("id") in rewrite_json:
for key, value in iteritems(rewrite_json.get(ref.get("id"))):
ref[key] = value
return json_content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrite_elife_funding_awards(json_content, doi):
""" rewrite elife funding awards """ |
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_content[i]
# add funding award recipient
if doi == "10.7554/eLife.04250":
recipients_for_04250 = [{"type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def person_same_name_map(json_content, role_from):
"to merge multiple editors into one record, filter by role values and group by name"
matched_editors = [(i, person) for i, person in enumerate(json_content)
if person.get('role') in role_from]
same_name_map = {}
for i, editor in 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 metadata_lint(old, new, locations):
"""Run the linter over the new metadata, comparing to the old.""" |
# ensure we don't modify the metadata
old = old.copy()
new = new.copy()
# remove version info
old.pop('$version', None)
new.pop('$version', None)
for old_group_name in old:
if old_group_name not in new:
yield LintError('', 'api group removed', api_name=old_group_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 lint_api(api_name, old, new, locations):
"""Lint an acceptable api metadata.""" |
is_new_api = not old
api_location = locations['api']
changelog = new.get('changelog', {})
changelog_location = api_location
if locations['changelog']:
changelog_location = list(locations['changelog'].values())[0]
# apis must have documentation if they are new
if not new.get('doc')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self):
"""Serialize into JSONable dict, and associated locations data.""" |
api_metadata = OrderedDict()
# $ char makes this come first in sort ordering
api_metadata['$version'] = self.current_version
locations = {}
for svc_name, group in self.groups():
group_apis = OrderedDict()
group_metadata = OrderedDict()
group_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api(self, url, name, introduced_at=None, undocumented=False, deprecated_at=None, title=None, **options):
"""Add an API to the service. :param url: This is th... |
location = get_callsite_location()
api = AcceptableAPI(
self,
name,
url,
introduced_at,
options,
undocumented=undocumented,
deprecated_at=deprecated_at,
title=title,
location=location,
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def django_api( self, name, introduced_at, undocumented=False, deprecated_at=None, title=None, **options):
"""Add a django API handler to the service. :param nam... |
from acceptable.djangoutil import DjangoAPI
location = get_callsite_location()
api = DjangoAPI(
self,
name,
introduced_at,
options,
location=location,
undocumented=undocumented,
deprecated_at=deprecated_at,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changelog(self, api_version, doc):
"""Add a changelog entry for this api.""" |
doc = textwrap.dedent(doc).strip()
self._changelog[api_version] = doc
self._changelog_locations[api_version] = get_callsite_location() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def title_prefix(soup):
"titlePrefix for article JSON is only articles with certain display_channel values"
prefix = None
display_channel_match_list = ['feature article', 'insight', 'editorial']
for d_channel in display_channel(soup):
if d_channel.lower() in display_channel_match_list:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def title_prefix_json(soup):
"titlePrefix with capitalisation changed"
prefix = title_prefix(soup)
prefix_rewritten = elifetools.json_rewrite.rewrite_json("title_prefix_json", soup, prefix)
return prefix_rewritten |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def research_organism(soup):
"Find the research-organism from the set of kwd-group tags"
if not raw_parser.research_organism_keywords(soup):
return []
return list(map(node_text, raw_parser.research_organism_keywords(soup))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def full_research_organism(soup):
"research-organism list including inline tags, such as italic"
if not raw_parser.research_organism_keywords(soup):
return []
return list(map(node_contents_str, raw_parser.research_organism_keywords(soup))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keywords(soup):
""" Find the keywords from the set of kwd-group tags which are typically labelled as the author keywords """ |
if not raw_parser.author_keywords(soup):
return []
return list(map(node_text, raw_parser.author_keywords(soup))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def full_keywords(soup):
"author keywords list including inline tags, such as italic"
if not raw_parser.author_keywords(soup):
return []
return list(map(node_contents_str, raw_parser.author_keywords(soup))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def version_history(soup, html_flag=True):
"extract the article version history details"
convert = lambda xml_string: xml_to_html(html_flag, xml_string)
version_history = []
related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
for tag in related_object_tags:
article... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.