_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275100 | wx_Menu.Enable | test | def Enable(self, value):
"enable or disable all menu items"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
it.Enable(value) | python | {
"resource": ""
} |
q275101 | wx_Menu.IsEnabled | test | def IsEnabled(self, *args, **kwargs):
"check if all menu items are enabled"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
if not it.IsEnabled():
return False
return True | python | {
"resource": ""
} |
q275102 | wx_MenuBar.Enable | test | def Enable(self, value):
"enable or disable all top menus"
for i in range(self.GetMenuCount()):
self.EnableTop(i, value) | python | {
"resource": ""
} |
q275103 | wx_MenuBar.IsEnabled | test | def IsEnabled(self, *args, **kwargs):
"check if all top menus are enabled"
for i in range(self.GetMenuCount()):
if not self.IsEnabledTop(i):
return False
return True | python | {
"resource": ""
} |
q275104 | wx_MenuBar.RemoveItem | test | def RemoveItem(self, menu):
"Helper method to remove a menu avoiding using its position"
menus = self.GetMenus() # get the list of (menu, title)
menus = [submenu for submenu in menus if submenu[0] != menu]
self.SetMenus(menus) | python | {
"resource": ""
} |
q275105 | HTMLForm.submit | test | def submit(self, btn=None):
"Process form submission"
data = self.build_data_set()
if btn and btn.name:
data[btn.name] = btn.name
evt = FormSubmitEvent(self, data)
self.container.ProcessEvent(evt) | python | {
"resource": ""
} |
q275106 | FormTagHandler.setObjectTag | test | def setObjectTag(self, object, tag):
""" Add a tag attribute to the wx window """
object._attributes = {}
object._name = tag.GetName().lower()
for name in self.attributes:
object._attributes["_%s" % name] = tag.GetParam(name)
if object._attributes["_%s" % name] == "":
object._attributes["_%s" % name] = None | python | {
"resource": ""
} |
q275107 | autosummary_table_visit_html | test | def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if isinstance(subnode, nodes.Text):
new_text = unicode(subnode.astext())
new_text = new_text.replace(u" ", u"\u00a0")
par[j] = nodes.Text(new_text)
except IndexError:
pass | python | {
"resource": ""
} |
q275108 | get_documenter | test | def get_documenter(obj, parent):
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import AutoDirective, DataDocumenter, \
ModuleDocumenter
if inspect.ismodule(obj):
# ModuleDocumenter.can_document_member always returns False
return ModuleDocumenter
# Construct a fake documenter for *parent*
if parent is not None:
parent_doc_cls = get_documenter(parent, None)
else:
parent_doc_cls = ModuleDocumenter
if hasattr(parent, '__name__'):
parent_doc = parent_doc_cls(FakeDirective(), parent.__name__)
else:
parent_doc = parent_doc_cls(FakeDirective(), "")
# Get the corrent documenter class for *obj*
classes = [cls for cls in AutoDirective._registry.values()
if cls.can_document_member(obj, '', False, parent_doc)]
if classes:
classes.sort(key=lambda cls: cls.priority)
return classes[-1]
else:
return DataDocumenter | python | {
"resource": ""
} |
q275109 | mangle_signature | test | def mangle_signature(sig, max_chars=30):
"""Reformat a function signature to a more compact form."""
s = re.sub(r"^\((.*)\)$", r"\1", sig).strip()
# Strip strings (which can contain things that confuse the code below)
s = re.sub(r"\\\\", "", s)
s = re.sub(r"\\'", "", s)
s = re.sub(r"'[^']*'", "", s)
# Parse the signature to arguments + options
args = []
opts = []
opt_re = re.compile(r"^(.*, |)([a-zA-Z0-9_*]+)=")
while s:
m = opt_re.search(s)
if not m:
# The rest are arguments
args = s.split(', ')
break
opts.insert(0, m.group(2))
s = m.group(1)[:-2]
# Produce a more compact signature
sig = limited_join(", ", args, max_chars=max_chars-2)
if opts:
if not sig:
sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars-4)
elif len(sig) < max_chars - 4 - 2 - 3:
sig += "[, %s]" % limited_join(", ", opts,
max_chars=max_chars-len(sig)-4-2)
return u"(%s)" % sig | python | {
"resource": ""
} |
q275110 | _import_by_name | test | def _import_by_name(name):
"""Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
__import__(modname)
mod = sys.modules[modname]
return getattr(mod, name_parts[-1]), mod
except (ImportError, IndexError, AttributeError):
pass
# ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ...
last_j = 0
modname = None
for j in reversed(range(1, len(name_parts)+1)):
last_j = j
modname = '.'.join(name_parts[:j])
try:
__import__(modname)
except:# ImportError:
continue
if modname in sys.modules:
break
if last_j < len(name_parts):
parent = None
obj = sys.modules[modname]
for obj_name in name_parts[last_j:]:
parent = obj
obj = getattr(obj, obj_name)
return obj, parent
else:
return sys.modules[modname], None
except (ValueError, ImportError, AttributeError, KeyError), e:
raise ImportError(*e.args) | python | {
"resource": ""
} |
q275111 | autolink_role | test | def autolink_role(typ, rawtext, etext, lineno, inliner,
options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('obj')(
'obj', rawtext, etext, lineno, inliner, options, content)
pnode = r[0][0]
prefixes = get_import_prefixes_from_env(env)
try:
name, obj, parent = import_by_name(pnode['reftarget'], prefixes)
except ImportError:
content = pnode[0]
r[0][0] = nodes.emphasis(rawtext, content[0].astext(),
classes=content['classes'])
return r | python | {
"resource": ""
} |
q275112 | alert | test | def alert(message, title="", parent=None, scrolled=False, icon="exclamation"):
"Show a simple pop-up modal dialog"
if not scrolled:
icons = {'exclamation': wx.ICON_EXCLAMATION, 'error': wx.ICON_ERROR,
'question': wx.ICON_QUESTION, 'info': wx.ICON_INFORMATION}
style = wx.OK | icons[icon]
result = dialogs.messageDialog(parent, message, title, style)
else:
result = dialogs.scrolledMessageDialog(parent, message, title) | python | {
"resource": ""
} |
q275113 | prompt | test | def prompt(message="", title="", default="", multiline=False, password=None,
parent=None):
"Modal dialog asking for an input, returns string or None if cancelled"
if password:
style = wx.TE_PASSWORD | wx.OK | wx.CANCEL
result = dialogs.textEntryDialog(parent, message, title, default, style)
elif multiline:
style = wx.TE_MULTILINE | wx.OK | wx.CANCEL
result = dialogs.textEntryDialog(parent, message, title, default, style)
# workaround for Mac OS X
result.text = '\n'.join(result.text.splitlines())
else:
result = dialogs.textEntryDialog(parent, message, title, default)
if result.accepted:
return result.text | python | {
"resource": ""
} |
q275114 | select_font | test | def select_font(message="", title="", font=None, parent=None):
"Show a dialog to select a font"
if font is not None:
wx_font = font._get_wx_font() # use as default
else:
wx_font = None
font = Font() # create an empty font
result = dialogs.fontDialog(parent, font=wx_font)
if result.accepted:
font_data = result.fontData
result.color = result.fontData.GetColour().Get()
wx_font = result.fontData.GetChosenFont()
font.set_wx_font(wx_font)
wx_font = None
return font | python | {
"resource": ""
} |
q275115 | select_color | test | def select_color(message="", title="", color=None, parent=None):
"Show a dialog to pick a color"
result = dialogs.colorDialog(parent, color=color)
return result.accepted and result.color | python | {
"resource": ""
} |
q275116 | choose_directory | test | def choose_directory(message='Choose a directory', path="", parent=None):
"Show a dialog to choose a directory"
result = dialogs.directoryDialog(parent, message, path)
return result.path | python | {
"resource": ""
} |
q275117 | find | test | def find(default='', whole_words=0, case_sensitive=0, parent=None):
"Shows a find text dialog"
result = dialogs.findDialog(parent, default, whole_words, case_sensitive)
return {'text': result.searchText, 'whole_words': result.wholeWordsOnly,
'case_sensitive': result.caseSensitive} | python | {
"resource": ""
} |
q275118 | TreeItem.set_has_children | test | def set_has_children(self, has_children=True):
"Force appearance of the button next to the item"
# This is useful to allow the user to expand the items which don't have
# any children now, but instead adding them only when needed, thus
# minimizing memory usage and loading time.
self._tree_model._tree_view.wx_obj.SetItemHasChildren(self.wx_item,
has_children) | python | {
"resource": ""
} |
q275119 | Window._set_icon | test | def _set_icon(self, icon=None):
"""Set icon based on resource values"""
if icon is not None:
try:
wx_icon = wx.Icon(icon, wx.BITMAP_TYPE_ICO)
self.wx_obj.SetIcon(wx_icon)
except:
pass | python | {
"resource": ""
} |
q275120 | Window.show | test | def show(self, value=True, modal=None):
"Display or hide the window, optionally disabling all other windows"
self.wx_obj.Show(value)
if modal:
# disable all top level windows of this application (MakeModal)
disabler = wx.WindowDisabler(self.wx_obj)
# create an event loop to stop execution
eventloop = wx.EventLoop()
def on_close_modal(evt):
evt.Skip()
eventloop.Exit()
self.wx_obj.Bind(wx.EVT_CLOSE, on_close_modal)
# start the event loop to wait user interaction
eventloop.Run()
# reenable the windows disabled and return control to the caller
del disabler | python | {
"resource": ""
} |
q275121 | parse | test | def parse(filename=""):
"Open, read and eval the resource from the source file"
# use the provided resource file:
s = open(filename).read()
##s.decode("latin1").encode("utf8")
import datetime, decimal
rsrc = eval(s)
return rsrc | python | {
"resource": ""
} |
q275122 | save | test | def save(filename, rsrc):
"Save the resource to the source file"
s = pprint.pformat(rsrc)
## s = s.encode("utf8")
open(filename, "w").write(s) | python | {
"resource": ""
} |
q275123 | build_window | test | def build_window(res):
"Create a gui2py window based on the python resource"
# windows specs (parameters)
kwargs = dict(res.items())
wintype = kwargs.pop('type')
menubar = kwargs.pop('menubar', None)
components = kwargs.pop('components')
panel = kwargs.pop('panel', {})
from gui import registry
import gui
winclass = registry.WINDOWS[wintype]
win = winclass(**kwargs)
# add an implicit panel by default (as pythoncard had)
if False and panel is not None:
panel['name'] = 'panel'
p = gui.Panel(win, **panel)
else:
p = win
if components:
for comp in components:
build_component(comp, parent=p)
if menubar:
mb = gui.MenuBar(name="menu", parent=win)
for menu in menubar:
build_component(menu, parent=mb)
return win | python | {
"resource": ""
} |
q275124 | build_component | test | def build_component(res, parent=None):
"Create a gui2py control based on the python resource"
# control specs (parameters)
kwargs = dict(res.items())
comtype = kwargs.pop('type')
if 'components' in res:
components = kwargs.pop('components')
elif comtype == 'Menu' and 'items' in res:
components = kwargs.pop('items')
else:
components = []
from gui import registry
if comtype in registry.CONTROLS:
comclass = registry.CONTROLS[comtype]
elif comtype in registry.MENU:
comclass = registry.MENU[comtype]
elif comtype in registry.MISC:
comclass = registry.MISC[comtype]
else:
raise RuntimeError("%s not in registry" % comtype)
# Instantiate the GUI object
com = comclass(parent=parent, **kwargs)
for comp in components:
build_component(comp, parent=com)
return com | python | {
"resource": ""
} |
q275125 | connect | test | def connect(component, controller=None):
"Associate event handlers "
# get the controller functions and names (module or class)
if not controller or isinstance(controller, dict):
if not controller:
controller = util.get_caller_module_dict()
controller_name = controller['__name__']
controller_dict = controller
else:
controller_name = controller.__class__.__name__
controller_dict = dict([(k, getattr(controller, k)) for k
in dir(controller) if k.startswith("on_")])
for fn in [n for n in controller_dict if n.startswith("on_")]:
# on_mypanel_mybutton_click -> ['mypanel']['mybutton'].onclick
names = fn.split("_")
event_name = names.pop(0) + names.pop(-1)
# find the control
obj = component
for name in names:
try:
obj = obj[name]
except KeyError:
obj = None
break
if not obj:
from .component import COMPONENTS
for key, obj in COMPONENTS.items():
if obj.name == name:
print "WARNING: %s should be %s" % (name, key.replace(".", "_"))
break
else:
raise NameError("'%s' component not found (%s.%s)" %
(name, controller_name, fn))
# check if the control supports the event:
if event_name in PYTHONCARD_EVENT_MAP:
new_name = PYTHONCARD_EVENT_MAP[event_name]
print "WARNING: %s should be %s (%s)" % (event_name, new_name, fn)
event_name = new_name
if not hasattr(obj, event_name):
raise NameError("'%s' event not valid (%s.%s)" %
(event_name, controller_name, fn))
# bind the event (assign the method to the on... spec)
setattr(obj, event_name, controller_dict[fn]) | python | {
"resource": ""
} |
q275126 | PythonCardWrapper.convert | test | def convert(self, name):
"translate gui2py attribute name from pythoncard legacy code"
new_name = PYTHONCARD_PROPERTY_MAP.get(name)
if new_name:
print "WARNING: property %s should be %s (%s)" % (name, new_name, self.obj.name)
return new_name
else:
return name | python | {
"resource": ""
} |
q275127 | set_data | test | def set_data(data):
"Write content to the clipboard, data can be either a string or a bitmap"
try:
if wx.TheClipboard.Open():
if isinstance(data, (str, unicode)):
do = wx.TextDataObject()
do.SetText(data)
wx.TheClipboard.SetData(do)
elif isinstance(data, wx.Bitmap):
do = wx.BitmapDataObject()
do.SetBitmap(data)
wx.TheClipboard.SetData(do)
wx.TheClipboard.Close()
except:
pass | python | {
"resource": ""
} |
q275128 | find_autosummary_in_docstring | test | def find_autosummary_in_docstring(name, module=None, filename=None):
"""Find out what items are documented in the given object's docstring.
See `find_autosummary_in_lines`.
"""
try:
real_name, obj, parent = import_by_name(name)
lines = pydoc.getdoc(obj).splitlines()
return find_autosummary_in_lines(lines, module=name, filename=filename)
except AttributeError:
pass
except ImportError, e:
print "Failed to import '%s': %s" % (name, e)
return [] | python | {
"resource": ""
} |
q275129 | InspectorPanel.load_object | test | def load_object(self, obj=None):
"Add the object and all their childs"
# if not obj is given, do a full reload using the current root
if obj:
self.root_obj = obj
else:
obj = self.root_obj
self.tree.DeleteAllItems()
self.root = self.tree.AddRoot("application")
self.tree.SetItemText(self.root, "App", 1)
self.tree.SetItemText(self.root, "col 2 root", 2)
#self.tree.SetItemImage(self.root, fldridx, which = wx.TreeItemIcon_Normal)
#self.tree.SetItemImage(self.root, fldropenidx, which = wx.TreeItemIcon_Expanded)
self.build_tree(self.root, obj)
self.tree.Expand(self.root) | python | {
"resource": ""
} |
q275130 | InspectorPanel.inspect | test | def inspect(self, obj, context_menu=False, edit_prop=False, mouse_pos=None):
"Select the object and show its properties"
child = self.tree.FindItem(self.root, obj.name)
if DEBUG: print "inspect child", child
if child:
self.tree.ScrollTo(child)
self.tree.SetCurrentItem(child)
self.tree.SelectItem(child)
child.Selected = True
self.activate_item(child, edit_prop)
if context_menu:
self.show_context_menu(child, mouse_pos) | python | {
"resource": ""
} |
q275131 | InspectorPanel.activate_item | test | def activate_item(self, child, edit_prop=False, select=False):
"load the selected item in the property editor"
d = self.tree.GetItemData(child)
if d:
o = d.GetData()
self.selected_obj = o
callback = lambda o=o, **kwargs: self.update(o, **kwargs)
self.propeditor.load_object(o, callback)
if edit_prop:
wx.CallAfter(self.propeditor.edit)
if select and self.designer:
self.designer.select(o)
else:
self.selected_obj = None | python | {
"resource": ""
} |
q275132 | InspectorPanel.update | test | def update(self, obj, **kwargs):
"Update the tree item when the object name changes"
# search for the old name:
child = self.tree.FindItem(self.root, kwargs['name'])
if DEBUG: print "update child", child, kwargs
if child:
self.tree.ScrollTo(child)
self.tree.SetCurrentItem(child)
self.tree.SelectItem(child)
child.Selected = True
# update the new name
self.tree.SetItemText(child, obj.name, 0) | python | {
"resource": ""
} |
q275133 | InspectorPanel.show_context_menu | test | def show_context_menu(self, item, mouse_pos=None):
"Open a popup menu with options regarding the selected object"
if item:
d = self.tree.GetItemData(item)
if d:
obj = d.GetData()
if obj:
# highligh and store the selected object:
self.highlight(obj.wx_obj)
self.obj = obj
# make the context menu
menu = wx.Menu()
id_del, id_dup, id_raise, id_lower = [wx.NewId() for i
in range(4)]
menu.Append(id_del, "Delete")
menu.Append(id_dup, "Duplicate")
menu.Append(id_raise, "Bring to Front")
menu.Append(id_lower, "Send to Back")
# make submenu!
sm = wx.Menu()
for ctrl in sorted(obj._meta.valid_children,
key=lambda c:
registry.ALL.index(c._meta.name)):
new_id = wx.NewId()
sm.Append(new_id, ctrl._meta.name)
self.Bind(wx.EVT_MENU,
lambda evt, ctrl=ctrl: self.add_child(ctrl, mouse_pos),
id=new_id)
menu.AppendMenu(wx.NewId(), "Add child", sm)
self.Bind(wx.EVT_MENU, self.delete, id=id_del)
self.Bind(wx.EVT_MENU, self.duplicate, id=id_dup)
self.Bind(wx.EVT_MENU, self.bring_to_front, id=id_raise)
self.Bind(wx.EVT_MENU, self.send_to_back, id=id_lower)
self.PopupMenu(menu)
menu.Destroy()
self.load_object(self.root_obj) | python | {
"resource": ""
} |
q275134 | HyperlinkedSorlImageField.to_representation | test | def to_representation(self, value):
"""
Perform the actual serialization.
Args:
value: the image to transform
Returns:
a url pointing at a scaled and cached image
"""
if not value:
return None
image = get_thumbnail(value, self.geometry_string, **self.options)
try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except:
try:
return super(HyperlinkedSorlImageField, self).to_representation(image)
except AttributeError: # NOQA
return super(HyperlinkedSorlImageField, self).to_native(image.url) # NOQA | python | {
"resource": ""
} |
q275135 | SelectorFactory.expression_filter | test | def expression_filter(self, name, **kwargs):
"""
Returns a decorator function for adding an expression filter.
Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.
Returns:
Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator
function for adding an expression filter.
"""
def decorator(func):
self.filters[name] = ExpressionFilter(name, func, **kwargs)
return decorator | python | {
"resource": ""
} |
q275136 | SelectorFactory.node_filter | test | def node_filter(self, name, **kwargs):
"""
Returns a decorator function for adding a node filter.
Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.
Returns:
Callable[[Callable[[Element, Any], bool]]]: A decorator function for adding a node
filter.
"""
def decorator(func):
self.filters[name] = NodeFilter(name, func, **kwargs)
return decorator | python | {
"resource": ""
} |
q275137 | SessionMatchersMixin.assert_current_path | test | def assert_current_path(self, path, **kwargs):
"""
Asserts that the page has the given path. By default this will compare against the
path+query portion of the full URL.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = CurrentPathQuery(path, **kwargs)
@self.document.synchronize
def assert_current_path():
if not query.resolves_for(self):
raise ExpectationNotMet(query.failure_message)
assert_current_path()
return True | python | {
"resource": ""
} |
q275138 | SessionMatchersMixin.assert_no_current_path | test | def assert_no_current_path(self, path, **kwargs):
"""
Asserts that the page doesn't have the given path.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = CurrentPathQuery(path, **kwargs)
@self.document.synchronize
def assert_no_current_path():
if query.resolves_for(self):
raise ExpectationNotMet(query.negative_failure_message)
assert_no_current_path()
return True | python | {
"resource": ""
} |
q275139 | SessionMatchersMixin.has_current_path | test | def has_current_path(self, path, **kwargs):
"""
Checks if the page has the given path.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
bool: Whether it matches.
"""
try:
return self.assert_current_path(path, **kwargs)
except ExpectationNotMet:
return False | python | {
"resource": ""
} |
q275140 | SessionMatchersMixin.has_no_current_path | test | def has_no_current_path(self, path, **kwargs):
"""
Checks if the page doesn't have the given path.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
bool: Whether it doesn't match.
"""
try:
return self.assert_no_current_path(path, **kwargs)
except ExpectationNotMet:
return False | python | {
"resource": ""
} |
q275141 | Element.select_option | test | def select_option(self):
""" Select this node if it is an option element inside a select tag. """
if self.disabled:
warn("Attempt to select disabled option: {}".format(self.value or self.text))
self.base.select_option() | python | {
"resource": ""
} |
q275142 | ExpressionFilter.apply_filter | test | def apply_filter(self, expr, value):
"""
Returns the given expression filtered by the given value.
Args:
expr (xpath.expression.AbstractExpression): The expression to filter.
value (object): The desired value with which the expression should be filtered.
Returns:
xpath.expression.AbstractExpression: The filtered expression.
"""
if self.skip(value):
return expr
if not self._valid_value(value):
msg = "Invalid value {value} passed to filter {name} - ".format(
value=repr(value),
name=self.name)
if self.default is not None:
warn(msg + "defaulting to {}".format(self.default))
value = self.default
else:
warn(msg + "skipping")
return expr
return self.func(expr, value) | python | {
"resource": ""
} |
q275143 | get_browser | test | def get_browser(browser_name, capabilities=None, **options):
"""
Returns an instance of the given browser with the given capabilities.
Args:
browser_name (str): The name of the desired browser.
capabilities (Dict[str, str | bool], optional): The desired capabilities of the browser.
Defaults to None.
options: Arbitrary keyword arguments for the browser-specific subclass of
:class:`webdriver.Remote`.
Returns:
WebDriver: An instance of the desired browser.
"""
if browser_name == "chrome":
return webdriver.Chrome(desired_capabilities=capabilities, **options)
if browser_name == "edge":
return webdriver.Edge(capabilities=capabilities, **options)
if browser_name in ["ff", "firefox"]:
return webdriver.Firefox(capabilities=capabilities, **options)
if browser_name in ["ie", "internet_explorer"]:
return webdriver.Ie(capabilities=capabilities, **options)
if browser_name == "phantomjs":
return webdriver.PhantomJS(desired_capabilities=capabilities, **options)
if browser_name == "remote":
return webdriver.Remote(desired_capabilities=capabilities, **options)
if browser_name == "safari":
return webdriver.Safari(desired_capabilities=capabilities, **options)
raise ValueError("unsupported browser: {}".format(repr(browser_name))) | python | {
"resource": ""
} |
q275144 | SelectorQuery.xpath | test | def xpath(self, exact=None):
"""
Returns the XPath query for this selector.
Args:
exact (bool, optional): Whether to exactly match text.
Returns:
str: The XPath query for this selector.
"""
exact = exact if exact is not None else self.exact
if isinstance(self.expression, AbstractExpression):
expression = self._apply_expression_filters(self.expression)
return to_xpath(expression, exact=exact)
else:
return str_(self.expression) | python | {
"resource": ""
} |
q275145 | SelectorQuery.matches_filters | test | def matches_filters(self, node):
"""
Returns whether the given node matches all filters.
Args:
node (Element): The node to evaluate.
Returns:
bool: Whether the given node matches.
"""
visible = self.visible
if self.options["text"]:
if isregex(self.options["text"]):
regex = self.options["text"]
elif self.exact_text is True:
regex = re.compile(r"\A{}\Z".format(re.escape(self.options["text"])))
else:
regex = toregex(self.options["text"])
text = normalize_text(
node.all_text if visible == "all" else node.visible_text)
if not regex.search(text):
return False
if isinstance(self.exact_text, (bytes_, str_)):
regex = re.compile(r"\A{}\Z".format(re.escape(self.exact_text)))
text = normalize_text(
node.all_text if visible == "all" else node.visible_text)
if not regex.search(text):
return False
if visible == "visible":
if not node.visible:
return False
elif visible == "hidden":
if node.visible:
return False
for name, node_filter in iter(self._node_filters.items()):
if name in self.filter_options:
if not node_filter.matches(node, self.filter_options[name]):
return False
elif node_filter.has_default:
if not node_filter.matches(node, node_filter.default):
return False
if self.options["filter"] and not self.options["filter"](node):
return False
return True | python | {
"resource": ""
} |
q275146 | Session.switch_to_frame | test | def switch_to_frame(self, frame):
"""
Switch to the given frame.
If you use this method you are responsible for making sure you switch back to the parent
frame when done in the frame changed to. :meth:`frame` is preferred over this method and
should be used when possible. May not be supported by all drivers.
Args:
frame (Element | str): The iframe/frame element to switch to.
"""
if isinstance(frame, Element):
self.driver.switch_to_frame(frame)
self._scopes.append("frame")
elif frame == "parent":
if self._scopes[-1] != "frame":
raise ScopeError("`switch_to_frame(\"parent\")` cannot be called "
"from inside a descendant frame's `scope` context.")
self._scopes.pop()
self.driver.switch_to_frame("parent")
elif frame == "top":
if "frame" in self._scopes:
idx = self._scopes.index("frame")
if any([scope not in ["frame", None] for scope in self._scopes[idx:]]):
raise ScopeError("`switch_to_frame(\"top\")` cannot be called "
"from inside a descendant frame's `scope` context.")
self._scopes = self._scopes[:idx]
self.driver.switch_to_frame("top")
else:
raise ValueError(
"You must provide a frame element, \"parent\", or \"top\" "
"when calling switch_to_frame") | python | {
"resource": ""
} |
q275147 | Session.accept_alert | test | def accept_alert(self, text=None, wait=None):
"""
Execute the wrapped code, accepting an alert.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
Raises:
ModalNotFound: If a modal dialog hasn't been found.
"""
wait = wait or capybara.default_max_wait_time
with self.driver.accept_modal("alert", text=text, wait=wait):
yield | python | {
"resource": ""
} |
q275148 | Session.accept_confirm | test | def accept_confirm(self, text=None, wait=None):
"""
Execute the wrapped code, accepting a confirm.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
Raises:
ModalNotFound: If a modal dialog hasn't been found.
"""
with self.driver.accept_modal("confirm", text=text, wait=wait):
yield | python | {
"resource": ""
} |
q275149 | Session.dismiss_confirm | test | def dismiss_confirm(self, text=None, wait=None):
"""
Execute the wrapped code, dismissing a confirm.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
Raises:
ModalNotFound: If a modal dialog hasn't been found.
"""
with self.driver.dismiss_modal("confirm", text=text, wait=wait):
yield | python | {
"resource": ""
} |
q275150 | Session.accept_prompt | test | def accept_prompt(self, text=None, response=None, wait=None):
"""
Execute the wrapped code, accepting a prompt, optionally responding to the prompt.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
response (str, optional): Response to provide to the prompt.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
Raises:
ModalNotFound: If a modal dialog hasn't been found.
"""
with self.driver.accept_modal("prompt", text=text, response=response, wait=wait):
yield | python | {
"resource": ""
} |
q275151 | Session.dismiss_prompt | test | def dismiss_prompt(self, text=None, wait=None):
"""
Execute the wrapped code, dismissing a prompt.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
Raises:
ModalNotFound: If a modal dialog hasn't been found.
"""
with self.driver.dismiss_modal("prompt", text=text, wait=wait):
yield | python | {
"resource": ""
} |
q275152 | Session.save_page | test | def save_page(self, path=None):
"""
Save a snapshot of the page.
If invoked without arguments, it will save a file to :data:`capybara.save_path` and the
file will be given a randomly generated filename. If invoked with a relative path, the path
will be relative to :data:`capybara.save_path`.
Args:
path (str, optional): The path to where it should be saved.
Returns:
str: The path to which the file was saved.
"""
path = _prepare_path(path, "html")
with open(path, "wb") as f:
f.write(encode_string(self.body))
return path | python | {
"resource": ""
} |
q275153 | Session.save_screenshot | test | def save_screenshot(self, path=None, **kwargs):
"""
Save a screenshot of the page.
If invoked without arguments, it will save a file to :data:`capybara.save_path` and the
file will be given a randomly generated filename. If invoked with a relative path, the path
will be relative to :data:`capybara.save_path`.
Args:
path (str, optional): The path to where it should be saved.
**kwargs: Arbitrary keywords arguments for the driver.
Returns:
str: The path to which the file was saved.
"""
path = _prepare_path(path, "png")
self.driver.save_screenshot(path, **kwargs)
return path | python | {
"resource": ""
} |
q275154 | Session.raise_server_error | test | def raise_server_error(self):
""" Raise errors encountered by the server. """
if self.server and self.server.error:
try:
if capybara.raise_server_errors:
raise self.server.error
finally:
self.server.reset_error() | python | {
"resource": ""
} |
q275155 | NodeFilter.matches | test | def matches(self, node, value):
"""
Returns whether the given node matches the filter rule with the given value.
Args:
node (Element): The node to filter.
value (object): The desired value with which the node should be evaluated.
Returns:
bool: Whether the given node matches.
"""
if self.skip(value):
return True
if not self._valid_value(value):
msg = "Invalid value {value} passed to filter {name} - ".format(
value=repr(value),
name=self.name)
if self.default is not None:
warn(msg + "defaulting to {}".format(self.default))
value = self.default
else:
warn(msg + "skipping")
return True
return self.func(node, value) | python | {
"resource": ""
} |
q275156 | MatchersMixin.has_checked_field | test | def has_checked_field(self, locator, **kwargs):
"""
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently checked.
Args:
locator (str): The label, name, or id of a checked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
bool: Whether it exists.
"""
kwargs["checked"] = True
return self.has_selector("field", locator, **kwargs) | python | {
"resource": ""
} |
q275157 | MatchersMixin.has_no_checked_field | test | def has_no_checked_field(self, locator, **kwargs):
"""
Checks if the page or current node has no radio button or checkbox with the given label,
value, or id that is currently checked.
Args:
locator (str): The label, name, or id of a checked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
bool: Whether it doesn't exist.
"""
kwargs["checked"] = True
return self.has_no_selector("field", locator, **kwargs) | python | {
"resource": ""
} |
q275158 | MatchersMixin.has_unchecked_field | test | def has_unchecked_field(self, locator, **kwargs):
"""
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
bool: Whether it exists.
"""
kwargs["checked"] = False
return self.has_selector("field", locator, **kwargs) | python | {
"resource": ""
} |
q275159 | MatchersMixin.has_no_unchecked_field | test | def has_no_unchecked_field(self, locator, **kwargs):
"""
Checks if the page or current node has no radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
bool: Whether it doesn't exist.
"""
kwargs["checked"] = False
return self.has_no_selector("field", locator, **kwargs) | python | {
"resource": ""
} |
q275160 | MatchersMixin.assert_text | test | def assert_text(self, *args, **kwargs):
"""
Asserts that the page or current node has the given text content, ignoring any HTML tags.
Args:
*args: Variable length argument list for :class:`TextQuery`.
**kwargs: Arbitrary keyword arguments for :class:`TextQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TextQuery(*args, **kwargs)
@self.synchronize(wait=query.wait)
def assert_text():
count = query.resolve_for(self)
if not (matches_count(count, query.options) and
(count > 0 or expects_none(query.options))):
raise ExpectationNotMet(query.failure_message)
return True
return assert_text() | python | {
"resource": ""
} |
q275161 | MatchersMixin.assert_no_text | test | def assert_no_text(self, *args, **kwargs):
"""
Asserts that the page or current node doesn't have the given text content, ignoring any
HTML tags.
Args:
*args: Variable length argument list for :class:`TextQuery`.
**kwargs: Arbitrary keyword arguments for :class:`TextQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TextQuery(*args, **kwargs)
@self.synchronize(wait=query.wait)
def assert_no_text():
count = query.resolve_for(self)
if matches_count(count, query.options) and (
count > 0 or expects_none(query.options)):
raise ExpectationNotMet(query.negative_failure_message)
return True
return assert_no_text() | python | {
"resource": ""
} |
q275162 | DocumentMatchersMixin.assert_title | test | def assert_title(self, title, **kwargs):
"""
Asserts that the page has the given title.
Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TitleQuery(title, **kwargs)
@self.synchronize(wait=query.wait)
def assert_title():
if not query.resolves_for(self):
raise ExpectationNotMet(query.failure_message)
return True
return assert_title() | python | {
"resource": ""
} |
q275163 | DocumentMatchersMixin.assert_no_title | test | def assert_no_title(self, title, **kwargs):
"""
Asserts that the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TitleQuery(title, **kwargs)
@self.synchronize(wait=query.wait)
def assert_no_title():
if query.resolves_for(self):
raise ExpectationNotMet(query.negative_failure_message)
return True
return assert_no_title() | python | {
"resource": ""
} |
q275164 | DocumentMatchersMixin.has_title | test | def has_title(self, title, **kwargs):
"""
Checks if the page has the given title.
Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whether it matches.
"""
try:
self.assert_title(title, **kwargs)
return True
except ExpectationNotMet:
return False | python | {
"resource": ""
} |
q275165 | DocumentMatchersMixin.has_no_title | test | def has_no_title(self, title, **kwargs):
"""
Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whether it doesn't match.
"""
try:
self.assert_no_title(title, **kwargs)
return True
except ExpectationNotMet:
return False | python | {
"resource": ""
} |
q275166 | FindersMixin.find_all | test | def find_all(self, *args, **kwargs):
"""
Find all elements on the page matching the given selector and options.
Both XPath and CSS expressions are supported, but Capybara does not try to automatically
distinguish between them. The following statements are equivalent::
page.find_all("css", "a#person_123")
page.find_all("xpath", "//a[@id='person_123']")
If the type of selector is left out, Capybara uses :data:`capybara.default_selector`. It's
set to ``"css"`` by default. ::
page.find_all("a#person_123")
capybara.default_selector = "xpath"
page.find_all("//a[@id='person_123']")
The set of found elements can further be restricted by specifying options. It's possible to
select elements by their text or visibility::
page.find_all("a", text="Home")
page.find_all("#menu li", visible=True)
By default if no elements are found, an empty list is returned; however, expectations can be
set on the number of elements to be found which will trigger Capybara's waiting behavior for
the expectations to match. The expectations can be set using::
page.assert_selector("p#foo", count=4)
page.assert_selector("p#foo", maximum=10)
page.assert_selector("p#foo", minimum=1)
page.assert_selector("p#foo", between=range(1, 11))
See :func:`capybara.result.Result.matches_count` for additional information about count
matching.
Args:
*args: Variable length argument list for :class:`SelectorQuery`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
Result: A collection of found elements.
Raises:
ExpectationNotMet: The matched results did not meet the expected criteria.
"""
query = SelectorQuery(*args, **kwargs)
@self.synchronize(wait=query.wait)
def find_all():
result = query.resolve_for(self)
if not result.matches_count:
raise ExpectationNotMet(result.failure_message)
return result
return find_all() | python | {
"resource": ""
} |
q275167 | FindersMixin.find_first | test | def find_first(self, *args, **kwargs):
"""
Find the first element on the page matching the given selector and options, or None if no
element matches.
By default, no waiting behavior occurs. However, if ``capybara.wait_on_first_by_default``
is set to true, it will trigger Capybara's waiting behavior for a minimum of 1 matching
element to be found.
Args:
*args: Variable length argument list for :class:`SelectorQuery`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
Element: The found element or None.
"""
if capybara.wait_on_first_by_default:
kwargs.setdefault("minimum", 1)
try:
result = self.find_all(*args, **kwargs)
return result[0] if len(result) > 0 else None
except ExpectationNotMet:
return None | python | {
"resource": ""
} |
q275168 | inner_content | test | def inner_content(node):
"""
Returns the inner content of a given XML node, including tags.
Args:
node (lxml.etree.Element): The node whose inner content is desired.
Returns:
str: The inner content of the node.
"""
from lxml import etree
# Include text content at the start of the node.
parts = [node.text]
for child in node.getchildren():
# Include the child serialized to raw XML.
parts.append(etree.tostring(child, encoding="utf-8"))
# Include any text following the child.
parts.append(child.tail)
# Discard any non-existent text parts and return.
return "".join(filter(None, parts)) | python | {
"resource": ""
} |
q275169 | inner_text | test | def inner_text(node):
"""
Returns the inner text of a given XML node, excluding tags.
Args:
node: (lxml.etree.Element): The node whose inner text is desired.
Returns:
str: The inner text of the node.
"""
from lxml import etree
# Include text content at the start of the node.
parts = [node.text]
for child in node.getchildren():
# Include the raw text content of the child.
parts.append(etree.tostring(child, encoding="utf-8", method="text"))
# Include any text following the child.
parts.append(child.tail)
# Discard any non-existent text parts and return.
return "".join(map(decode_bytes, filter(None, parts))) | python | {
"resource": ""
} |
q275170 | normalize_url | test | def normalize_url(url):
"""
Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL.
"""
uri = urlparse(url)
query = uri.query or ""
pairs = parse_qsl(query)
decoded_pairs = [(unquote(key), value) for key, value in pairs]
encoded_pairs = [(quote(key), value) for key, value in decoded_pairs]
normalized_query = urlencode(encoded_pairs)
return ParseResult(
scheme=uri.scheme,
netloc=uri.netloc,
path=uri.path,
params=uri.params,
query=normalized_query,
fragment=uri.fragment).geturl() | python | {
"resource": ""
} |
q275171 | setter_decorator | test | def setter_decorator(fset):
"""
Define a write-only property that, in addition to the given setter function, also
provides a setter decorator defined as the property's getter function.
This allows one to set the property either through traditional assignment, as a
method argument, or through decoration::
class Widget(object):
@setter_decorator
def handler(self, value):
self._handler = value
widget = Widget()
# Method 1: Traditional assignment
widget.handler = lambda input: process(input)
# Method 2: Assignment via method argument
widget.handler(lambda input: process(input))
# Method 3: Assignment via decoration
@widget.handler
def handler(input):
return process(input)
# Method 3b: Assignment via decoration with extraneous parens
@widget.handler()
def handler(input):
return process(input)
"""
def fget(self):
def inner(value):
fset(self, value)
def outer(value=None):
if value:
# We are being called with the desired value, either directly or
# as a decorator.
inner(value)
else:
# Assume we are being called as a decorator with extraneous parens,
# so return the setter as the actual decorator.
return inner
return outer
fdoc = fset.__doc__
return property(fget, fset, None, fdoc) | python | {
"resource": ""
} |
q275172 | Base.synchronize | test | def synchronize(self, func=None, wait=None, errors=()):
"""
This method is Capybara's primary defense against asynchronicity problems. It works by
attempting to run a given decorated function until it succeeds. The exact behavior of this
method depends on a number of factors. Basically there are certain exceptions which, when
raised from the decorated function, instead of bubbling up, are caught, and the function is
re-run.
Certain drivers have no support for asynchronous processes. These drivers run the function,
and any error raised bubbles up immediately. This allows faster turn around in the case
where an expectation fails.
Only exceptions that are :exc:`ElementNotFound` or any subclass thereof cause the block to
be rerun. Drivers may specify additional exceptions which also cause reruns. This usually
occurs when a node is manipulated which no longer exists on the page. For example, the
Selenium driver specifies ``selenium.common.exceptions.StateElementReferenceException``.
As long as any of these exceptions are thrown, the function is re-run, until a certain
amount of time passes. The amount of time defaults to :data:`capybara.default_max_wait_time`
and can be overridden through the ``wait`` argument. This time is compared with the system
time to see how much time has passed. If the return value of ``time.time()`` is stubbed
out, Capybara will raise :exc:`FrozenInTime`.
Args:
func (Callable, optional): The function to decorate.
wait (int, optional): Number of seconds to retry this function.
errors (Tuple[Type[Exception]], optional): Exception types that cause the function to be
rerun. Defaults to ``driver.invalid_element_errors`` + :exc:`ElementNotFound`.
Returns:
Callable: The decorated function, or a decorator function.
Raises:
FrozenInTime: If the return value of ``time.time()`` appears stuck.
"""
def decorator(func):
@wraps(func)
def outer(*args, **kwargs):
seconds = wait if wait is not None else capybara.default_max_wait_time
def inner():
return func(*args, **kwargs)
if self.session.synchronized:
return inner()
else:
timer = Timer(seconds)
self.session.synchronized = True
try:
while True:
try:
return inner()
except Exception as e:
self.session.raise_server_error()
if not self._should_catch_error(e, errors):
raise
if timer.expired:
raise
sleep(0.05)
if timer.stalled:
raise FrozenInTime(
"time appears to be frozen, Capybara does not work with "
"libraries which freeze time, consider using time "
"traveling instead")
if capybara.automatic_reload:
self.reload()
finally:
self.session.synchronized = False
return outer
if func:
return decorator(func)
else:
return decorator | python | {
"resource": ""
} |
q275173 | Base._should_catch_error | test | def _should_catch_error(self, error, errors=()):
"""
Returns whether to catch the given error.
Args:
error (Exception): The error to consider.
errors (Tuple[Type[Exception], ...], optional): The exception types that should be
caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid
element errors.
Returns:
bool: Whether to catch the given error.
"""
caught_errors = (
errors or
self.session.driver.invalid_element_errors + (ElementNotFound,))
return isinstance(error, caught_errors) | python | {
"resource": ""
} |
q275174 | Result.compare_count | test | def compare_count(self):
"""
Returns how the result count compares to the query options.
The return value is negative if too few results were found, zero if enough were found, and
positive if too many were found.
Returns:
int: -1, 0, or 1.
"""
if self.query.options["count"] is not None:
count_opt = int(self.query.options["count"])
self._cache_at_least(count_opt + 1)
return cmp(len(self._result_cache), count_opt)
if self.query.options["minimum"] is not None:
min_opt = int(self.query.options["minimum"])
if not self._cache_at_least(min_opt):
return -1
if self.query.options["maximum"] is not None:
max_opt = int(self.query.options["maximum"])
if self._cache_at_least(max_opt + 1):
return 1
if self.query.options["between"] is not None:
between = self.query.options["between"]
min_opt, max_opt = between[0], between[-1]
if not self._cache_at_least(min_opt):
return -1
if self._cache_at_least(max_opt + 1):
return 1
return 0
return 0 | python | {
"resource": ""
} |
q275175 | Result._cache_at_least | test | def _cache_at_least(self, size):
"""
Attempts to fill the result cache with at least the given number of results.
Returns:
bool: Whether the cache contains at least the given size.
"""
try:
while len(self._result_cache) < size:
self._result_cache.append(next(self._result_iter))
return True
except StopIteration:
return False | python | {
"resource": ""
} |
q275176 | expects_none | test | def expects_none(options):
"""
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
"""
if any(options.get(key) is not None for key in ["count", "maximum", "minimum", "between"]):
return matches_count(0, options)
else:
return False | python | {
"resource": ""
} |
q275177 | failure_message | test | def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""
message = "expected to find {}".format(description)
if options["count"] is not None:
message += " {count} {times}".format(
count=options["count"],
times=declension("time", "times", options["count"]))
elif options["between"] is not None:
between = options["between"]
if between:
first, last = between[0], between[-1]
else:
first, last = None, None
message += " between {first} and {last} times".format(
first=first,
last=last)
elif options["maximum"] is not None:
message += " at most {maximum} {times}".format(
maximum=options["maximum"],
times=declension("time", "times", options["maximum"]))
elif options["minimum"] is not None:
message += " at least {minimum} {times}".format(
minimum=options["minimum"],
times=declension("time", "times", options["minimum"]))
return message | python | {
"resource": ""
} |
q275178 | matches_count | test | def matches_count(count, options):
"""
Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether the count matches the options.
"""
if options.get("count") is not None:
return count == int(options["count"])
if options.get("maximum") is not None and int(options["maximum"]) < count:
return False
if options.get("minimum") is not None and int(options["minimum"]) > count:
return False
if options.get("between") is not None and count not in options["between"]:
return False
return True | python | {
"resource": ""
} |
q275179 | normalize_text | test | def normalize_text(value):
"""
Normalizes the given value to a string of text with extra whitespace removed.
Byte sequences are decoded. ``None`` is converted to an empty string. Everything else
is simply cast to a string.
Args:
value (Any): The data to normalize.
Returns:
str: The normalized text.
"""
if value is None:
return ""
text = decode_bytes(value) if isbytes(value) else str_(value)
return normalize_whitespace(text) | python | {
"resource": ""
} |
q275180 | normalize_whitespace | test | def normalize_whitespace(text):
"""
Returns the given text with outer whitespace removed and inner whitespace collapsed.
Args:
text (str): The text to normalize.
Returns:
str: The normalized text.
"""
return re.sub(r"\s+", " ", text, flags=re.UNICODE).strip() | python | {
"resource": ""
} |
q275181 | toregex | test | def toregex(text, exact=False):
"""
Returns a compiled regular expression for the given text.
Args:
text (str | RegexObject): The text to match.
exact (bool, optional): Whether the generated regular expression should match exact
strings. Defaults to False.
Returns:
RegexObject: A compiled regular expression that will match the text.
"""
if isregex(text):
return text
escaped = re.escape(normalize_text(text))
if exact:
escaped = r"\A{}\Z".format(escaped)
return re.compile(escaped) | python | {
"resource": ""
} |
q275182 | CurrentPathQuery.resolves_for | test | def resolves_for(self, session):
"""
Returns whether this query resolves for the given session.
Args:
session (Session): The session for which this query should be executed.
Returns:
bool: Whether this query resolves.
"""
if self.url:
self.actual_path = session.current_url
else:
result = urlparse(session.current_url)
if self.only_path:
self.actual_path = result.path
else:
request_uri = result.path
if result.query:
request_uri += "?{0}".format(result.query)
self.actual_path = request_uri
if isregex(self.expected_path):
return self.expected_path.search(self.actual_path)
else:
return normalize_url(self.actual_path) == normalize_url(self.expected_path) | python | {
"resource": ""
} |
q275183 | Window.resize_to | test | def resize_to(self, width, height):
"""
Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
width (int): The new window width in pixels.
height (int): The new window height in pixels.
"""
self.driver.resize_window_to(self.handle, width, height) | python | {
"resource": ""
} |
q275184 | Server.boot | test | def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_key] = self.port
init_func = capybara.servers[capybara.server_name]
init_args = (self.middleware, self.port, self.host)
self.server_thread = Thread(target=init_func, args=init_args)
# Inform Python that it shouldn't wait for this thread to terminate before
# exiting. (It will still be appropriately terminated when the process exits.)
self.server_thread.daemon = True
self.server_thread.start()
# Make sure the server actually starts and becomes responsive.
timer = Timer(60)
while not self.responsive:
if timer.expired:
raise RuntimeError("WSGI application timed out during boot")
self.server_thread.join(0.1)
return self | python | {
"resource": ""
} |
q275185 | AdvancedProperty.cgetter | test | def cgetter(self, fcget: typing.Optional[typing.Callable[[typing.Any], typing.Any]]) -> "AdvancedProperty":
"""Descriptor to change the class wide getter on a property.
:param fcget: new class-wide getter.
:type fcget: typing.Optional[typing.Callable[[typing.Any, ], typing.Any]]
:return: AdvancedProperty
:rtype: AdvancedProperty
"""
self.__fcget = fcget
return self | python | {
"resource": ""
} |
q275186 | SeparateClassMethod.instance_method | test | def instance_method(self, imeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change instance method.
:param imeth: New instance method.
:type imeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
"""
self.__instance_method = imeth
return self | python | {
"resource": ""
} |
q275187 | SeparateClassMethod.class_method | test | def class_method(self, cmeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change class method.
:param cmeth: New class method.
:type cmeth: typing.Optional[typing.Callable]
:return: SeparateClassMethod
:rtype: SeparateClassMethod
"""
self.__class_method = cmeth
return self | python | {
"resource": ""
} |
q275188 | LogOnAccess.__traceback | test | def __traceback(self) -> str:
"""Get outer traceback text for logging."""
if not self.log_traceback:
return ""
exc_info = sys.exc_info()
stack = traceback.extract_stack()
exc_tb = traceback.extract_tb(exc_info[2])
full_tb = stack[:1] + exc_tb # cut decorator and build full traceback
exc_line: typing.List[str] = traceback.format_exception_only(*exc_info[:2])
# Make standard traceback string
tb_text = "\nTraceback (most recent call last):\n" + "".join(traceback.format_list(full_tb)) + "".join(exc_line)
return tb_text | python | {
"resource": ""
} |
q275189 | LogOnAccess.__get_obj_source | test | def __get_obj_source(self, instance: typing.Any, owner: typing.Optional[type] = None) -> str:
"""Get object repr block."""
if self.log_object_repr:
return f"{instance!r}"
return f"<{owner.__name__ if owner is not None else instance.__class__.__name__}() at 0x{id(instance):X}>" | python | {
"resource": ""
} |
q275190 | LogOnAccess._get_logger_for_instance | test | def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger:
"""Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
"""
if self.logger is not None: # pylint: disable=no-else-return
return self.logger
elif hasattr(instance, "logger") and isinstance(instance.logger, logging.Logger):
return instance.logger
elif hasattr(instance, "log") and isinstance(instance.log, logging.Logger):
return instance.log
return _LOGGER | python | {
"resource": ""
} |
q275191 | LogOnAccess.logger | test | def logger(self, logger: typing.Union[logging.Logger, str, None]) -> None:
"""Logger instance to use as override."""
if logger is None or isinstance(logger, logging.Logger):
self.__logger = logger
else:
self.__logger = logging.getLogger(logger) | python | {
"resource": ""
} |
q275192 | SlackAPI._call_api | test | def _call_api(self, method, params=None):
"""
Low-level method to call the Slack API.
Args:
method: {str} method name to call
params: {dict} GET parameters
The token will always be added
"""
url = self.url.format(method=method)
if not params:
params = {'token': self.token}
else:
params['token'] = self.token
logger.debug('Send request to %s', url)
response = requests.get(url, params=params).json()
if self.verify:
if not response['ok']:
msg = 'For {url} API returned this bad response {response}'
raise Exception(msg.format(url=url, response=response))
return response | python | {
"resource": ""
} |
q275193 | SlackAPI.channels | test | def channels(self):
"""
List of channels of this slack team
"""
if not self._channels:
self._channels = self._call_api('channels.list')['channels']
return self._channels | python | {
"resource": ""
} |
q275194 | SlackAPI.users | test | def users(self):
"""
List of users of this slack team
"""
if not self._users:
self._users = self._call_api('users.list')['members']
return self._users | python | {
"resource": ""
} |
q275195 | SlackClientProtocol.make_message | test | def make_message(self, text, channel):
"""
High-level function for creating messages. Return packed bytes.
Args:
text: {str}
channel: {str} Either name or ID
"""
try:
channel_id = self.slack.channel_from_name(channel)['id']
except ValueError:
channel_id = channel
return pack({
'text': text,
'type': 'message',
'channel': channel_id,
'id': self.message_id,
}) | python | {
"resource": ""
} |
q275196 | SlackClientProtocol.translate | test | def translate(self, message):
"""
Translate machine identifiers into human-readable
"""
# translate user
try:
user_id = message.pop('user')
user = self.slack.user_from_id(user_id)
message[u'user'] = user['name']
except (KeyError, IndexError, ValueError):
pass
# translate channel
try:
if type(message['channel']) == str:
channel_id = message.pop('channel')
else:
channel_id = message.pop('channel')['id']
self.slack.reload_channels()
channel = self.slack.channel_from_id(channel_id)
message[u'channel'] = channel['name']
except (KeyError, IndexError, ValueError):
pass
return message | python | {
"resource": ""
} |
q275197 | SlackClientProtocol.sendSlack | test | def sendSlack(self, message):
"""
Send message to Slack
"""
channel = message.get('channel', 'general')
self.sendMessage(self.make_message(message['text'], channel)) | python | {
"resource": ""
} |
q275198 | SlackClientFactory.read_channel | test | def read_channel(self):
"""
Get available messages and send through to the protocol
"""
channel, message = self.protocol.channel_layer.receive_many([u'slack.send'], block=False)
delay = 0.1
if channel:
self.protocols[0].sendSlack(message)
reactor.callLater(delay, self.read_channel) | python | {
"resource": ""
} |
q275199 | Client.run | test | def run(self):
"""
Main interface. Instantiate the SlackAPI, connect to RTM
and start the client.
"""
slack = SlackAPI(token=self.token)
rtm = slack.rtm_start()
factory = SlackClientFactory(rtm['url'])
# Attach attributes
factory.protocol = SlackClientProtocol
factory.protocol.slack = slack
factory.protocol.channel_layer = self.channel_layer
factory.channel_name = self.channel_name
# Here we go
factory.run() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.