text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Generate an ACL.
<END_TASK>
<USER_TASK:>
Description:
def generate_acl(config, model_cls, raml_resource, es_based=True):
""" Generate an ACL.
Generated ACL class has a `item_model` attribute set to
:model_cls:.
ACLs used for collection and item access control are generated from a
fi... |
schemes = raml_resource.security_schemes or []
schemes = [sch for sch in schemes if sch.type == 'x-ACL']
if not schemes:
collection_acl = item_acl = []
log.debug('No ACL scheme applied. Using ACL: {}'.format(item_acl))
else:
sec_scheme = schemes[0]
log.debug('{} ACL sch... |
<SYSTEM_TASK:>
Override to support ACL filtering.
<END_TASK>
<USER_TASK:>
Description:
def getitem_es(self, key):
""" Override to support ACL filtering.
To do so: passes `self.request` to `get_item` and uses
`ACLFilterES`.
""" |
from nefertari_guards.elasticsearch import ACLFilterES
es = ACLFilterES(self.item_model.__name__)
params = {
'id': key,
'request': self.request,
}
obj = es.get_item(**params)
obj.__acl__ = self.item_acl(obj)
obj.__parent__ = self
o... |
<SYSTEM_TASK:>
Generate view method names needed for `raml_resource` view.
<END_TASK>
<USER_TASK:>
Description:
def resource_view_attrs(raml_resource, singular=False):
""" Generate view method names needed for `raml_resource` view.
Collects HTTP method names from resource siblings and dynamic children
if e... |
from .views import collection_methods, item_methods
# Singular resource doesn't have collection methods though
# it looks like a collection
if singular:
collection_methods = item_methods
siblings = get_resource_siblings(raml_resource)
http_methods = [sibl.method.lower() for sibl in sib... |
<SYSTEM_TASK:>
Prepare map of event subscribers.
<END_TASK>
<USER_TASK:>
Description:
def get_events_map():
""" Prepare map of event subscribers.
* Extends copies of BEFORE_EVENTS and AFTER_EVENTS maps with
'set' action.
* Returns map of {before/after: {action: event class(es)}}
""" |
from nefertari import events
set_keys = ('create', 'update', 'replace', 'update_many', 'register')
before_events = events.BEFORE_EVENTS.copy()
before_events['set'] = [before_events[key] for key in set_keys]
after_events = events.AFTER_EVENTS.copy()
after_events['set'] = [after_events[key] for k... |
<SYSTEM_TASK:>
Patches view_cls.Model with model_cls.
<END_TASK>
<USER_TASK:>
Description:
def patch_view_model(view_cls, model_cls):
""" Patches view_cls.Model with model_cls.
:param view_cls: View class "Model" param of which should be
patched
:param model_cls: Model class which should be used to... |
original_model = view_cls.Model
view_cls.Model = model_cls
try:
yield
finally:
view_cls.Model = original_model |
<SYSTEM_TASK:>
Get route name from RAML resource URI.
<END_TASK>
<USER_TASK:>
Description:
def get_route_name(resource_uri):
""" Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripp... |
resource_uri = resource_uri.strip('/')
resource_uri = re.sub('\W', '', resource_uri)
return resource_uri |
<SYSTEM_TASK:>
Perform complete one resource configuration process
<END_TASK>
<USER_TASK:>
Description:
def generate_resource(config, raml_resource, parent_resource):
""" Perform complete one resource configuration process
This function generates: ACL, view, route, resource, database
model for a given `ram... |
from .models import get_existing_model
# Don't generate resources for dynamic routes as they are already
# generated by their parent
resource_uri = get_resource_uri(raml_resource)
if is_dynamic_uri(resource_uri):
if parent_resource.is_root:
raise Exception("Top-level resources ... |
<SYSTEM_TASK:>
Handle server generation process.
<END_TASK>
<USER_TASK:>
Description:
def generate_server(raml_root, config):
""" Handle server generation process.
:param raml_root: Instance of ramlfications.raml.RootNode.
:param config: Pyramid Configurator instance.
""" |
log.info('Server generation started')
if not raml_root.resources:
return
root_resource = config.get_root_resource()
generated_resources = {}
for raml_resource in raml_root.resources:
if raml_resource.path in generated_resources:
continue
# Get Nefertari paren... |
<SYSTEM_TASK:>
Generate REST view for a model class.
<END_TASK>
<USER_TASK:>
Description:
def generate_rest_view(config, model_cls, attrs=None, es_based=True,
attr_view=False, singular=False):
""" Generate REST view for a model class.
:param model_cls: Generated DB model class.
:para... |
valid_attrs = (list(collection_methods.values()) +
list(item_methods.values()))
missing_attrs = set(valid_attrs) - set(attrs)
if singular:
bases = [ItemSingularView]
elif attr_view:
bases = [ItemAttributeView]
elif es_based:
bases = [ESCollectionView]
... |
<SYSTEM_TASK:>
Get location of the `obj`
<END_TASK>
<USER_TASK:>
Description:
def _location(self, obj):
""" Get location of the `obj`
Arguments:
:obj: self.Model instance.
""" |
field_name = self.clean_id_name
return self.request.route_url(
self._resource.uid,
**{self._resource.id_name: getattr(obj, field_name)}) |
<SYSTEM_TASK:>
Get queryset of parent view.
<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:>
Get objects collection taking into account generated queryset
<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... |
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:>
Get collection item taking into account generated queryset
<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
... |
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:>
Reload `self.context` object into a DB or ES object.
<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... |
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:>
Get ES objects collection taking into account the generated
<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... |
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:>
Get ES collection item taking into account generated queryset
<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_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:>
Delete multiple objects from collection.
<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... |
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._delete_many(db_objects, self.request) |
<SYSTEM_TASK:>
Update multiple objects from collection.
<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
... |
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._update_many(
db_objects, self._json_params, self.request) |
<SYSTEM_TASK:>
Allow this module to be used as sphinx extension.
<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:>
Fix the appearance of some classes in autodoc.
<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:>
Hook that tells autodoc to include or exclude certain fields.
<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 ``na... |
if name in config.EXCLUDE_MEMBERS:
return True
if name in config.INCLUDE_MEMBERS:
return False
return skip |
<SYSTEM_TASK:>
Hook that improves the autodoc docstrings for Django models.
<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 ty... |
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:>
Improve the documentation of a class.
<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:>
Improve the documentation of a Django model subclass.
<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.appl... |
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:>
Improve the documentation of a Django Form class.
<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:>
Improve the documentation of various attributes.
<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.
... |
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:>
Improve the documentation of various methods.
<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: e... |
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:>
Calculate elliptical Fourier descriptors for a contour.
<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]``.
:pa... |
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:>
Normalizes an array of Fourier coefficients.
<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... |
# 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:>
Generate input mask from bytemask
<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:>
Move the mouse to a specific location.
<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 pixel... |
# 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:>
Move the mouse to a specific location relative to the top-left corner
<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 ... |
_libxdo.xdo_move_mouse_relative_to_window(
self._xdo, ctypes.c_ulong(window), x, y) |
<SYSTEM_TASK:>
Move the mouse relative to it's current position.
<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 mo... |
_libxdo.xdo_move_mouse_relative(self._xdo, x, y) |
<SYSTEM_TASK:>
Get the window the mouse is currently over
<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:>
Get all mouse location-related data.
<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:>
Wait for the mouse to move from a location. This function will block
<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.
... |
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, origin_x, origin_y) |
<SYSTEM_TASK:>
Wait for the mouse to move to a location. This function will block
<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... |
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, dest_x, dest_y) |
<SYSTEM_TASK:>
Send a click for a specific mouse button at the current mouse location.
<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 ... |
_libxdo.xdo_click_window(self._xdo, window, button) |
<SYSTEM_TASK:>
Send a one or more clicks for a specific mouse button at the
<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 windo... |
_libxdo.xdo_click_window_multiple(
self._xdo, window, button, repeat, delay) |
<SYSTEM_TASK:>
Type a string to the specified window.
<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
"alt+l", you want instead ``send_ke... |
return _libxdo.xdo_enter_text_window(self._xdo, window, string, delay) |
<SYSTEM_TASK:>
Send a keysequence to the specified window.
<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 X1... |
_libxdo.xdo_send_keysequence_window(
self._xdo, window, keysequence, delay) |
<SYSTEM_TASK:>
Send a series of keystrokes.
<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
:p... |
# 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:>
Wait for a window to have a specific map state.
<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 -... |
_libxdo.xdo_wait_for_window_map_state(self._xdo, window, state) |
<SYSTEM_TASK:>
Move a window to a specific location.
<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 ... |
_libxdo.xdo_move_window(self._xdo, window, x, y) |
<SYSTEM_TASK:>
Change the window size.
<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,... |
_libxdo.xdo_set_window_size(self._xdo, window, w, h, flags) |
<SYSTEM_TASK:>
Change a window property.
<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.
:par... |
_libxdo.xdo_set_window_property(self._xdo, window, name, value) |
<SYSTEM_TASK:>
Change the window's classname and or class.
<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 ``N... |
_libxdo.xdo_set_window_class(self._xdo, window, name, class_) |
<SYSTEM_TASK:>
Set the override_redirect value for a window. This generally means
<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 ma... |
_libxdo.xdo_set_window_override_redirect(
self._xdo, window, override_redirect) |
<SYSTEM_TASK:>
Get the window currently having focus.
<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:>
Wait for a window to have or lose focus.
<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 los... |
_libxdo.xdo_wait_for_window_focus(self._xdo, window, want_focus) |
<SYSTEM_TASK:>
Wait for a window to be active or not active.
<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 spe... |
_libxdo.xdo_wait_for_window_active(self._xdo, window, active) |
<SYSTEM_TASK:>
Reparents a window
<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:>
Get the currently-active window.
<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:>
Get a window ID by clicking on it.
<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:>
Get the current number of desktops.
<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 ... |
ndesktops = ctypes.c_long(0)
_libxdo.xdo_get_number_of_desktops(self._xdo, ctypes.byref(ndesktops))
return ndesktops.value |
<SYSTEM_TASK:>
Move a window to another desktop
<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 destinat... |
_libxdo.xdo_set_desktop_for_window(self._xdo, window, desktop) |
<SYSTEM_TASK:>
Get the desktop a window is on.
<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 ... |
desktop = ctypes.c_long(0)
_libxdo.xdo_get_desktop_for_window(
self._xdo, window, ctypes.byref(desktop))
return desktop.value |
<SYSTEM_TASK:>
Search for windows.
<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 f... |
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:>
If you need the symbol map, use this method.
<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"
... |
# 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:>
Get a list of active keys. Uses XQueryKeymap.
<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:>
Attempts to cast given value to an integer, return the original value if failed or the default if one provided.
<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 pro... |
try:
return int(val)
except (TypeError, ValueError):
if default != 0xDEADBEEF:
return default
return val |
<SYSTEM_TASK:>
Given year, month and day numeric values and a timezone
<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:>
Assemble a date object but if day or month is none set them to 1
<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:>
Only intended for use in getting components, look for tag name of fig-group
<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... |
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:>
Given a beautiful soup tag, look at its parents and return the first
<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:>
Meant for finding the position of fig tags with respect to whether
<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:>
Count previous tags of the same name until it
<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:>
Count sibling ordinal differently depending on if the
<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:>
Strategy is to count the previous supplementary-material tags
<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 i... |
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:>
when a title is required, generate one from the value
<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:>
Quick convert unicode ampersand characters not associated with
<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:>
to extract the doctype details from the file when parsed and return the data
<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... |
<SYSTEM_TASK:>
Helper function to refactor the adding of new tags
<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:>
Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with
<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 s... |
doctype = ElifeDocumentType(qualifiedName)
doctype._identified_mixin_init(publicId, systemId)
if internalSubset:
doctype.internalSubset = internalSubset
return doctype |
<SYSTEM_TASK:>
Due to XML content that will not conform with the strict JSON schema validation rules,
<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, r... |
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:>
this does the work of rewriting elife references json
<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:>
general purpose references json rewriting by matching the id value
<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:>
rewrite elife funding awards
<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:>
Run the linter over the new metadata, comparing to the old.
<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:>
Serialize into JSONable dict, and associated locations data.
<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:>
Add an API to the service.
<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.
:... |
location = get_callsite_location()
api = AcceptableAPI(
self,
name,
url,
introduced_at,
options,
undocumented=undocumented,
deprecated_at=deprecated_at,
title=title,
location=location,
)
... |
<SYSTEM_TASK:>
Add a django API handler to the service.
<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 ... |
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:>
Add a changelog entry for this api.
<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:>
Find the keywords from the set of kwd-group tags
<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:>
return a list of article-id data
<END_TASK>
<USER_TASK:>
Description:
def article_id_list(soup):
"""return a list of article-id data""" |
id_list = []
for article_id_tag in raw_parser.article_id(soup):
id_details = OrderedDict()
set_if_value(id_details, "type", article_id_tag.get("pub-id-type"))
set_if_value(id_details, "value", article_id_tag.text)
set_if_value(id_details, "assigning-authority", article_id_tag.ge... |
<SYSTEM_TASK:>
Find the subject areas from article-categories subject tags
<END_TASK>
<USER_TASK:>
Description:
def subject_area(soup):
"""
Find the subject areas from article-categories subject tags
""" |
subject_area = []
tags = raw_parser.subject_area(soup)
for tag in tags:
subject_area.append(node_text(tag))
return subject_area |
<SYSTEM_TASK:>
Find the subject areas of type display-channel
<END_TASK>
<USER_TASK:>
Description:
def display_channel(soup):
"""
Find the subject areas of type display-channel
""" |
display_channel = []
tags = raw_parser.display_channel(soup)
for tag in tags:
display_channel.append(node_text(tag))
return display_channel |
<SYSTEM_TASK:>
Find the category from subject areas
<END_TASK>
<USER_TASK:>
Description:
def category(soup):
"""
Find the category from subject areas
""" |
category = []
tags = raw_parser.category(soup)
for tag in tags:
category.append(node_text(tag))
return category |
<SYSTEM_TASK:>
Get the year, month and day from child tags
<END_TASK>
<USER_TASK:>
Description:
def ymd(soup):
"""
Get the year, month and day from child tags
""" |
day = node_text(raw_parser.day(soup))
month = node_text(raw_parser.month(soup))
year = node_text(raw_parser.year(soup))
return (day, month, year) |
<SYSTEM_TASK:>
Return the publishing date in struct format
<END_TASK>
<USER_TASK:>
Description:
def pub_date(soup):
"""
Return the publishing date in struct format
pub_date_date, pub_date_day, pub_date_month, pub_date_year, pub_date_timestamp
Default date_type is pub
""" |
pub_date = first(raw_parser.pub_date(soup, date_type="pub"))
if pub_date is None:
pub_date = first(raw_parser.pub_date(soup, date_type="publication"))
if pub_date is None:
return None
(day, month, year) = ymd(pub_date)
return date_struct(year, month, day) |
<SYSTEM_TASK:>
return a list of all the pub dates
<END_TASK>
<USER_TASK:>
Description:
def pub_dates(soup):
"""
return a list of all the pub dates
""" |
pub_dates = []
tags = raw_parser.pub_date(soup)
for tag in tags:
pub_date = OrderedDict()
copy_attribute(tag.attrs, 'publication-format', pub_date)
copy_attribute(tag.attrs, 'date-type', pub_date)
copy_attribute(tag.attrs, 'pub-type', pub_date)
for tag_attr in ["date... |
<SYSTEM_TASK:>
Pub date of type collection will hold a year element for VOR articles
<END_TASK>
<USER_TASK:>
Description:
def collection_year(soup):
"""
Pub date of type collection will hold a year element for VOR articles
""" |
pub_date = first(raw_parser.pub_date(soup, pub_type="collection"))
if not pub_date:
pub_date = first(raw_parser.pub_date(soup, date_type="collection"))
if not pub_date:
return None
year = None
year_tag = raw_parser.year(pub_date)
if year_tag:
year = int(node_text(year_t... |
<SYSTEM_TASK:>
Find the article abstract and format it
<END_TASK>
<USER_TASK:>
Description:
def abstracts(soup):
"""
Find the article abstract and format it
""" |
abstracts = []
abstract_tags = raw_parser.abstract(soup)
for tag in abstract_tags:
abstract = {}
abstract["abstract_type"] = tag.get("abstract-type")
title_tag = raw_parser.title(tag)
if title_tag:
abstract["title"] = node_text(title_tag)
abstract["c... |
<SYSTEM_TASK:>
Look for all object-id of pub-type-id = doi, these are the component DOI tags
<END_TASK>
<USER_TASK:>
Description:
def component_doi(soup):
"""
Look for all object-id of pub-type-id = doi, these are the component DOI tags
""" |
component_doi = []
object_id_tags = raw_parser.object_id(soup, pub_id_type = "doi")
# Get components too for later
component_list = components(soup)
position = 1
for tag in object_id_tags:
component_object = {}
component_object["doi"] = doi_uri_to_doi(tag.text)
compo... |
<SYSTEM_TASK:>
Used in media and graphics to extract data from their parent tags
<END_TASK>
<USER_TASK:>
Description:
def tag_details(tag, nodenames):
"""
Used in media and graphics to extract data from their parent tags
""" |
details = {}
details['type'] = tag.name
details['ordinal'] = tag_ordinal(tag)
# Ordinal value
if tag_details_sibling_ordinal(tag):
details['sibling_ordinal'] = tag_details_sibling_ordinal(tag)
# Asset name
if tag_details_asset(tag):
details['asset'] = tag_details_asset(ta... |
<SYSTEM_TASK:>
Given a contrib tag, look for an email tag, and
<END_TASK>
<USER_TASK:>
Description:
def contrib_email(contrib_tag):
"""
Given a contrib tag, look for an email tag, and
only return the value if it is not inside an aff tag
""" |
email = []
for email_tag in extract_nodes(contrib_tag, "email"):
if email_tag.parent.name != "aff":
email.append(email_tag.text)
return email if len(email) > 0 else None |
<SYSTEM_TASK:>
Given a contrib tag, look for an phone tag
<END_TASK>
<USER_TASK:>
Description:
def contrib_phone(contrib_tag):
"""
Given a contrib tag, look for an phone tag
""" |
phone = None
if raw_parser.phone(contrib_tag):
phone = first(raw_parser.phone(contrib_tag)).text
return phone |
<SYSTEM_TASK:>
Given a contrib tag, look for an aff tag directly inside it
<END_TASK>
<USER_TASK:>
Description:
def contrib_inline_aff(contrib_tag):
"""
Given a contrib tag, look for an aff tag directly inside it
""" |
aff_tags = []
for child_tag in contrib_tag:
if child_tag and child_tag.name and child_tag.name == "aff":
aff_tags.append(child_tag)
return aff_tags |
<SYSTEM_TASK:>
Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag
<END_TASK>
<USER_TASK:>
Description:
def contrib_xref(contrib_tag, ref_type):
"""
Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag
""" |
aff_tags = []
for child_tag in contrib_tag:
if (child_tag and child_tag.name and child_tag.name == "xref"
and child_tag.get('ref-type') and child_tag.get('ref-type') == ref_type):
aff_tags.append(child_tag)
return aff_tags |
<SYSTEM_TASK:>
Non-byline authors for group author members
<END_TASK>
<USER_TASK:>
Description:
def authors_non_byline(soup, detail="full"):
"""Non-byline authors for group author members""" |
# Get a filtered list of contributors, in order to get their group-author-id
contrib_type = "author non-byline"
contributors_ = contributors(soup, detail)
non_byline_authors = [author for author in contributors_ if author.get('type', None) == contrib_type]
# Then renumber their position attribute
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.