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.view(parent.view._factory, req)
obj = parent_view.get_item(**req.matchdict)
if isinstance(self, ItemSubresourceBaseView):
return
prop = self._resource.collection_name
return getattr(obj, prop, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_collection(self, **kwargs):
""" Get objects collection taking into account generated queryset of parent view. This method allows working with nested resources properly. Thus a queryset returned by this method will be a subset of its parent view's queryset, thus filtering out objects that don't belong to the parent object. """ |
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 properly. Thus an item returned by this method will belong to its parent view's queryset, thus filtering out objects that don't belong to the parent object. Returns an object from the applicable ACL. If ACL wasn't applied, it is applied explicitly. """ |
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__,
self._get_context_key(**kwargs)))
return self.context |
<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 :kwargs: and then getting a context key item from the new instance of `self._factory` which is an ACL class used by the current view. Arguments: :es_based: Boolean. Whether to init ACL ac es-based or not. This affects the backend which will be queried - either DB or ES :kwargs: Kwargs that contain value for current resource 'id_name' key """ |
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.Model
self.context = acl[key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_collection_es(self):
""" Get ES objects collection taking into account the generated queryset of parent view. This method allows working with nested resources properly. Thus a queryset returned by this method will be a subset of its parent view's queryset, thus filtering out objects that don't belong to the parent object. """ |
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 resources properly. Thus an item returned by this method will belong to its parent view's queryset, thus filtering out objects that don't belong to the parent object. Returns an object retrieved from the applicable ACL. If an ACL wasn't applied, it is applied explicitly. """ |
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 is not None) and (item_id not in objects_ids):
raise JHTTPNotFound('{}(id={}) resource not found'.format(
self.Model.__name__, item_id))
return self.context |
<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 make sure deleted objects are those filtered by ES in the 'index' method (so user deletes what he saw). """ |
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 sure updated objects are those filtered by ES in the 'index' method (so user updates what he saw). """ |
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 parent object, so only the ``name`` can be used for referencing. :type app: sphinx.application.Sphinx :param what: The parent type, ``class`` or ``module`` :type what: str :param name: The name of the child method/attribute. :type name: str :param obj: The child value (e.g. a method, dict, or module reference) :param options: The current autodoc settings. :type options: dict .. seealso:: http://www.sphinx-doc.org/en/stable/ext/autodoc.html#event-autodoc-skip-member """ |
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.Sphinx :param what: The parent type, ``class`` or ``module`` :type what: str :param name: The dotted path to the child method/attribute. :type name: str :param obj: The Python object that i s being documented. :param options: The current autodoc settings. :type options: dict :param lines: The current documentation lines :type lines: list """ |
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 ``__init__()`` method. :type app: sphinx.application.Sphinx :type lines: list """ |
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:
lines.append(u':param %s: %s' % (field.name, help_text))
else:
lines.append(u':param %s: %s' % (field.name, verbose_name))
# Add type
lines.append(_get_field_type(field))
if 'sphinx.ext.inheritance_diagram' in app.extensions and \
'sphinx.ext.graphviz' in app.extensions and \
not any('inheritance-diagram::' in line for line in lines):
lines.append('.. inheritance-diagram::') |
<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,
field=field,
label=field.label or name.replace('_', ' ').title(),
field_type=field_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 _improve_attribute_docs(obj, name, lines):
"""Improve the documentation of various attributes. This improves the navigation between related objects. :param obj: the instance of the object to document. :param name: full dotted path to the object. :param lines: expected documentation lines. """ |
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)
field = model._meta.get_field(obj.field_name)
del lines[:] # lines.clear() is Python 3 only
lines.append("**Model field:** {label}".format(
label=field.verbose_name
))
elif isinstance(obj, _FIELD_DESCRIPTORS):
# These
del lines[:]
lines.append("**Model field:** {label}".format(
label=obj.field.verbose_name
))
if isinstance(obj, FileDescriptor):
lines.append("**Return type:** :class:`~django.db.models.fields.files.FieldFile`")
elif PhoneNumberDescriptor is not None and isinstance(obj, PhoneNumberDescriptor):
lines.append("**Return type:** :class:`~phonenumber_field.phonenumber.PhoneNumber`")
elif isinstance(obj, related_descriptors.ForwardManyToOneDescriptor):
# Display a reasonable output for forward descriptors.
related_model = obj.field.remote_field.model
if isinstance(related_model, str):
cls_path = related_model
else:
cls_path = "{}.{}".format(related_model.__module__, related_model.__name__)
del lines[:]
lines.append("**Model field:** {label}, "
"accesses the :class:`~{cls_path}` model.".format(
label=obj.field.verbose_name, cls_path=cls_path
))
elif isinstance(obj, related_descriptors.ReverseOneToOneDescriptor):
related_model = obj.related.related_model
if isinstance(related_model, str):
cls_path = related_model
else:
cls_path = "{}.{}".format(related_model.__module__, related_model.__name__)
del lines[:]
lines.append("**Model field:** {label}, "
"accesses the :class:`~{cls_path}` model.".format(
label=obj.related.field.verbose_name, cls_path=cls_path
))
elif isinstance(obj, related_descriptors.ReverseManyToOneDescriptor):
related_model = obj.rel.related_model
if isinstance(related_model, str):
cls_path = related_model
else:
cls_path = "{}.{}".format(related_model.__module__, related_model.__name__)
del lines[:]
lines.append("**Model field:** {label}, "
"accesses the M2M :class:`~{cls_path}` model.".format(
label=obj.field.verbose_name, cls_path=cls_path
))
elif isinstance(obj, (models.Manager, ManagerDescriptor)):
# Somehow the 'objects' manager doesn't pass through the docstrings.
module, cls_name, field_name = name.rsplit('.', 2)
lines.append("Django manager to access the ORM")
tpl = "Use ``{cls_name}.objects.all()`` to fetch all objects."
lines.append(tpl.format(cls_name=cls_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_method_docs(obj, name, lines):
"""Improve the documentation of various methods. :param obj: the instance of the method to document. :param name: full dotted path to the object. :param lines: expected documentation lines. """ |
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 the label of the :attr:`{field}`".format(
field=match.group('field')
))
elif '.get_next_by_' in name:
match = RE_GET_NEXT_BY.search(name)
if match is not None:
lines.append("**Autogenerated:** Finds next instance"
" based on :attr:`{field}`.".format(
field=match.group('field')
))
elif '.get_previous_by_' in name:
match = RE_GET_PREVIOUS_BY.search(name)
if match is not None:
lines.append("**Autogenerated:** Finds previous instance"
" based on :attr:`{field}`.".format(
field=match.group('field')
)) |
<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 contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficients should be normalized; see references for details. :return: A ``[order x 4]`` array of Fourier coefficients. :rtype: :py:class:`numpy.ndarray` """ |
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
d_cos_phi_n = np.cos(phi_n[1:]) - np.cos(phi_n[:-1])
d_sin_phi_n = np.sin(phi_n[1:]) - np.sin(phi_n[:-1])
a_n = const * np.sum((dxy[:, 0] / dt) * d_cos_phi_n)
b_n = const * np.sum((dxy[:, 0] / dt) * d_sin_phi_n)
c_n = const * np.sum((dxy[:, 1] / dt) * d_cos_phi_n)
d_n = const * np.sum((dxy[:, 1] / dt) * d_sin_phi_n)
coeffs[n - 1, :] = a_n, b_n, c_n, d_n
if normalize:
coeffs = normalize_efd(coeffs)
return coeffs |
<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 ``[n x 4]`` Fourier coefficient array. :param bool size_invariant: If size invariance normalizing should be done as well. Default is ``True``. :return: The normalized ``[n x 4]`` Fourier coefficient array. :rtype: :py:class:`numpy.ndarray` """ |
# 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)))
# Rotate all coefficients by theta_1.
for n in _range(1, coeffs.shape[0] + 1):
coeffs[n - 1, :] = np.dot(
np.array([[coeffs[n - 1, 0], coeffs[n - 1, 1]],
[coeffs[n - 1, 2], coeffs[n - 1, 3]]]),
np.array([[np.cos(n * theta_1), -np.sin(n * theta_1)],
[np.sin(n * theta_1), np.cos(n * theta_1)]])).flatten()
# Make the coefficients rotation invariant by rotating so that
# the semi-major axis is parallel to the x-axis.
psi_1 = np.arctan2(coeffs[0, 2], coeffs[0, 0])
psi_rotation_matrix = np.array([[np.cos(psi_1), np.sin(psi_1)],
[-np.sin(psi_1), np.cos(psi_1)]])
# Rotate all coefficients by -psi_1.
for n in _range(1, coeffs.shape[0] + 1):
coeffs[n - 1, :] = psi_rotation_matrix.dot(
np.array([[coeffs[n - 1, 0], coeffs[n - 1, 1]],
[coeffs[n - 1, 2], coeffs[n - 1, 3]]])).flatten()
if size_invariant:
# Obtain size-invariance by normalizing.
coeffs /= np.abs(coeffs[0, 0])
return coeffs |
<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 Y coordinate on the screen in pixels. :param screen: the screen (number) you want to move on. """ |
# 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 parameter)
# Major opcode of failed request: 41 (X_WarpPointer)
# Resource id in failed request: 0x2a4fca0
# Serial number of failed request: 25
# Current serial number in output stream: 26
# Just to be safe..
# screen = 0
x = ctypes.c_int(x)
y = ctypes.c_int(y)
screen = ctypes.c_int(screen)
_libxdo.xdo_move_mouse(self._xdo, x, y, screen) |
<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 target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. """ |
_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 distance in pixels to move on the Y axis. """ |
_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 mouse_location2(x.value, y.value, screen_num_ret.value,
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_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 satisified. :param origin_x: the X position you expect the mouse to move from :param origin_y: the Y position you expect the mouse to move from """ |
_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. :param dest_x: the X position you expect the mouse to move to :param dest_y: the Y position you expect the mouse to move to """ |
_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 the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. """ |
_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. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. :param repeat: number of repetitions (default: 2) :param delay: delay between clicks, in microseconds (default: 100k) """ |
_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 :param window: The window you want to send keystrokes to or CURRENTWINDOW :param string: The string to type, like "Hello world!" :param delay: The delay between keystrokes in microseconds. 12000 is a decent choice if you don't have other plans. """ |
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 symbol name. Any combination of X11 KeySym names separated by '+' are valid. Single KeySym names are valid, too. Examples: "l" "semicolon" "alt+Return" "Alt_L+Tab" If you want to type a string, such as "Hello world." you want to instead use xdo_enter_text_window. :param window: The window you want to send the keysequence to or CURRENTWINDOW :param keysequence: The string keysequence to send. :param delay: The delay between keystrokes in microseconds. """ |
_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 send events to or CURRENTWINDOW :param keys: The array of charcodemap_t entities to send. :param pressed: 1 for key press, 0 for key release. :param modifier: Pointer to integer to record the modifiers activated by the keys being pressed. If NULL, we don't save the modifiers. :param delay: The delay between keystrokes in microseconds. """ |
# 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_keycode_list(
self._xdo, ctypes.byref(keys), ctypes.byref(nkeys))
# todo: make sure this returns a list of charcodemap_t!
return keys.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_map_state(self, window, state):
""" Wait for a window to have a specific map state. State possibilities: IsUnmapped - window is not displayed. IsViewable - window is mapped and shown (though may be clipped by windows on top of it) IsUnviewable - window is mapped but a parent window is unmapped. :param window: the window you want to wait for. :param state: the state to wait for. """ |
_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: the window to move :param x: the X coordinate to move to. :param y: the Y coordinate to move to. """ |
_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 desired height :param flags: if 0, use pixels for units. If SIZE_USEHINTS, then the units will be relative to the window size hints. """ |
_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: The window to change a property of. :param name: the string name of the property. :param value: the string value of the property. """ |
_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 class_: The new class. If ``None``, no change. """ |
_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 manager will manage this window. If you set it to 1, the window manager will usually not draw borders on the window, etc. If you set it to 0, the window manager will see it like a normal application 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, wait for focus. If 0, wait for loss of focus. """ |
_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_ACTIVE_WINDOW from the EWMH spec. :param window: the window to wait on :param active: If 1, wait for active. If 0, wait for inactive. """ |
_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 window """ |
_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 where the current number of desktops is stored """ |
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 :param desktop: the desktop destination for the window """ |
_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_DESKTOP``, then '*desktop' remains unmodified. :param wid: the window to query """ |
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, limit=0, max_depth=-1):
""" Search for windows. :param winname: Regexp to be matched against window name :param winclass: Regexp to be matched against window class :param winclassname: Regexp to be matched against window class name :param pid: Only return windows from this PID :param only_visible: If True, only return visible windows :param screen: Search only windows on this screen :param require: If True, will match ALL conditions. Otherwise, windows matching ANY condition will be returned. :param searchmask: Search mask, for advanced usage. Leave this alone if you don't kwnow what you are doing. :param limit: Maximum number of windows to list. Zero means no limit. :param max_depth: Maximum depth to return. Defaults to -1, meaning "no limit". :return: A list of window ids matching query. """ |
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.winclass = winclass
search.searchmask |= SEARCH_CLASS
if winclassname is not None:
search.winclassname = winclassname
search.searchmask |= SEARCH_CLASSNAME
if pid is not None:
search.pid = pid
search.searchmask |= SEARCH_PID
if only_visible:
search.only_visible = True
search.searchmask |= SEARCH_ONLYVISIBLE
if screen is not None:
search.screen = screen
search.searchmask |= SEARCH_SCREEN
if screen is not None:
search.screen = desktop
search.searchmask |= SEARCH_DESKTOP
search.limit = limit
search.max_depth = max_depth
_libxdo.xdo_search_windows(
self._xdo, search,
ctypes.byref(windowlist_ret),
ctypes.byref(nwindows_ret))
return [windowlist_ret[i] for i in range(nwindows_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_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, such as "alt" to "Alt_L" :return: array of 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 = []
while True:
c = sm[i]
if c is None:
return ret
ret.append(c)
i += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_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.value
_libX11.XFree(name_ptr) # Free the string allocated by Xlib
return 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 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)
return modules |
<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
for group in metadata:
if group == '$version':
continue
apis = metadata[group]['apis']
for api in apis.values():
int_changelog = OrderedDict()
for version, log in api.get('changelog', {}).items():
int_changelog[int(version)] = log
api['changelog'] = int_changelog
finally:
stream.close()
return metadata |
<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:
string = string.replace(match, replacement)
return string
if value == None:
return None
if type(value) == list:
return [strip_punctuation(v) for v in value]
return strip_punctuation(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 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
new_string = string1.rstrip()
if not new_string.endswith(glue):
new_string += glue
new_string += ' ' + string2.lstrip()
return new_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 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):
#logger.debug("date failed to convert: %s" % str(ymdtz))
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 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 = 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 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 tag inside it as the acting parent tag """ |
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
return acting_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_tag in first_parent_tag.find_all(tag.name):
if 'mimetype' in tag.attrs and tag['mimetype'] == 'video':
# Count all video type media tags
if 'mimetype' in media_tag.attrs and tag['mimetype'] == 'video':
sibling_ordinal += 1
if media_tag == tag:
break
else:
# Count all non-video type media tags
if (('mimetype' not in media_tag.attrs)
or ('mimetype' in media_tag.attrs and tag['mimetype'] != 'video')):
sibling_ordinal += 1
if media_tag == tag:
break
else:
# Start counting at 1
sibling_ordinal = 1
for prev_tag in tag.find_all_previous(tag.name):
if not first_parent(prev_tag, nodenames):
if 'mimetype' in tag.attrs and tag['mimetype'] == 'video':
# Count all video type media tags
if supp_asset(prev_tag) == supp_asset(tag) and 'mimetype' in prev_tag.attrs:
sibling_ordinal += 1
else:
if supp_asset(prev_tag) == supp_asset(tag) and 'mimetype' not in prev_tag.attrs:
sibling_ordinal += 1
return sibling_ordinal |
<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 sibling ordinal. The result is its position inside any parent tag that are the same asset type """ |
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 the same asset value
for supp_tag in first_parent_tag.find_all(tag.name):
if tag == supp_tag:
# Stop once we reach the same tag we are checking
break
if supp_asset(supp_tag) == supp_asset(tag):
sibling_ordinal += 1
else:
# Look in all previous elements that do not have a parent
# and count the tags having the same asset value
for prev_tag in tag.find_all_previous(tag.name):
if not first_parent(prev_tag, nodenames):
if supp_asset(prev_tag) == supp_asset(tag):
sibling_ordinal += 1
return sibling_ordinal |
<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
else:
keep_words.append(word)
if len(keep_words) > 0:
title = " ".join(keep_words)
if title.split(" ")[-1] != "spp.":
title = title.rstrip(" .:")
return title |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape_ampersand(string):
""" Quick convert unicode ampersand characters not associated with a numbered entity or not starting with allowed characters to a plain & """ |
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_doctype_dict to True """ |
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 = CustomTreeBuilder()
parser = ElementTree.XMLParser(html=0, target=tree_builder, encoding='utf-8')
tree = ElementTree.parse(filename, parser)
root = tree.getroot()
if sys.version_info < (3,2):
doctype_dict = parser.doctype_dict
else:
doctype_dict = tree_builder.doctype_dict
if return_doctype_dict is True:
return root, doctype_dict
else:
return root |
<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 to role tags """ |
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
xpath_parent = './/front/article-meta/article-categories'
# the wraping tag in case article-categories does not exist
xpath_article_meta = './/front/article-meta'
# the xpath to find the subject tags we are interested in
xpath = './/{parent_tag_name}[@{tag_attribute}="{group_type}"]'.format(
parent_tag_name=parent_tag_name,
tag_attribute=tag_attribute,
group_type=subject_group_type)
count = 0
# get the parent tag
parent_tag = root.find(xpath_parent)
if parent_tag is None:
# parent tag not found, add one
wrap_tag = root.find(xpath_article_meta)
article_categories_tag = SubElement(wrap_tag, wrap_tag_name)
parent_tag = article_categories_tag
insert_index = 0
# iterate all tags to find the index of the first tag we are interested in
if parent_tag is not None:
for tag_index, tag in enumerate(parent_tag.findall('*')):
if tag.tag == parent_tag_name and tag.get(tag_attribute) == subject_group_type:
insert_index = tag_index
if overwrite is True:
# if overwriting use the first one found
break
# if not overwriting, use the last one found + 1
if overwrite is not True:
insert_index += 1
# remove the tag if overwriting the existing values
if overwrite is True:
# remove all the tags
for tag in root.findall(xpath):
parent_tag.remove(tag)
# add the subjects
for subject in subjects:
subj_group_tag = Element(parent_tag_name)
subj_group_tag.set(tag_attribute, subject_group_type)
subject_tag = SubElement(subj_group_tag, tag_name)
subject_tag.text = subject
parent_tag.insert(insert_index, subj_group_tag)
count += 1
insert_index += 1
return 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 build_doctype(qualifiedName, publicId=None, systemId=None, internalSubset=None):
""" Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with some properties so it is more testable """ |
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 only, rewrite the JSON to make it valid """ |
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)
journal_id = elifetools.utils.node_text(journal_id_tag)
doi = elifetools.utils.doi_uri_to_doi(elifetools.utils.node_text(doi_tag))
if journal_id.lower() == "elife":
function_name = rewrite_function_name(journal_id, rewrite_type)
if function_name:
try:
json_content = globals()[function_name](json_content, doi)
except KeyError:
pass
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_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):
if ref.get("id") and ref.get("id") == "bib11":
del json_content[i]
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_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": "person", "name": {"preferred": "Eric Jonas", "index": "Jonas, Eric"}}]
for i, award in enumerate(json_content):
if "id" in award and award["id"] in ["par-2", "par-3", "par-4"]:
if "recipients" not in award:
json_content[i]["recipients"] = recipients_for_04250
# add funding award recipient
if doi == "10.7554/eLife.06412":
recipients_for_06412 = [{"type": "person", "name": {"preferred": "Adam J Granger", "index": "Granger, Adam J"}}]
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-1":
if "recipients" not in award:
json_content[i]["recipients"] = recipients_for_06412
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 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 matched_editors:
if not editor.get("name"):
continue
# compare name of each
name = editor.get("name").get("index")
if name not in same_name_map:
same_name_map[name] = []
same_name_map[name].append(i)
return same_name_map |
<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)
for group_name, new_group in new.items():
old_group = old.get(group_name, {'apis': {}})
for name, api in new_group['apis'].items():
old_api = old_group['apis'].get(name, {})
api_locations = locations[name]
for message in lint_api(name, old_api, api, api_locations):
message.api_name = name
if message.location is None:
message.location = api_locations['api']
yield message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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'):
msg_type = LintError if is_new_api else LintWarning
yield msg_type(
'doc',
'missing docstring documentation',
api_name=api_name,
location=locations.get('view', api_location)
)
introduced_at = new.get('introduced_at')
if introduced_at is None:
yield LintError(
'introduced_at',
'missing introduced_at field',
location=api_location,
)
if not is_new_api:
# cannot change introduced_at if we already have it
old_introduced_at = old.get('introduced_at')
if old_introduced_at is not None:
if old_introduced_at != introduced_at:
yield LintError(
'introduced_at',
'introduced_at changed from {} to {}',
old_introduced_at,
introduced_at,
api_name=api_name,
location=api_location,
)
# cannot change url
if new['url'] != old.get('url', new['url']):
yield LintError(
'url',
'url changed from {} to {}',
old['url'],
new['url'],
api_name=api_name,
location=api_location,
)
# cannot add required fields
for removed in set(old.get('methods', [])) - set(new['methods']):
yield LintError(
'methods',
'HTTP method {} removed',
removed,
api_name=api_name,
location=api_location,
)
for schema in ['request_schema', 'response_schema']:
new_schema = new.get(schema)
if new_schema is None:
continue
schema_location = locations[schema]
old_schema = old.get(schema, {})
for message in walk_schema(
schema, old_schema, new_schema, root=True, new_api=is_new_api):
if isinstance(message, CheckChangelog):
if message.revision not in changelog:
yield LintFixit(
message.name,
'No changelog entry for revision {}',
message.revision,
location=changelog_location,
)
else:
# add in here, saves passing it down the recursive call
message.location = schema_location
yield message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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_metadata['apis'] = group_apis
group_metadata['title'] = group.title
api_metadata[group.name] = group_metadata
if group.docs is not None:
group_metadata['docs'] = group.docs
for name, api in group.items():
group_apis[name] = OrderedDict()
group_apis[name]['service'] = svc_name
group_apis[name]['api_group'] = group.name
group_apis[name]['api_name'] = api.name
group_apis[name]['introduced_at'] = api.introduced_at
group_apis[name]['methods'] = api.methods
group_apis[name]['request_schema'] = api.request_schema
group_apis[name]['response_schema'] = api.response_schema
group_apis[name]['doc'] = api.docs
group_apis[name]['changelog'] = api._changelog
if api.title:
group_apis[name]['title'] = api.title
else:
title = name.replace('-', ' ').replace('_', ' ').title()
group_apis[name]['title'] = title
group_apis[name]['url'] = api.resolve_url()
if api.undocumented:
group_apis[name]['undocumented'] = True
if api.deprecated_at is not None:
group_apis[name]['deprecated_at'] = api.deprecated_at
locations[name] = {
'api': api.location,
'request_schema': api._request_schema_location,
'response_schema': api._response_schema_location,
'changelog': api._changelog_locations,
'view': api.view_fn_location,
}
return api_metadata, locations |
<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 the url that the API should be registered at. :param name: This is the name of the api, and will be registered with flask apps under. Other keyword arguments may be used, and they will be passed to the flask application when initialised. Of particular interest is the 'methods' keyword argument, which can be used to specify the HTTP method the URL will be added for. """ |
location = get_callsite_location()
api = AcceptableAPI(
self,
name,
url,
introduced_at,
options,
undocumented=undocumented,
deprecated_at=deprecated_at,
title=title,
location=location,
)
self.metadata.register_api(self.name, self.group, api)
return api |
<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 name: This is the name of the django url to use. The 'methods' paramater can be supplied as normal, you can also user the @api.handler decorator to link this API to its handler. """ |
from acceptable.djangoutil import DjangoAPI
location = get_callsite_location()
api = DjangoAPI(
self,
name,
introduced_at,
options,
location=location,
undocumented=undocumented,
deprecated_at=deprecated_at,
title=title,
)
self.metadata.register_api(self.name, self.group, api)
return api |
<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:
if raw_parser.sub_display_channel(soup):
prefix = node_text(first(raw_parser.sub_display_channel(soup)))
return prefix |
<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_version = OrderedDict()
date_tag = first(raw_parser.date(tag))
if date_tag:
copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')
(day, month, year) = ymd(date_tag)
article_version['day'] = day
article_version['month'] = month
article_version['year'] = year
article_version['date'] = date_struct_nn(year, month, day)
copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')
set_if_value(article_version, "comment",
convert(node_contents_str(first(raw_parser.comment(tag)))))
version_history.append(article_version)
return version_history |
Subsets and Splits