partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
bitmap_type
Get the type of an image from the file's extension ( .jpg, etc. )
gui/graphic.py
def bitmap_type(filename): """ Get the type of an image from the file's extension ( .jpg, etc. ) """ if filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': return wx.BITMAP_TYPE_GIF elif ext == 'JPG' or ext == 'JPEG': return wx.BITMAP_TYPE_JPEG elif ext == 'PCX': return wx.BITMAP_TYPE_PCX elif ext == 'PICT': return wx.BITMAP_TYPE_PICT elif ext == 'PNG': return wx.BITMAP_TYPE_PNG elif ext == 'PNM': return wx.BITMAP_TYPE_PNM elif ext == 'TIF' or ext == 'TIFF': return wx.BITMAP_TYPE_TIF elif ext == 'XBM': return wx.BITMAP_TYPE_XBM elif ext == 'XPM': return wx.BITMAP_TYPE_XPM else: # KEA 2001-10-10 # rather than throw an exception, we could try and have wxPython figure out the image # type by returning wxBITMAP_TYPE_ANY raise RuntimeErro('invalid graphics format')
def bitmap_type(filename): """ Get the type of an image from the file's extension ( .jpg, etc. ) """ if filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': return wx.BITMAP_TYPE_GIF elif ext == 'JPG' or ext == 'JPEG': return wx.BITMAP_TYPE_JPEG elif ext == 'PCX': return wx.BITMAP_TYPE_PCX elif ext == 'PICT': return wx.BITMAP_TYPE_PICT elif ext == 'PNG': return wx.BITMAP_TYPE_PNG elif ext == 'PNM': return wx.BITMAP_TYPE_PNM elif ext == 'TIF' or ext == 'TIFF': return wx.BITMAP_TYPE_TIF elif ext == 'XBM': return wx.BITMAP_TYPE_XBM elif ext == 'XPM': return wx.BITMAP_TYPE_XPM else: # KEA 2001-10-10 # rather than throw an exception, we could try and have wxPython figure out the image # type by returning wxBITMAP_TYPE_ANY raise RuntimeErro('invalid graphics format')
[ "Get", "the", "type", "of", "an", "image", "from", "the", "file", "s", "extension", "(", ".", "jpg", "etc", ".", ")" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/graphic.py#L52-L86
[ "def", "bitmap_type", "(", "filename", ")", ":", "if", "filename", "==", "''", ":", "return", "None", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "ext", "=", "ext", "[", "1", ":", "]", ".", "upper", "(", ")", "if", "ext", "==", "'BMP'", ":", "return", "wx", ".", "BITMAP_TYPE_BMP", "elif", "ext", "==", "'GIF'", ":", "return", "wx", ".", "BITMAP_TYPE_GIF", "elif", "ext", "==", "'JPG'", "or", "ext", "==", "'JPEG'", ":", "return", "wx", ".", "BITMAP_TYPE_JPEG", "elif", "ext", "==", "'PCX'", ":", "return", "wx", ".", "BITMAP_TYPE_PCX", "elif", "ext", "==", "'PICT'", ":", "return", "wx", ".", "BITMAP_TYPE_PICT", "elif", "ext", "==", "'PNG'", ":", "return", "wx", ".", "BITMAP_TYPE_PNG", "elif", "ext", "==", "'PNM'", ":", "return", "wx", ".", "BITMAP_TYPE_PNM", "elif", "ext", "==", "'TIF'", "or", "ext", "==", "'TIFF'", ":", "return", "wx", ".", "BITMAP_TYPE_TIF", "elif", "ext", "==", "'XBM'", ":", "return", "wx", ".", "BITMAP_TYPE_XBM", "elif", "ext", "==", "'XPM'", ":", "return", "wx", ".", "BITMAP_TYPE_XPM", "else", ":", "# KEA 2001-10-10\r", "# rather than throw an exception, we could try and have wxPython figure out the image\r", "# type by returning wxBITMAP_TYPE_ANY\r", "raise", "RuntimeErro", "(", "'invalid graphics format'", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
Bitmap._getbitmap_type
Get the type of an image from the file's extension ( .jpg, etc. )
gui/graphic.py
def _getbitmap_type( self, filename ) : """ Get the type of an image from the file's extension ( .jpg, etc. ) """ # KEA 2001-07-27 # was #name, ext = filename.split( '.' ) #ext = ext.upper() if filename is None or filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': return wx.BITMAP_TYPE_GIF elif ext == 'JPG' or ext == 'JPEG': return wx.BITMAP_TYPE_JPEG elif ext == 'PCX': return wx.BITMAP_TYPE_PCX #elif ext == 'PICT': # return wx.BITMAP_TYPE_PICT elif ext == 'PNG': return wx.BITMAP_TYPE_PNG elif ext == 'PNM': return wx.BITMAP_TYPE_PNM elif ext == 'TIF' or ext == 'TIFF': return wx.BITMAP_TYPE_TIF elif ext == 'XBM': return wx.BITMAP_TYPE_XBM elif ext == 'XPM': return wx.BITMAP_TYPE_XPM else: # KEA 2001-10-10 # rather than throw an exception, we could try and have wxPython figure out the image # type by returning wxBITMAP_TYPE_ANY raise RuntimeError('invalid graphics format')
def _getbitmap_type( self, filename ) : """ Get the type of an image from the file's extension ( .jpg, etc. ) """ # KEA 2001-07-27 # was #name, ext = filename.split( '.' ) #ext = ext.upper() if filename is None or filename == '': return None name, ext = os.path.splitext(filename) ext = ext[1:].upper() if ext == 'BMP': return wx.BITMAP_TYPE_BMP elif ext == 'GIF': return wx.BITMAP_TYPE_GIF elif ext == 'JPG' or ext == 'JPEG': return wx.BITMAP_TYPE_JPEG elif ext == 'PCX': return wx.BITMAP_TYPE_PCX #elif ext == 'PICT': # return wx.BITMAP_TYPE_PICT elif ext == 'PNG': return wx.BITMAP_TYPE_PNG elif ext == 'PNM': return wx.BITMAP_TYPE_PNM elif ext == 'TIF' or ext == 'TIFF': return wx.BITMAP_TYPE_TIF elif ext == 'XBM': return wx.BITMAP_TYPE_XBM elif ext == 'XPM': return wx.BITMAP_TYPE_XPM else: # KEA 2001-10-10 # rather than throw an exception, we could try and have wxPython figure out the image # type by returning wxBITMAP_TYPE_ANY raise RuntimeError('invalid graphics format')
[ "Get", "the", "type", "of", "an", "image", "from", "the", "file", "s", "extension", "(", ".", "jpg", "etc", ".", ")" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/graphic.py#L153-L190
[ "def", "_getbitmap_type", "(", "self", ",", "filename", ")", ":", "# KEA 2001-07-27\r", "# was\r", "#name, ext = filename.split( '.' )\r", "#ext = ext.upper()\r", "if", "filename", "is", "None", "or", "filename", "==", "''", ":", "return", "None", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "ext", "=", "ext", "[", "1", ":", "]", ".", "upper", "(", ")", "if", "ext", "==", "'BMP'", ":", "return", "wx", ".", "BITMAP_TYPE_BMP", "elif", "ext", "==", "'GIF'", ":", "return", "wx", ".", "BITMAP_TYPE_GIF", "elif", "ext", "==", "'JPG'", "or", "ext", "==", "'JPEG'", ":", "return", "wx", ".", "BITMAP_TYPE_JPEG", "elif", "ext", "==", "'PCX'", ":", "return", "wx", ".", "BITMAP_TYPE_PCX", "#elif ext == 'PICT':\r", "# return wx.BITMAP_TYPE_PICT\r", "elif", "ext", "==", "'PNG'", ":", "return", "wx", ".", "BITMAP_TYPE_PNG", "elif", "ext", "==", "'PNM'", ":", "return", "wx", ".", "BITMAP_TYPE_PNM", "elif", "ext", "==", "'TIF'", "or", "ext", "==", "'TIFF'", ":", "return", "wx", ".", "BITMAP_TYPE_TIF", "elif", "ext", "==", "'XBM'", ":", "return", "wx", ".", "BITMAP_TYPE_XBM", "elif", "ext", "==", "'XPM'", ":", "return", "wx", ".", "BITMAP_TYPE_XPM", "else", ":", "# KEA 2001-10-10\r", "# rather than throw an exception, we could try and have wxPython figure out the image\r", "# type by returning wxBITMAP_TYPE_ANY\r", "raise", "RuntimeError", "(", "'invalid graphics format'", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
Window._set_icon
Set icon based on resource values
gui/windows/window.py
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
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
[ "Set", "icon", "based", "on", "resource", "values" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/windows/window.py#L78-L85
[ "def", "_set_icon", "(", "self", ",", "icon", "=", "None", ")", ":", "if", "icon", "is", "not", "None", ":", "try", ":", "wx_icon", "=", "wx", ".", "Icon", "(", "icon", ",", "wx", ".", "BITMAP_TYPE_ICO", ")", "self", ".", "wx_obj", ".", "SetIcon", "(", "wx_icon", ")", "except", ":", "pass" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
Window.show
Display or hide the window, optionally disabling all other windows
gui/windows/window.py
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
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
[ "Display", "or", "hide", "the", "window", "optionally", "disabling", "all", "other", "windows" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/windows/window.py#L124-L139
[ "def", "show", "(", "self", ",", "value", "=", "True", ",", "modal", "=", "None", ")", ":", "self", ".", "wx_obj", ".", "Show", "(", "value", ")", "if", "modal", ":", "# disable all top level windows of this application (MakeModal)\r", "disabler", "=", "wx", ".", "WindowDisabler", "(", "self", ".", "wx_obj", ")", "# create an event loop to stop execution \r", "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 \r", "eventloop", ".", "Run", "(", ")", "# reenable the windows disabled and return control to the caller\r", "del", "disabler" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
Canvas.draw_arc
Draws an arc of a circle, centered on (xc, yc), with starting point (x1, y1) and ending at (x2, y2). The current pen is used for the outline and the current brush for filling the shape. The arc is drawn in an anticlockwise direction from the start point to the end point.
gui/controls/canvas.py
def draw_arc(self, x1y1, x2y2, xcyc): """ Draws an arc of a circle, centered on (xc, yc), with starting point (x1, y1) and ending at (x2, y2). The current pen is used for the outline and the current brush for filling the shape. The arc is drawn in an anticlockwise direction from the start point to the end point. """ self._buf_image.DrawArcPoint(x1y1, x2y2, xcyc) if self.auto_refresh: dc = wx.ClientDC(self.wx_obj) dc.BlitPointSize((0, 0), (self._size[0], self._size[1]), self._buf_image, (0, 0))
def draw_arc(self, x1y1, x2y2, xcyc): """ Draws an arc of a circle, centered on (xc, yc), with starting point (x1, y1) and ending at (x2, y2). The current pen is used for the outline and the current brush for filling the shape. The arc is drawn in an anticlockwise direction from the start point to the end point. """ self._buf_image.DrawArcPoint(x1y1, x2y2, xcyc) if self.auto_refresh: dc = wx.ClientDC(self.wx_obj) dc.BlitPointSize((0, 0), (self._size[0], self._size[1]), self._buf_image, (0, 0))
[ "Draws", "an", "arc", "of", "a", "circle", "centered", "on", "(", "xc", "yc", ")", "with", "starting", "point", "(", "x1", "y1", ")", "and", "ending", "at", "(", "x2", "y2", ")", ".", "The", "current", "pen", "is", "used", "for", "the", "outline", "and", "the", "current", "brush", "for", "filling", "the", "shape", "." ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/controls/canvas.py#L225-L238
[ "def", "draw_arc", "(", "self", ",", "x1y1", ",", "x2y2", ",", "xcyc", ")", ":", "self", ".", "_buf_image", ".", "DrawArcPoint", "(", "x1y1", ",", "x2y2", ",", "xcyc", ")", "if", "self", ".", "auto_refresh", ":", "dc", "=", "wx", ".", "ClientDC", "(", "self", ".", "wx_obj", ")", "dc", ".", "BlitPointSize", "(", "(", "0", ",", "0", ")", ",", "(", "self", ".", "_size", "[", "0", "]", ",", "self", ".", "_size", "[", "1", "]", ")", ",", "self", ".", "_buf_image", ",", "(", "0", ",", "0", ")", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
TabPanel.resize
automatically adjust relative pos and size of children controls
gui/controls/notebook.py
def resize(self, evt=None): "automatically adjust relative pos and size of children controls" for child in self: if isinstance(child, Control): child.resize(evt) # call original handler (wx.HtmlWindow) if evt: evt.Skip()
def resize(self, evt=None): "automatically adjust relative pos and size of children controls" for child in self: if isinstance(child, Control): child.resize(evt) # call original handler (wx.HtmlWindow) if evt: evt.Skip()
[ "automatically", "adjust", "relative", "pos", "and", "size", "of", "children", "controls" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/controls/notebook.py#L104-L111
[ "def", "resize", "(", "self", ",", "evt", "=", "None", ")", ":", "for", "child", "in", "self", ":", "if", "isinstance", "(", "child", ",", "Control", ")", ":", "child", ".", "resize", "(", "evt", ")", "# call original handler (wx.HtmlWindow)\r", "if", "evt", ":", "evt", ".", "Skip", "(", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
parse
Open, read and eval the resource from the source file
gui/resource.py
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
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
[ "Open", "read", "and", "eval", "the", "resource", "from", "the", "source", "file" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L24-L31
[ "def", "parse", "(", "filename", "=", "\"\"", ")", ":", "# use the provided resource file:", "s", "=", "open", "(", "filename", ")", ".", "read", "(", ")", "##s.decode(\"latin1\").encode(\"utf8\")", "import", "datetime", ",", "decimal", "rsrc", "=", "eval", "(", "s", ")", "return", "rsrc" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
save
Save the resource to the source file
gui/resource.py
def save(filename, rsrc): "Save the resource to the source file" s = pprint.pformat(rsrc) ## s = s.encode("utf8") open(filename, "w").write(s)
def save(filename, rsrc): "Save the resource to the source file" s = pprint.pformat(rsrc) ## s = s.encode("utf8") open(filename, "w").write(s)
[ "Save", "the", "resource", "to", "the", "source", "file" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L34-L38
[ "def", "save", "(", "filename", ",", "rsrc", ")", ":", "s", "=", "pprint", ".", "pformat", "(", "rsrc", ")", "## s = s.encode(\"utf8\")", "open", "(", "filename", ",", "\"w\"", ")", ".", "write", "(", "s", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
load
Create the GUI objects defined in the resource (filename or python struct)
gui/resource.py
def load(controller=None, filename="", name=None, rsrc=None): "Create the GUI objects defined in the resource (filename or python struct)" # if no filename is given, search for the rsrc.py with the same module name: if not filename and not rsrc: if isinstance(controller, types.ClassType): # use the controller class module (to get __file__ for rsrc.py) mod_dict = util.get_class_module_dict(controller) elif isinstance(controller, types.ModuleType): # use the module provided as controller mod_dict = controller.__dict__ elif isinstance(controller, Controller): # use the instance provided as controller mod_dict = util.get_class_module_dict(controller) else: # use the caller module (no controller explicitelly provided) mod_dict = util.get_caller_module_dict() # do not use as controller if it was explicitly False or empty if controller is None: controller = mod_dict if util.main_is_frozen(): # running standalone if '__file__' in mod_dict: filename = os.path.split(mod_dict['__file__'])[1] else: # __main__ has not __file__ under py2exe! filename = os.path.split(sys.argv[0])[-1] filename = os.path.join(util.get_app_dir(), filename) else: # figure out the .rsrc.py filename based on the module name filename = mod_dict['__file__'] # chop the .pyc or .pyo from the end base, ext = os.path.splitext(filename) filename = base + ".rsrc.py" # when rsrc is a file name, open, read and eval it: if isinstance(filename, basestring): rsrc = parse(filename) ret = [] # search over the resource to create the requested object (or all) for win in rsrc: if not name or win['name'] == name: ret.append(build_window(win)) # associate event handlers if ret and controller: connect(ret[0], controller) # return the first instance created (if any): return ret[0] else: # return all the instances created -for the designer- (if any): return ret
def load(controller=None, filename="", name=None, rsrc=None): "Create the GUI objects defined in the resource (filename or python struct)" # if no filename is given, search for the rsrc.py with the same module name: if not filename and not rsrc: if isinstance(controller, types.ClassType): # use the controller class module (to get __file__ for rsrc.py) mod_dict = util.get_class_module_dict(controller) elif isinstance(controller, types.ModuleType): # use the module provided as controller mod_dict = controller.__dict__ elif isinstance(controller, Controller): # use the instance provided as controller mod_dict = util.get_class_module_dict(controller) else: # use the caller module (no controller explicitelly provided) mod_dict = util.get_caller_module_dict() # do not use as controller if it was explicitly False or empty if controller is None: controller = mod_dict if util.main_is_frozen(): # running standalone if '__file__' in mod_dict: filename = os.path.split(mod_dict['__file__'])[1] else: # __main__ has not __file__ under py2exe! filename = os.path.split(sys.argv[0])[-1] filename = os.path.join(util.get_app_dir(), filename) else: # figure out the .rsrc.py filename based on the module name filename = mod_dict['__file__'] # chop the .pyc or .pyo from the end base, ext = os.path.splitext(filename) filename = base + ".rsrc.py" # when rsrc is a file name, open, read and eval it: if isinstance(filename, basestring): rsrc = parse(filename) ret = [] # search over the resource to create the requested object (or all) for win in rsrc: if not name or win['name'] == name: ret.append(build_window(win)) # associate event handlers if ret and controller: connect(ret[0], controller) # return the first instance created (if any): return ret[0] else: # return all the instances created -for the designer- (if any): return ret
[ "Create", "the", "GUI", "objects", "defined", "in", "the", "resource", "(", "filename", "or", "python", "struct", ")" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L41-L89
[ "def", "load", "(", "controller", "=", "None", ",", "filename", "=", "\"\"", ",", "name", "=", "None", ",", "rsrc", "=", "None", ")", ":", "# if no filename is given, search for the rsrc.py with the same module name:", "if", "not", "filename", "and", "not", "rsrc", ":", "if", "isinstance", "(", "controller", ",", "types", ".", "ClassType", ")", ":", "# use the controller class module (to get __file__ for rsrc.py)", "mod_dict", "=", "util", ".", "get_class_module_dict", "(", "controller", ")", "elif", "isinstance", "(", "controller", ",", "types", ".", "ModuleType", ")", ":", "# use the module provided as controller", "mod_dict", "=", "controller", ".", "__dict__", "elif", "isinstance", "(", "controller", ",", "Controller", ")", ":", "# use the instance provided as controller", "mod_dict", "=", "util", ".", "get_class_module_dict", "(", "controller", ")", "else", ":", "# use the caller module (no controller explicitelly provided)", "mod_dict", "=", "util", ".", "get_caller_module_dict", "(", ")", "# do not use as controller if it was explicitly False or empty", "if", "controller", "is", "None", ":", "controller", "=", "mod_dict", "if", "util", ".", "main_is_frozen", "(", ")", ":", "# running standalone", "if", "'__file__'", "in", "mod_dict", ":", "filename", "=", "os", ".", "path", ".", "split", "(", "mod_dict", "[", "'__file__'", "]", ")", "[", "1", "]", "else", ":", "# __main__ has not __file__ under py2exe!", "filename", "=", "os", ".", "path", ".", "split", "(", "sys", ".", "argv", "[", "0", "]", ")", "[", "-", "1", "]", "filename", "=", "os", ".", "path", ".", "join", "(", "util", ".", "get_app_dir", "(", ")", ",", "filename", ")", "else", ":", "# figure out the .rsrc.py filename based on the module name", "filename", "=", "mod_dict", "[", "'__file__'", "]", "# chop the .pyc or .pyo from the end", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "filename", "=", "base", "+", "\".rsrc.py\"", "# when rsrc is a file name, open, read and eval it:", "if", "isinstance", "(", "filename", ",", "basestring", ")", ":", "rsrc", "=", "parse", "(", "filename", ")", "ret", "=", "[", "]", "# search over the resource to create the requested object (or all)", "for", "win", "in", "rsrc", ":", "if", "not", "name", "or", "win", "[", "'name'", "]", "==", "name", ":", "ret", ".", "append", "(", "build_window", "(", "win", ")", ")", "# associate event handlers", "if", "ret", "and", "controller", ":", "connect", "(", "ret", "[", "0", "]", ",", "controller", ")", "# return the first instance created (if any):", "return", "ret", "[", "0", "]", "else", ":", "# return all the instances created -for the designer- (if any):", "return", "ret" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
build_window
Create a gui2py window based on the python resource
gui/resource.py
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
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
[ "Create", "a", "gui2py", "window", "based", "on", "the", "python", "resource" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L92-L123
[ "def", "build_window", "(", "res", ")", ":", "# 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" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
build_component
Create a gui2py control based on the python resource
gui/resource.py
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
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
[ "Create", "a", "gui2py", "control", "based", "on", "the", "python", "resource" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L126-L155
[ "def", "build_component", "(", "res", ",", "parent", "=", "None", ")", ":", "# 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" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
dump
Recursive convert a live GUI object to a resource list/dict
gui/resource.py
def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name__} for (k, spec) in obj._meta.specs.items(): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' and k != 'parent' ): ret[k] = v for ctl in obj: if ret['type'] in registry.MENU: ret.setdefault('items', []).append(dump(ctl)) else: res = dump(ctl) if 'menubar' in res: ret.setdefault('menubar', []).append(res.pop('menubar')) else: ret.setdefault('components', []).append(res) return ret
def dump(obj): "Recursive convert a live GUI object to a resource list/dict" from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec import decimal, datetime from .font import Font from .graphic import Bitmap, Color from . import registry ret = {'type': obj.__class__.__name__} for (k, spec) in obj._meta.specs.items(): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' and k != 'parent' ): ret[k] = v for ctl in obj: if ret['type'] in registry.MENU: ret.setdefault('items', []).append(dump(ctl)) else: res = dump(ctl) if 'menubar' in res: ret.setdefault('menubar', []).append(res.pop('menubar')) else: ret.setdefault('components', []).append(res) return ret
[ "Recursive", "convert", "a", "live", "GUI", "object", "to", "a", "resource", "list", "/", "dict" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L158-L196
[ "def", "dump", "(", "obj", ")", ":", "from", ".", "spec", "import", "InitSpec", ",", "DimensionSpec", ",", "StyleSpec", ",", "InternalSpec", "import", "decimal", ",", "datetime", "from", ".", "font", "import", "Font", "from", ".", "graphic", "import", "Bitmap", ",", "Color", "from", ".", "import", "registry", "ret", "=", "{", "'type'", ":", "obj", ".", "__class__", ".", "__name__", "}", "for", "(", "k", ",", "spec", ")", "in", "obj", ".", "_meta", ".", "specs", ".", "items", "(", ")", ":", "if", "k", "==", "\"index\"", ":", "# index is really defined by creation order", "continue", "# also, avoid infinite recursion", "v", "=", "getattr", "(", "obj", ",", "k", ",", "\"\"", ")", "if", "(", "not", "isinstance", "(", "spec", ",", "InternalSpec", ")", "and", "v", "!=", "spec", ".", "default", "and", "(", "k", "!=", "'id'", "or", "v", ">", "0", ")", "and", "isinstance", "(", "v", ",", "(", "basestring", ",", "int", ",", "long", ",", "float", ",", "bool", ",", "dict", ",", "list", ",", "decimal", ".", "Decimal", ",", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "datetime", ".", "time", ",", "Font", ",", "Color", ")", ")", "and", "repr", "(", "v", ")", "!=", "'None'", "and", "k", "!=", "'parent'", ")", ":", "ret", "[", "k", "]", "=", "v", "for", "ctl", "in", "obj", ":", "if", "ret", "[", "'type'", "]", "in", "registry", ".", "MENU", ":", "ret", ".", "setdefault", "(", "'items'", ",", "[", "]", ")", ".", "append", "(", "dump", "(", "ctl", ")", ")", "else", ":", "res", "=", "dump", "(", "ctl", ")", "if", "'menubar'", "in", "res", ":", "ret", ".", "setdefault", "(", "'menubar'", ",", "[", "]", ")", ".", "append", "(", "res", ".", "pop", "(", "'menubar'", ")", ")", "else", ":", "ret", ".", "setdefault", "(", "'components'", ",", "[", "]", ")", ".", "append", "(", "res", ")", "return", "ret" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
connect
Associate event handlers
gui/resource.py
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])
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])
[ "Associate", "event", "handlers" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L199-L243
[ "def", "connect", "(", "component", ",", "controller", "=", "None", ")", ":", "# 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", "]", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
PythonCardWrapper.convert
translate gui2py attribute name from pythoncard legacy code
gui/resource.py
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
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
[ "translate", "gui2py", "attribute", "name", "from", "pythoncard", "legacy", "code" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L252-L259
[ "def", "convert", "(", "self", ",", "name", ")", ":", "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" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
get_data
Read from the clipboard content, return a suitable object (string or bitmap)
gui/clipboard.py
def get_data(): "Read from the clipboard content, return a suitable object (string or bitmap)" data = None try: if wx.TheClipboard.Open(): if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): do = wx.TextDataObject() wx.TheClipboard.GetData(do) data = do.GetText() elif wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)): do = wx.BitmapDataObject() wx.TheClipboard.GetData(do) data = do.GetBitmap() wx.TheClipboard.Close() except: data = None return data
def get_data(): "Read from the clipboard content, return a suitable object (string or bitmap)" data = None try: if wx.TheClipboard.Open(): if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)): do = wx.TextDataObject() wx.TheClipboard.GetData(do) data = do.GetText() elif wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)): do = wx.BitmapDataObject() wx.TheClipboard.GetData(do) data = do.GetBitmap() wx.TheClipboard.Close() except: data = None return data
[ "Read", "from", "the", "clipboard", "content", "return", "a", "suitable", "object", "(", "string", "or", "bitmap", ")" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/clipboard.py#L8-L24
[ "def", "get_data", "(", ")", ":", "data", "=", "None", "try", ":", "if", "wx", ".", "TheClipboard", ".", "Open", "(", ")", ":", "if", "wx", ".", "TheClipboard", ".", "IsSupported", "(", "wx", ".", "DataFormat", "(", "wx", ".", "DF_TEXT", ")", ")", ":", "do", "=", "wx", ".", "TextDataObject", "(", ")", "wx", ".", "TheClipboard", ".", "GetData", "(", "do", ")", "data", "=", "do", ".", "GetText", "(", ")", "elif", "wx", ".", "TheClipboard", ".", "IsSupported", "(", "wx", ".", "DataFormat", "(", "wx", ".", "DF_BITMAP", ")", ")", ":", "do", "=", "wx", ".", "BitmapDataObject", "(", ")", "wx", ".", "TheClipboard", ".", "GetData", "(", "do", ")", "data", "=", "do", ".", "GetBitmap", "(", ")", "wx", ".", "TheClipboard", ".", "Close", "(", ")", "except", ":", "data", "=", "None", "return", "data" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
set_data
Write content to the clipboard, data can be either a string or a bitmap
gui/clipboard.py
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
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
[ "Write", "content", "to", "the", "clipboard", "data", "can", "be", "either", "a", "string", "or", "a", "bitmap" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/clipboard.py#L27-L41
[ "def", "set_data", "(", "data", ")", ":", "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" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
find_autosummary_in_files
Find out what items are documented in source/*.rst. See `find_autosummary_in_lines`.
gui/doc/ext/autosummary/generate.py
def find_autosummary_in_files(filenames): """Find out what items are documented in source/*.rst. See `find_autosummary_in_lines`. """ documented = [] for filename in filenames: f = open(filename, 'r') lines = f.read().splitlines() documented.extend(find_autosummary_in_lines(lines, filename=filename)) f.close() return documented
def find_autosummary_in_files(filenames): """Find out what items are documented in source/*.rst. See `find_autosummary_in_lines`. """ documented = [] for filename in filenames: f = open(filename, 'r') lines = f.read().splitlines() documented.extend(find_autosummary_in_lines(lines, filename=filename)) f.close() return documented
[ "Find", "out", "what", "items", "are", "documented", "in", "source", "/", "*", ".", "rst", "." ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/doc/ext/autosummary/generate.py#L274-L285
[ "def", "find_autosummary_in_files", "(", "filenames", ")", ":", "documented", "=", "[", "]", "for", "filename", "in", "filenames", ":", "f", "=", "open", "(", "filename", ",", "'r'", ")", "lines", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "documented", ".", "extend", "(", "find_autosummary_in_lines", "(", "lines", ",", "filename", "=", "filename", ")", ")", "f", ".", "close", "(", ")", "return", "documented" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
find_autosummary_in_docstring
Find out what items are documented in the given object's docstring. See `find_autosummary_in_lines`.
gui/doc/ext/autosummary/generate.py
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 []
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 []
[ "Find", "out", "what", "items", "are", "documented", "in", "the", "given", "object", "s", "docstring", "." ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/doc/ext/autosummary/generate.py#L287-L300
[ "def", "find_autosummary_in_docstring", "(", "name", ",", "module", "=", "None", ",", "filename", "=", "None", ")", ":", "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", "[", "]" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
find_autosummary_in_lines
Find out what items appear in autosummary:: directives in the given lines. Returns a list of (name, toctree, template) where *name* is a name of an object and *toctree* the :toctree: path of the corresponding autosummary directive (relative to the root of the file name), and *template* the value of the :template: option. *toctree* and *template* ``None`` if the directive does not have the corresponding options set.
gui/doc/ext/autosummary/generate.py
def find_autosummary_in_lines(lines, module=None, filename=None): """Find out what items appear in autosummary:: directives in the given lines. Returns a list of (name, toctree, template) where *name* is a name of an object and *toctree* the :toctree: path of the corresponding autosummary directive (relative to the root of the file name), and *template* the value of the :template: option. *toctree* and *template* ``None`` if the directive does not have the corresponding options set. """ autosummary_re = re.compile(r'^(\s*)\.\.\s+autosummary::\s*') automodule_re = re.compile( r'^\s*\.\.\s+automodule::\s*([A-Za-z0-9_.]+)\s*$') module_re = re.compile( r'^\s*\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') template_arg_re = re.compile(r'^\s+:template:\s*(.*?)\s*$') documented = [] toctree = None template = None current_module = module in_autosummary = False base_indent = "" for line in lines: if in_autosummary: m = toctree_arg_re.match(line) if m: toctree = m.group(1) if filename: toctree = os.path.join(os.path.dirname(filename), toctree) continue m = template_arg_re.match(line) if m: template = m.group(1).strip() continue if line.strip().startswith(':'): continue # skip options m = autosummary_item_re.match(line) if m: name = m.group(1).strip() if name.startswith('~'): name = name[1:] if current_module and \ not name.startswith(current_module + '.'): name = "%s.%s" % (current_module, name) documented.append((name, toctree, template)) continue if not line.strip() or line.startswith(base_indent + " "): continue in_autosummary = False m = autosummary_re.match(line) if m: in_autosummary = True base_indent = m.group(1) toctree = None template = None continue m = automodule_re.search(line) if m: current_module = m.group(1).strip() # recurse into the automodule docstring documented.extend(find_autosummary_in_docstring( current_module, filename=filename)) continue m = module_re.match(line) if m: current_module = m.group(2) continue return documented
def find_autosummary_in_lines(lines, module=None, filename=None): """Find out what items appear in autosummary:: directives in the given lines. Returns a list of (name, toctree, template) where *name* is a name of an object and *toctree* the :toctree: path of the corresponding autosummary directive (relative to the root of the file name), and *template* the value of the :template: option. *toctree* and *template* ``None`` if the directive does not have the corresponding options set. """ autosummary_re = re.compile(r'^(\s*)\.\.\s+autosummary::\s*') automodule_re = re.compile( r'^\s*\.\.\s+automodule::\s*([A-Za-z0-9_.]+)\s*$') module_re = re.compile( r'^\s*\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') template_arg_re = re.compile(r'^\s+:template:\s*(.*?)\s*$') documented = [] toctree = None template = None current_module = module in_autosummary = False base_indent = "" for line in lines: if in_autosummary: m = toctree_arg_re.match(line) if m: toctree = m.group(1) if filename: toctree = os.path.join(os.path.dirname(filename), toctree) continue m = template_arg_re.match(line) if m: template = m.group(1).strip() continue if line.strip().startswith(':'): continue # skip options m = autosummary_item_re.match(line) if m: name = m.group(1).strip() if name.startswith('~'): name = name[1:] if current_module and \ not name.startswith(current_module + '.'): name = "%s.%s" % (current_module, name) documented.append((name, toctree, template)) continue if not line.strip() or line.startswith(base_indent + " "): continue in_autosummary = False m = autosummary_re.match(line) if m: in_autosummary = True base_indent = m.group(1) toctree = None template = None continue m = automodule_re.search(line) if m: current_module = m.group(1).strip() # recurse into the automodule docstring documented.extend(find_autosummary_in_docstring( current_module, filename=filename)) continue m = module_re.match(line) if m: current_module = m.group(2) continue return documented
[ "Find", "out", "what", "items", "appear", "in", "autosummary", "::", "directives", "in", "the", "given", "lines", "." ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/doc/ext/autosummary/generate.py#L302-L385
[ "def", "find_autosummary_in_lines", "(", "lines", ",", "module", "=", "None", ",", "filename", "=", "None", ")", ":", "autosummary_re", "=", "re", ".", "compile", "(", "r'^(\\s*)\\.\\.\\s+autosummary::\\s*'", ")", "automodule_re", "=", "re", ".", "compile", "(", "r'^\\s*\\.\\.\\s+automodule::\\s*([A-Za-z0-9_.]+)\\s*$'", ")", "module_re", "=", "re", ".", "compile", "(", "r'^\\s*\\.\\.\\s+(current)?module::\\s*([a-zA-Z0-9_.]+)\\s*$'", ")", "autosummary_item_re", "=", "re", ".", "compile", "(", "r'^\\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\\s*.*?'", ")", "toctree_arg_re", "=", "re", ".", "compile", "(", "r'^\\s+:toctree:\\s*(.*?)\\s*$'", ")", "template_arg_re", "=", "re", ".", "compile", "(", "r'^\\s+:template:\\s*(.*?)\\s*$'", ")", "documented", "=", "[", "]", "toctree", "=", "None", "template", "=", "None", "current_module", "=", "module", "in_autosummary", "=", "False", "base_indent", "=", "\"\"", "for", "line", "in", "lines", ":", "if", "in_autosummary", ":", "m", "=", "toctree_arg_re", ".", "match", "(", "line", ")", "if", "m", ":", "toctree", "=", "m", ".", "group", "(", "1", ")", "if", "filename", ":", "toctree", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "filename", ")", ",", "toctree", ")", "continue", "m", "=", "template_arg_re", ".", "match", "(", "line", ")", "if", "m", ":", "template", "=", "m", ".", "group", "(", "1", ")", ".", "strip", "(", ")", "continue", "if", "line", ".", "strip", "(", ")", ".", "startswith", "(", "':'", ")", ":", "continue", "# skip options", "m", "=", "autosummary_item_re", ".", "match", "(", "line", ")", "if", "m", ":", "name", "=", "m", ".", "group", "(", "1", ")", ".", "strip", "(", ")", "if", "name", ".", "startswith", "(", "'~'", ")", ":", "name", "=", "name", "[", "1", ":", "]", "if", "current_module", "and", "not", "name", ".", "startswith", "(", "current_module", "+", "'.'", ")", ":", "name", "=", "\"%s.%s\"", "%", "(", "current_module", ",", "name", ")", "documented", ".", "append", "(", "(", "name", ",", "toctree", ",", "template", ")", ")", "continue", "if", "not", "line", ".", "strip", "(", ")", "or", "line", ".", "startswith", "(", "base_indent", "+", "\" \"", ")", ":", "continue", "in_autosummary", "=", "False", "m", "=", "autosummary_re", ".", "match", "(", "line", ")", "if", "m", ":", "in_autosummary", "=", "True", "base_indent", "=", "m", ".", "group", "(", "1", ")", "toctree", "=", "None", "template", "=", "None", "continue", "m", "=", "automodule_re", ".", "search", "(", "line", ")", "if", "m", ":", "current_module", "=", "m", ".", "group", "(", "1", ")", ".", "strip", "(", ")", "# recurse into the automodule docstring", "documented", ".", "extend", "(", "find_autosummary_in_docstring", "(", "current_module", ",", "filename", "=", "filename", ")", ")", "continue", "m", "=", "module_re", ".", "match", "(", "line", ")", "if", "m", ":", "current_module", "=", "m", ".", "group", "(", "2", ")", "continue", "return", "documented" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
InspectorPanel.load_object
Add the object and all their childs
gui/tools/inspector.py
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)
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)
[ "Add", "the", "object", "and", "all", "their", "childs" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/tools/inspector.py#L73-L88
[ "def", "load_object", "(", "self", ",", "obj", "=", "None", ")", ":", "# 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", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
InspectorPanel.inspect
Select the object and show its properties
gui/tools/inspector.py
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)
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)
[ "Select", "the", "object", "and", "show", "its", "properties" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/tools/inspector.py#L90-L101
[ "def", "inspect", "(", "self", ",", "obj", ",", "context_menu", "=", "False", ",", "edit_prop", "=", "False", ",", "mouse_pos", "=", "None", ")", ":", "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", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
InspectorPanel.activate_item
load the selected item in the property editor
gui/tools/inspector.py
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
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
[ "load", "the", "selected", "item", "in", "the", "property", "editor" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/tools/inspector.py#L121-L134
[ "def", "activate_item", "(", "self", ",", "child", ",", "edit_prop", "=", "False", ",", "select", "=", "False", ")", ":", "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" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
InspectorPanel.update
Update the tree item when the object name changes
gui/tools/inspector.py
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)
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)
[ "Update", "the", "tree", "item", "when", "the", "object", "name", "changes" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/tools/inspector.py#L136-L147
[ "def", "update", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "# 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", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
InspectorPanel.show_context_menu
Open a popup menu with options regarding the selected object
gui/tools/inspector.py
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)
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)
[ "Open", "a", "popup", "menu", "with", "options", "regarding", "the", "selected", "object" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/tools/inspector.py#L200-L240
[ "def", "show_context_menu", "(", "self", ",", "item", ",", "mouse_pos", "=", "None", ")", ":", "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", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
Timer.set_parent
Re-parent a child control with the new wx_obj parent (owner)
gui/timer.py
def set_parent(self, new_parent, init=False): "Re-parent a child control with the new wx_obj parent (owner)" ##SubComponent.set_parent(self, new_parent, init) self.wx_obj.SetOwner(new_parent.wx_obj.GetEventHandler())
def set_parent(self, new_parent, init=False): "Re-parent a child control with the new wx_obj parent (owner)" ##SubComponent.set_parent(self, new_parent, init) self.wx_obj.SetOwner(new_parent.wx_obj.GetEventHandler())
[ "Re", "-", "parent", "a", "child", "control", "with", "the", "new", "wx_obj", "parent", "(", "owner", ")" ]
reingart/gui2py
python
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/timer.py#L28-L31
[ "def", "set_parent", "(", "self", ",", "new_parent", ",", "init", "=", "False", ")", ":", "##SubComponent.set_parent(self, new_parent, init)", "self", ".", "wx_obj", ".", "SetOwner", "(", "new_parent", ".", "wx_obj", ".", "GetEventHandler", "(", ")", ")" ]
aca0a05f6fcde55c94ad7cc058671a06608b01a4
test
HyperlinkedSorlImageField.to_representation
Perform the actual serialization. Args: value: the image to transform Returns: a url pointing at a scaled and cached image
sorl_thumbnail_serializer/fields.py
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
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
[ "Perform", "the", "actual", "serialization", "." ]
dessibelle/sorl-thumbnail-serializer-field
python
https://github.com/dessibelle/sorl-thumbnail-serializer-field/blob/ac36f9de2f1df4c902e7bb371ac5be24d8b50f1f/sorl_thumbnail_serializer/fields.py#L71-L92
[ "def", "to_representation", "(", "self", ",", "value", ")", ":", "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" ]
ac36f9de2f1df4c902e7bb371ac5be24d8b50f1f
test
add_selector
Builds and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`.
capybara/selector/selector.py
def add_selector(name): """ Builds and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`. """ factory = SelectorFactory(name) yield factory selectors[name] = factory.build_selector()
def add_selector(name): """ Builds and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`. """ factory = SelectorFactory(name) yield factory selectors[name] = factory.build_selector()
[ "Builds", "and", "registers", "a", ":", "class", ":", "Selector", "object", "with", "the", "given", "name", "and", "configuration", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L188-L201
[ "def", "add_selector", "(", "name", ")", ":", "factory", "=", "SelectorFactory", "(", "name", ")", "yield", "factory", "selectors", "[", "name", "]", "=", "factory", ".", "build_selector", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Selector.expression_filters
Dict[str, ExpressionFilter]: Returns the expression filters for this selector.
capybara/selector/selector.py
def expression_filters(self): """ Dict[str, ExpressionFilter]: Returns the expression filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, ExpressionFilter)}
def expression_filters(self): """ Dict[str, ExpressionFilter]: Returns the expression filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, ExpressionFilter)}
[ "Dict", "[", "str", "ExpressionFilter", "]", ":", "Returns", "the", "expression", "filters", "for", "this", "selector", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L57-L62
[ "def", "expression_filters", "(", "self", ")", ":", "return", "{", "name", ":", "filter", "for", "name", ",", "filter", "in", "iter", "(", "self", ".", "filters", ".", "items", "(", ")", ")", "if", "isinstance", "(", "filter", ",", "ExpressionFilter", ")", "}" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Selector.node_filters
Dict[str, NodeFilter]: Returns the node filters for this selector.
capybara/selector/selector.py
def node_filters(self): """ Dict[str, NodeFilter]: Returns the node filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, NodeFilter)}
def node_filters(self): """ Dict[str, NodeFilter]: Returns the node filters for this selector. """ return { name: filter for name, filter in iter(self.filters.items()) if isinstance(filter, NodeFilter)}
[ "Dict", "[", "str", "NodeFilter", "]", ":", "Returns", "the", "node", "filters", "for", "this", "selector", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L65-L70
[ "def", "node_filters", "(", "self", ")", ":", "return", "{", "name", ":", "filter", "for", "name", ",", "filter", "in", "iter", "(", "self", ".", "filters", ".", "items", "(", ")", ")", "if", "isinstance", "(", "filter", ",", "NodeFilter", ")", "}" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorFactory.expression_filter
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.
capybara/selector/selector.py
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
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
[ "Returns", "a", "decorator", "function", "for", "adding", "an", "expression", "filter", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L123-L139
[ "def", "expression_filter", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "self", ".", "filters", "[", "name", "]", "=", "ExpressionFilter", "(", "name", ",", "func", ",", "*", "*", "kwargs", ")", "return", "decorator" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorFactory.node_filter
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.
capybara/selector/selector.py
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
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
[ "Returns", "a", "decorator", "function", "for", "adding", "a", "node", "filter", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L141-L157
[ "def", "node_filter", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "self", ".", "filters", "[", "name", "]", "=", "NodeFilter", "(", "name", ",", "func", ",", "*", "*", "kwargs", ")", "return", "decorator" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorFactory.filter_set
Adds filters from a particular global :class:`FilterSet`. Args: name (str): The name of the set whose filters should be added.
capybara/selector/selector.py
def filter_set(self, name): """ Adds filters from a particular global :class:`FilterSet`. Args: name (str): The name of the set whose filters should be added. """ filter_set = filter_sets[name] for name, filter in iter(filter_set.filters.items()): self.filters[name] = filter self.descriptions += filter_set.descriptions
def filter_set(self, name): """ Adds filters from a particular global :class:`FilterSet`. Args: name (str): The name of the set whose filters should be added. """ filter_set = filter_sets[name] for name, filter in iter(filter_set.filters.items()): self.filters[name] = filter self.descriptions += filter_set.descriptions
[ "Adds", "filters", "from", "a", "particular", "global", ":", "class", ":", "FilterSet", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L159-L170
[ "def", "filter_set", "(", "self", ",", "name", ")", ":", "filter_set", "=", "filter_sets", "[", "name", "]", "for", "name", ",", "filter", "in", "iter", "(", "filter_set", ".", "filters", ".", "items", "(", ")", ")", ":", "self", ".", "filters", "[", "name", "]", "=", "filter", "self", ".", "descriptions", "+=", "filter_set", ".", "descriptions" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorFactory.build_selector
Selector: Returns a new :class:`Selector` instance with the current configuration.
capybara/selector/selector.py
def build_selector(self): """ Selector: Returns a new :class:`Selector` instance with the current configuration. """ kwargs = { 'label': self.label, 'descriptions': self.descriptions, 'filters': self.filters} if self.format == "xpath": kwargs['xpath'] = self.func if self.format == "css": kwargs['css'] = self.func return Selector(self.name, **kwargs)
def build_selector(self): """ Selector: Returns a new :class:`Selector` instance with the current configuration. """ kwargs = { 'label': self.label, 'descriptions': self.descriptions, 'filters': self.filters} if self.format == "xpath": kwargs['xpath'] = self.func if self.format == "css": kwargs['css'] = self.func return Selector(self.name, **kwargs)
[ "Selector", ":", "Returns", "a", "new", ":", "class", ":", "Selector", "instance", "with", "the", "current", "configuration", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L172-L184
[ "def", "build_selector", "(", "self", ")", ":", "kwargs", "=", "{", "'label'", ":", "self", ".", "label", ",", "'descriptions'", ":", "self", ".", "descriptions", ",", "'filters'", ":", "self", ".", "filters", "}", "if", "self", ".", "format", "==", "\"xpath\"", ":", "kwargs", "[", "'xpath'", "]", "=", "self", ".", "func", "if", "self", ".", "format", "==", "\"css\"", ":", "kwargs", "[", "'css'", "]", "=", "self", ".", "func", "return", "Selector", "(", "self", ".", "name", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
StyleQuery.resolves_for
Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found.
capybara/queries/style_query.py
def resolves_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_styles = node.style(*self.expected_styles.keys()) return all( toregex(value).search(self.actual_styles[style]) for style, value in iter(self.expected_styles.items()))
def resolves_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_styles = node.style(*self.expected_styles.keys()) return all( toregex(value).search(self.actual_styles[style]) for style, value in iter(self.expected_styles.items()))
[ "Resolves", "this", "query", "relative", "to", "the", "given", "node", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/style_query.py#L27-L43
[ "def", "resolves_for", "(", "self", ",", "node", ")", ":", "self", ".", "node", "=", "node", "self", ".", "actual_styles", "=", "node", ".", "style", "(", "*", "self", ".", "expected_styles", ".", "keys", "(", ")", ")", "return", "all", "(", "toregex", "(", "value", ")", ".", "search", "(", "self", ".", "actual_styles", "[", "style", "]", ")", "for", "style", ",", "value", "in", "iter", "(", "self", ".", "expected_styles", ".", "items", "(", ")", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
StyleQuery.failure_message
str: A message describing the query failure.
capybara/queries/style_query.py
def failure_message(self): """ str: A message describing the query failure. """ return ( "Expected node to have styles {expected}. " "Actual styles were {actual}").format( expected=desc(self.expected_styles), actual=desc(self.actual_styles))
def failure_message(self): """ str: A message describing the query failure. """ return ( "Expected node to have styles {expected}. " "Actual styles were {actual}").format( expected=desc(self.expected_styles), actual=desc(self.actual_styles))
[ "str", ":", "A", "message", "describing", "the", "query", "failure", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/style_query.py#L46-L52
[ "def", "failure_message", "(", "self", ")", ":", "return", "(", "\"Expected node to have styles {expected}. \"", "\"Actual styles were {actual}\"", ")", ".", "format", "(", "expected", "=", "desc", "(", "self", ".", "expected_styles", ")", ",", "actual", "=", "desc", "(", "self", ".", "actual_styles", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SessionMatchersMixin.assert_current_path
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.
capybara/session_matchers.py
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
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
[ "Asserts", "that", "the", "page", "has", "the", "given", "path", ".", "By", "default", "this", "will", "compare", "against", "the", "path", "+", "query", "portion", "of", "the", "full", "URL", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session_matchers.py#L6-L30
[ "def", "assert_current_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "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" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SessionMatchersMixin.assert_no_current_path
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.
capybara/session_matchers.py
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
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
[ "Asserts", "that", "the", "page", "doesn", "t", "have", "the", "given", "path", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session_matchers.py#L32-L56
[ "def", "assert_no_current_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "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" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SessionMatchersMixin.has_current_path
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.
capybara/session_matchers.py
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
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
[ "Checks", "if", "the", "page", "has", "the", "given", "path", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session_matchers.py#L58-L73
[ "def", "has_current_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "assert_current_path", "(", "path", ",", "*", "*", "kwargs", ")", "except", "ExpectationNotMet", ":", "return", "False" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SessionMatchersMixin.has_no_current_path
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.
capybara/session_matchers.py
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
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
[ "Checks", "if", "the", "page", "doesn", "t", "have", "the", "given", "path", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session_matchers.py#L75-L90
[ "def", "has_no_current_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "assert_no_current_path", "(", "path", ",", "*", "*", "kwargs", ")", "except", "ExpectationNotMet", ":", "return", "False" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Element.text
Retrieve the text of the element. If :data:`capybara.ignore_hidden_elements` is ``True``, which it is by default, then this will return only text which is visible. The exact semantics of this may differ between drivers, but generally any text within elements with ``display: none`` is ignored. Returns: str: The text of the element.
capybara/node/element.py
def text(self): """ Retrieve the text of the element. If :data:`capybara.ignore_hidden_elements` is ``True``, which it is by default, then this will return only text which is visible. The exact semantics of this may differ between drivers, but generally any text within elements with ``display: none`` is ignored. Returns: str: The text of the element. """ if capybara.ignore_hidden_elements or capybara.visible_text_only: return self.visible_text else: return self.all_text
def text(self): """ Retrieve the text of the element. If :data:`capybara.ignore_hidden_elements` is ``True``, which it is by default, then this will return only text which is visible. The exact semantics of this may differ between drivers, but generally any text within elements with ``display: none`` is ignored. Returns: str: The text of the element. """ if capybara.ignore_hidden_elements or capybara.visible_text_only: return self.visible_text else: return self.all_text
[ "Retrieve", "the", "text", "of", "the", "element", ".", "If", ":", "data", ":", "capybara", ".", "ignore_hidden_elements", "is", "True", "which", "it", "is", "by", "default", "then", "this", "will", "return", "only", "text", "which", "is", "visible", ".", "The", "exact", "semantics", "of", "this", "may", "differ", "between", "drivers", "but", "generally", "any", "text", "within", "elements", "with", "display", ":", "none", "is", "ignored", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/element.py#L111-L125
[ "def", "text", "(", "self", ")", ":", "if", "capybara", ".", "ignore_hidden_elements", "or", "capybara", ".", "visible_text_only", ":", "return", "self", ".", "visible_text", "else", ":", "return", "self", ".", "all_text" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Element.select_option
Select this node if it is an option element inside a select tag.
capybara/node/element.py
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()
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()
[ "Select", "this", "node", "if", "it", "is", "an", "option", "element", "inside", "a", "select", "tag", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/element.py#L276-L280
[ "def", "select_option", "(", "self", ")", ":", "if", "self", ".", "disabled", ":", "warn", "(", "\"Attempt to select disabled option: {}\"", ".", "format", "(", "self", ".", "value", "or", "self", ".", "text", ")", ")", "self", ".", "base", ".", "select_option", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
ExpressionFilter.apply_filter
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.
capybara/selector/expression_filter.py
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)
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)
[ "Returns", "the", "given", "expression", "filtered", "by", "the", "given", "value", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/expression_filter.py#L7-L34
[ "def", "apply_filter", "(", "self", ",", "expr", ",", "value", ")", ":", "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", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
get_browser
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.
capybara/selenium/browser.py
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)))
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)))
[ "Returns", "an", "instance", "of", "the", "given", "browser", "with", "the", "given", "capabilities", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selenium/browser.py#L4-L34
[ "def", "get_browser", "(", "browser_name", ",", "capabilities", "=", "None", ",", "*", "*", "options", ")", ":", "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", ")", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorQuery.kwargs
Dict[str, Any]: The keyword arguments with which this query was initialized.
capybara/queries/selector_query.py
def kwargs(self): """ Dict[str, Any]: The keyword arguments with which this query was initialized. """ kwargs = {} kwargs.update(self.options) kwargs.update(self.filter_options) return kwargs
def kwargs(self): """ Dict[str, Any]: The keyword arguments with which this query was initialized. """ kwargs = {} kwargs.update(self.options) kwargs.update(self.filter_options) return kwargs
[ "Dict", "[", "str", "Any", "]", ":", "The", "keyword", "arguments", "with", "which", "this", "query", "was", "initialized", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L93-L98
[ "def", "kwargs", "(", "self", ")", ":", "kwargs", "=", "{", "}", "kwargs", ".", "update", "(", "self", ".", "options", ")", "kwargs", ".", "update", "(", "self", ".", "filter_options", ")", "return", "kwargs" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorQuery.description
str: A long description of this query.
capybara/queries/selector_query.py
def description(self): """ str: A long description of this query. """ description = self.label if self.locator: description += " {}".format(desc(self.locator)) if self.options["text"] is not None: description += " with text {}".format(desc(self.options["text"])) description += self.selector.description(self.filter_options) return description
def description(self): """ str: A long description of this query. """ description = self.label if self.locator: description += " {}".format(desc(self.locator)) if self.options["text"] is not None: description += " with text {}".format(desc(self.options["text"])) description += self.selector.description(self.filter_options) return description
[ "str", ":", "A", "long", "description", "of", "this", "query", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L101-L113
[ "def", "description", "(", "self", ")", ":", "description", "=", "self", ".", "label", "if", "self", ".", "locator", ":", "description", "+=", "\" {}\"", ".", "format", "(", "desc", "(", "self", ".", "locator", ")", ")", "if", "self", ".", "options", "[", "\"text\"", "]", "is", "not", "None", ":", "description", "+=", "\" with text {}\"", ".", "format", "(", "desc", "(", "self", ".", "options", "[", "\"text\"", "]", ")", ")", "description", "+=", "self", ".", "selector", ".", "description", "(", "self", ".", "filter_options", ")", "return", "description" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorQuery.visible
str: The desired element visibility.
capybara/queries/selector_query.py
def visible(self): """ str: The desired element visibility. """ if self.options["visible"] is not None: if self.options["visible"] is True: return "visible" elif self.options["visible"] is False: return "all" else: return self.options["visible"] else: if capybara.ignore_hidden_elements: return "visible" else: return "all"
def visible(self): """ str: The desired element visibility. """ if self.options["visible"] is not None: if self.options["visible"] is True: return "visible" elif self.options["visible"] is False: return "all" else: return self.options["visible"] else: if capybara.ignore_hidden_elements: return "visible" else: return "all"
[ "str", ":", "The", "desired", "element", "visibility", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L136-L149
[ "def", "visible", "(", "self", ")", ":", "if", "self", ".", "options", "[", "\"visible\"", "]", "is", "not", "None", ":", "if", "self", ".", "options", "[", "\"visible\"", "]", "is", "True", ":", "return", "\"visible\"", "elif", "self", ".", "options", "[", "\"visible\"", "]", "is", "False", ":", "return", "\"all\"", "else", ":", "return", "self", ".", "options", "[", "\"visible\"", "]", "else", ":", "if", "capybara", ".", "ignore_hidden_elements", ":", "return", "\"visible\"", "else", ":", "return", "\"all\"" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorQuery.xpath
Returns the XPath query for this selector. Args: exact (bool, optional): Whether to exactly match text. Returns: str: The XPath query for this selector.
capybara/queries/selector_query.py
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)
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)
[ "Returns", "the", "XPath", "query", "for", "this", "selector", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L160-L178
[ "def", "xpath", "(", "self", ",", "exact", "=", "None", ")", ":", "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", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorQuery.resolve_for
Resolves this query relative to the given node. Args: node (node.Base): The node relative to which this query should be resolved. exact (bool, optional): Whether to exactly match text. Returns: list[Element]: A list of elements matched by this query.
capybara/queries/selector_query.py
def resolve_for(self, node, exact=None): """ Resolves this query relative to the given node. Args: node (node.Base): The node relative to which this query should be resolved. exact (bool, optional): Whether to exactly match text. Returns: list[Element]: A list of elements matched by this query. """ from capybara.driver.node import Node from capybara.node.element import Element from capybara.node.simple import Simple @node.synchronize def resolve(): if self.selector.format == "css": children = node._find_css(self.css()) else: children = node._find_xpath(self.xpath(exact)) def wrap(child): if isinstance(child, Node): return Element(node.session, child, node, self) else: return Simple(child) children = [wrap(child) for child in children] return Result(children, self) return resolve()
def resolve_for(self, node, exact=None): """ Resolves this query relative to the given node. Args: node (node.Base): The node relative to which this query should be resolved. exact (bool, optional): Whether to exactly match text. Returns: list[Element]: A list of elements matched by this query. """ from capybara.driver.node import Node from capybara.node.element import Element from capybara.node.simple import Simple @node.synchronize def resolve(): if self.selector.format == "css": children = node._find_css(self.css()) else: children = node._find_xpath(self.xpath(exact)) def wrap(child): if isinstance(child, Node): return Element(node.session, child, node, self) else: return Simple(child) children = [wrap(child) for child in children] return Result(children, self) return resolve()
[ "Resolves", "this", "query", "relative", "to", "the", "given", "node", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L180-L213
[ "def", "resolve_for", "(", "self", ",", "node", ",", "exact", "=", "None", ")", ":", "from", "capybara", ".", "driver", ".", "node", "import", "Node", "from", "capybara", ".", "node", ".", "element", "import", "Element", "from", "capybara", ".", "node", ".", "simple", "import", "Simple", "@", "node", ".", "synchronize", "def", "resolve", "(", ")", ":", "if", "self", ".", "selector", ".", "format", "==", "\"css\"", ":", "children", "=", "node", ".", "_find_css", "(", "self", ".", "css", "(", ")", ")", "else", ":", "children", "=", "node", ".", "_find_xpath", "(", "self", ".", "xpath", "(", "exact", ")", ")", "def", "wrap", "(", "child", ")", ":", "if", "isinstance", "(", "child", ",", "Node", ")", ":", "return", "Element", "(", "node", ".", "session", ",", "child", ",", "node", ",", "self", ")", "else", ":", "return", "Simple", "(", "child", ")", "children", "=", "[", "wrap", "(", "child", ")", "for", "child", "in", "children", "]", "return", "Result", "(", "children", ",", "self", ")", "return", "resolve", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
SelectorQuery.matches_filters
Returns whether the given node matches all filters. Args: node (Element): The node to evaluate. Returns: bool: Whether the given node matches.
capybara/queries/selector_query.py
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
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
[ "Returns", "whether", "the", "given", "node", "matches", "all", "filters", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L215-L269
[ "def", "matches_filters", "(", "self", ",", "node", ")", ":", "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" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.current_scope
node.Base: The current node relative to which all interaction will be scoped.
capybara/session.py
def current_scope(self): """ node.Base: The current node relative to which all interaction will be scoped. """ scope = self._scopes[-1] if scope in [None, "frame"]: scope = self.document return scope
def current_scope(self): """ node.Base: The current node relative to which all interaction will be scoped. """ scope = self._scopes[-1] if scope in [None, "frame"]: scope = self.document return scope
[ "node", ".", "Base", ":", "The", "current", "node", "relative", "to", "which", "all", "interaction", "will", "be", "scoped", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L93-L98
[ "def", "current_scope", "(", "self", ")", ":", "scope", "=", "self", ".", "_scopes", "[", "-", "1", "]", "if", "scope", "in", "[", "None", ",", "\"frame\"", "]", ":", "scope", "=", "self", ".", "document", "return", "scope" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.current_path
str: Path of the current page, without any domain information.
capybara/session.py
def current_path(self): """ str: Path of the current page, without any domain information. """ if not self.current_url: return path = urlparse(self.current_url).path return path if path else None
def current_path(self): """ str: Path of the current page, without any domain information. """ if not self.current_url: return path = urlparse(self.current_url).path return path if path else None
[ "str", ":", "Path", "of", "the", "current", "page", "without", "any", "domain", "information", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L112-L119
[ "def", "current_path", "(", "self", ")", ":", "if", "not", "self", ".", "current_url", ":", "return", "path", "=", "urlparse", "(", "self", ".", "current_url", ")", ".", "path", "return", "path", "if", "path", "else", "None" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.current_host
str: Host of the current page.
capybara/session.py
def current_host(self): """ str: Host of the current page. """ if not self.current_url: return result = urlparse(self.current_url) scheme, netloc = result.scheme, result.netloc host = netloc.split(":")[0] if netloc else None return "{0}://{1}".format(scheme, host) if host else None
def current_host(self): """ str: Host of the current page. """ if not self.current_url: return result = urlparse(self.current_url) scheme, netloc = result.scheme, result.netloc host = netloc.split(":")[0] if netloc else None return "{0}://{1}".format(scheme, host) if host else None
[ "str", ":", "Host", "of", "the", "current", "page", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L122-L131
[ "def", "current_host", "(", "self", ")", ":", "if", "not", "self", ".", "current_url", ":", "return", "result", "=", "urlparse", "(", "self", ".", "current_url", ")", "scheme", ",", "netloc", "=", "result", ".", "scheme", ",", "result", ".", "netloc", "host", "=", "netloc", ".", "split", "(", "\":\"", ")", "[", "0", "]", "if", "netloc", "else", "None", "return", "\"{0}://{1}\"", ".", "format", "(", "scheme", ",", "host", ")", "if", "host", "else", "None" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.visit
Navigate to the given URL. The URL can either be a relative URL or an absolute URL. The behavior of either depends on the driver. :: session.visit("/foo") session.visit("http://google.com") For drivers which can run against an external application, such as the Selenium driver, giving an absolute URL will navigate to that page. This allows testing applications running on remote servers. For these drivers, setting :data:`capybara.app_host` will make the remote server the default. For example:: capybara.app_host = "http://google.com" session.visit("/") # visits the Google homepage Args: visit_uri (str): The URL to navigate to.
capybara/session.py
def visit(self, visit_uri): """ Navigate to the given URL. The URL can either be a relative URL or an absolute URL. The behavior of either depends on the driver. :: session.visit("/foo") session.visit("http://google.com") For drivers which can run against an external application, such as the Selenium driver, giving an absolute URL will navigate to that page. This allows testing applications running on remote servers. For these drivers, setting :data:`capybara.app_host` will make the remote server the default. For example:: capybara.app_host = "http://google.com" session.visit("/") # visits the Google homepage Args: visit_uri (str): The URL to navigate to. """ self.raise_server_error() visit_uri = urlparse(visit_uri) if capybara.app_host: uri_base = urlparse(capybara.app_host) elif self.server: uri_base = urlparse("http://{}:{}".format(self.server.host, self.server.port)) else: uri_base = None visit_uri = ParseResult( scheme=visit_uri.scheme or (uri_base.scheme if uri_base else ""), netloc=visit_uri.netloc or (uri_base.netloc if uri_base else ""), path=visit_uri.path, params=visit_uri.params, query=visit_uri.query, fragment=visit_uri.fragment) self.driver.visit(visit_uri.geturl())
def visit(self, visit_uri): """ Navigate to the given URL. The URL can either be a relative URL or an absolute URL. The behavior of either depends on the driver. :: session.visit("/foo") session.visit("http://google.com") For drivers which can run against an external application, such as the Selenium driver, giving an absolute URL will navigate to that page. This allows testing applications running on remote servers. For these drivers, setting :data:`capybara.app_host` will make the remote server the default. For example:: capybara.app_host = "http://google.com" session.visit("/") # visits the Google homepage Args: visit_uri (str): The URL to navigate to. """ self.raise_server_error() visit_uri = urlparse(visit_uri) if capybara.app_host: uri_base = urlparse(capybara.app_host) elif self.server: uri_base = urlparse("http://{}:{}".format(self.server.host, self.server.port)) else: uri_base = None visit_uri = ParseResult( scheme=visit_uri.scheme or (uri_base.scheme if uri_base else ""), netloc=visit_uri.netloc or (uri_base.netloc if uri_base else ""), path=visit_uri.path, params=visit_uri.params, query=visit_uri.query, fragment=visit_uri.fragment) self.driver.visit(visit_uri.geturl())
[ "Navigate", "to", "the", "given", "URL", ".", "The", "URL", "can", "either", "be", "a", "relative", "URL", "or", "an", "absolute", "URL", ".", "The", "behavior", "of", "either", "depends", "on", "the", "driver", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L138-L177
[ "def", "visit", "(", "self", ",", "visit_uri", ")", ":", "self", ".", "raise_server_error", "(", ")", "visit_uri", "=", "urlparse", "(", "visit_uri", ")", "if", "capybara", ".", "app_host", ":", "uri_base", "=", "urlparse", "(", "capybara", ".", "app_host", ")", "elif", "self", ".", "server", ":", "uri_base", "=", "urlparse", "(", "\"http://{}:{}\"", ".", "format", "(", "self", ".", "server", ".", "host", ",", "self", ".", "server", ".", "port", ")", ")", "else", ":", "uri_base", "=", "None", "visit_uri", "=", "ParseResult", "(", "scheme", "=", "visit_uri", ".", "scheme", "or", "(", "uri_base", ".", "scheme", "if", "uri_base", "else", "\"\"", ")", ",", "netloc", "=", "visit_uri", ".", "netloc", "or", "(", "uri_base", ".", "netloc", "if", "uri_base", "else", "\"\"", ")", ",", "path", "=", "visit_uri", ".", "path", ",", "params", "=", "visit_uri", ".", "params", ",", "query", "=", "visit_uri", ".", "query", ",", "fragment", "=", "visit_uri", ".", "fragment", ")", "self", ".", "driver", ".", "visit", "(", "visit_uri", ".", "geturl", "(", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.scope
Executes the wrapped code within the context of a node. ``scope`` takes the same options as :meth:`find`. For the duration of the context, any command to Capybara will be handled as though it were scoped to the given element. :: with scope("xpath", "//div[@id='delivery-address']"): fill_in("Street", value="12 Main Street") Just as with :meth:`find`, if multiple elements match the selector given to ``scope``, an error will be raised, and just as with :meth:`find`, this behavior can be controlled through the ``match`` and ``exact`` options. It is possible to omit the first argument, in that case, the selector is assumed to be of the type set in :data:`capybara.default_selector`. :: with scope("div#delivery-address"): fill_in("Street", value="12 Main Street") Note that a lot of uses of ``scope`` can be replaced more succinctly with chaining:: find("div#delivery-address").fill_in("Street", value="12 Main Street") Args: *args: Variable length argument list for the call to :meth:`find`. **kwargs: Arbitrary keywords arguments for the call to :meth:`find`.
capybara/session.py
def scope(self, *args, **kwargs): """ Executes the wrapped code within the context of a node. ``scope`` takes the same options as :meth:`find`. For the duration of the context, any command to Capybara will be handled as though it were scoped to the given element. :: with scope("xpath", "//div[@id='delivery-address']"): fill_in("Street", value="12 Main Street") Just as with :meth:`find`, if multiple elements match the selector given to ``scope``, an error will be raised, and just as with :meth:`find`, this behavior can be controlled through the ``match`` and ``exact`` options. It is possible to omit the first argument, in that case, the selector is assumed to be of the type set in :data:`capybara.default_selector`. :: with scope("div#delivery-address"): fill_in("Street", value="12 Main Street") Note that a lot of uses of ``scope`` can be replaced more succinctly with chaining:: find("div#delivery-address").fill_in("Street", value="12 Main Street") Args: *args: Variable length argument list for the call to :meth:`find`. **kwargs: Arbitrary keywords arguments for the call to :meth:`find`. """ new_scope = args[0] if isinstance(args[0], Base) else self.find(*args, **kwargs) self._scopes.append(new_scope) try: yield finally: self._scopes.pop()
def scope(self, *args, **kwargs): """ Executes the wrapped code within the context of a node. ``scope`` takes the same options as :meth:`find`. For the duration of the context, any command to Capybara will be handled as though it were scoped to the given element. :: with scope("xpath", "//div[@id='delivery-address']"): fill_in("Street", value="12 Main Street") Just as with :meth:`find`, if multiple elements match the selector given to ``scope``, an error will be raised, and just as with :meth:`find`, this behavior can be controlled through the ``match`` and ``exact`` options. It is possible to omit the first argument, in that case, the selector is assumed to be of the type set in :data:`capybara.default_selector`. :: with scope("div#delivery-address"): fill_in("Street", value="12 Main Street") Note that a lot of uses of ``scope`` can be replaced more succinctly with chaining:: find("div#delivery-address").fill_in("Street", value="12 Main Street") Args: *args: Variable length argument list for the call to :meth:`find`. **kwargs: Arbitrary keywords arguments for the call to :meth:`find`. """ new_scope = args[0] if isinstance(args[0], Base) else self.find(*args, **kwargs) self._scopes.append(new_scope) try: yield finally: self._scopes.pop()
[ "Executes", "the", "wrapped", "code", "within", "the", "context", "of", "a", "node", ".", "scope", "takes", "the", "same", "options", "as", ":", "meth", ":", "find", ".", "For", "the", "duration", "of", "the", "context", "any", "command", "to", "Capybara", "will", "be", "handled", "as", "though", "it", "were", "scoped", "to", "the", "given", "element", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L193-L226
[ "def", "scope", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_scope", "=", "args", "[", "0", "]", "if", "isinstance", "(", "args", "[", "0", "]", ",", "Base", ")", "else", "self", ".", "find", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_scopes", ".", "append", "(", "new_scope", ")", "try", ":", "yield", "finally", ":", "self", ".", "_scopes", ".", "pop", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.frame
Execute the wrapped code within the given iframe using the given frame or frame name/id. May not be supported by all drivers. Args: locator (str | Element, optional): The name/id of the frame or the frame's element. Defaults to the only frame in the document.
capybara/session.py
def frame(self, locator=None, *args, **kwargs): """ Execute the wrapped code within the given iframe using the given frame or frame name/id. May not be supported by all drivers. Args: locator (str | Element, optional): The name/id of the frame or the frame's element. Defaults to the only frame in the document. """ self.switch_to_frame(self._find_frame(locator, *args, **kwargs)) try: yield finally: self.switch_to_frame("parent")
def frame(self, locator=None, *args, **kwargs): """ Execute the wrapped code within the given iframe using the given frame or frame name/id. May not be supported by all drivers. Args: locator (str | Element, optional): The name/id of the frame or the frame's element. Defaults to the only frame in the document. """ self.switch_to_frame(self._find_frame(locator, *args, **kwargs)) try: yield finally: self.switch_to_frame("parent")
[ "Execute", "the", "wrapped", "code", "within", "the", "given", "iframe", "using", "the", "given", "frame", "or", "frame", "name", "/", "id", ".", "May", "not", "be", "supported", "by", "all", "drivers", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L254-L268
[ "def", "frame", "(", "self", ",", "locator", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "switch_to_frame", "(", "self", ".", "_find_frame", "(", "locator", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "try", ":", "yield", "finally", ":", "self", ".", "switch_to_frame", "(", "\"parent\"", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.switch_to_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.
capybara/session.py
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")
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")
[ "Switch", "to", "the", "given", "frame", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L308-L340
[ "def", "switch_to_frame", "(", "self", ",", "frame", ")", ":", "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\"", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.switch_to_window
If ``window`` is a lambda, it switches to the first window for which ``window`` returns a value other than False or None. If a window that matches can't be found, the window will be switched back and :exc:`WindowError` will be raised. Args: window (Window | lambda): The window that should be switched to, or a filtering lambda. wait (int | float, optional): The number of seconds to wait to find the window. Returns: Window: The new current window. Raises: ScopeError: If this method is invoked inside :meth:`scope, :meth:`frame`, or :meth:`window`. WindowError: If no window matches the given lambda.
capybara/session.py
def switch_to_window(self, window, wait=None): """ If ``window`` is a lambda, it switches to the first window for which ``window`` returns a value other than False or None. If a window that matches can't be found, the window will be switched back and :exc:`WindowError` will be raised. Args: window (Window | lambda): The window that should be switched to, or a filtering lambda. wait (int | float, optional): The number of seconds to wait to find the window. Returns: Window: The new current window. Raises: ScopeError: If this method is invoked inside :meth:`scope, :meth:`frame`, or :meth:`window`. WindowError: If no window matches the given lambda. """ if len(self._scopes) > 1: raise ScopeError( "`switch_to_window` is not supposed to be invoked from " "within `scope`s, `frame`s, or other `window`s.") if isinstance(window, Window): self.driver.switch_to_window(window.handle) return window else: @self.document.synchronize(errors=(WindowError,), wait=wait) def switch_and_get_matching_window(): original_window_handle = self.driver.current_window_handle try: for handle in self.driver.window_handles: self.driver.switch_to_window(handle) result = window() if result: return Window(self, handle) except Exception: self.driver.switch_to_window(original_window_handle) raise self.driver.switch_to_window(original_window_handle) raise WindowError("Could not find a window matching lambda") return switch_and_get_matching_window()
def switch_to_window(self, window, wait=None): """ If ``window`` is a lambda, it switches to the first window for which ``window`` returns a value other than False or None. If a window that matches can't be found, the window will be switched back and :exc:`WindowError` will be raised. Args: window (Window | lambda): The window that should be switched to, or a filtering lambda. wait (int | float, optional): The number of seconds to wait to find the window. Returns: Window: The new current window. Raises: ScopeError: If this method is invoked inside :meth:`scope, :meth:`frame`, or :meth:`window`. WindowError: If no window matches the given lambda. """ if len(self._scopes) > 1: raise ScopeError( "`switch_to_window` is not supposed to be invoked from " "within `scope`s, `frame`s, or other `window`s.") if isinstance(window, Window): self.driver.switch_to_window(window.handle) return window else: @self.document.synchronize(errors=(WindowError,), wait=wait) def switch_and_get_matching_window(): original_window_handle = self.driver.current_window_handle try: for handle in self.driver.window_handles: self.driver.switch_to_window(handle) result = window() if result: return Window(self, handle) except Exception: self.driver.switch_to_window(original_window_handle) raise self.driver.switch_to_window(original_window_handle) raise WindowError("Could not find a window matching lambda") return switch_and_get_matching_window()
[ "If", "window", "is", "a", "lambda", "it", "switches", "to", "the", "first", "window", "for", "which", "window", "returns", "a", "value", "other", "than", "False", "or", "None", ".", "If", "a", "window", "that", "matches", "can", "t", "be", "found", "the", "window", "will", "be", "switched", "back", "and", ":", "exc", ":", "WindowError", "will", "be", "raised", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L342-L386
[ "def", "switch_to_window", "(", "self", ",", "window", ",", "wait", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_scopes", ")", ">", "1", ":", "raise", "ScopeError", "(", "\"`switch_to_window` is not supposed to be invoked from \"", "\"within `scope`s, `frame`s, or other `window`s.\"", ")", "if", "isinstance", "(", "window", ",", "Window", ")", ":", "self", ".", "driver", ".", "switch_to_window", "(", "window", ".", "handle", ")", "return", "window", "else", ":", "@", "self", ".", "document", ".", "synchronize", "(", "errors", "=", "(", "WindowError", ",", ")", ",", "wait", "=", "wait", ")", "def", "switch_and_get_matching_window", "(", ")", ":", "original_window_handle", "=", "self", ".", "driver", ".", "current_window_handle", "try", ":", "for", "handle", "in", "self", ".", "driver", ".", "window_handles", ":", "self", ".", "driver", ".", "switch_to_window", "(", "handle", ")", "result", "=", "window", "(", ")", "if", "result", ":", "return", "Window", "(", "self", ",", "handle", ")", "except", "Exception", ":", "self", ".", "driver", ".", "switch_to_window", "(", "original_window_handle", ")", "raise", "self", ".", "driver", ".", "switch_to_window", "(", "original_window_handle", ")", "raise", "WindowError", "(", "\"Could not find a window matching lambda\"", ")", "return", "switch_and_get_matching_window", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.window
This method does the following: 1. Switches to the given window (it can be located by window instance/lambda/string). 2. Executes the given block (within window located at previous step). 3. Switches back (this step will be invoked even if exception happens at second step). Args: window (Window | lambda): The desired :class:`Window`, or a lambda that will be run in the context of each open window and returns ``True`` for the desired window.
capybara/session.py
def window(self, window): """ This method does the following: 1. Switches to the given window (it can be located by window instance/lambda/string). 2. Executes the given block (within window located at previous step). 3. Switches back (this step will be invoked even if exception happens at second step). Args: window (Window | lambda): The desired :class:`Window`, or a lambda that will be run in the context of each open window and returns ``True`` for the desired window. """ original = self.current_window if window != original: self.switch_to_window(window) self._scopes.append(None) try: yield finally: self._scopes.pop() if original != window: self.switch_to_window(original)
def window(self, window): """ This method does the following: 1. Switches to the given window (it can be located by window instance/lambda/string). 2. Executes the given block (within window located at previous step). 3. Switches back (this step will be invoked even if exception happens at second step). Args: window (Window | lambda): The desired :class:`Window`, or a lambda that will be run in the context of each open window and returns ``True`` for the desired window. """ original = self.current_window if window != original: self.switch_to_window(window) self._scopes.append(None) try: yield finally: self._scopes.pop() if original != window: self.switch_to_window(original)
[ "This", "method", "does", "the", "following", ":" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L389-L411
[ "def", "window", "(", "self", ",", "window", ")", ":", "original", "=", "self", ".", "current_window", "if", "window", "!=", "original", ":", "self", ".", "switch_to_window", "(", "window", ")", "self", ".", "_scopes", ".", "append", "(", "None", ")", "try", ":", "yield", "finally", ":", "self", ".", "_scopes", ".", "pop", "(", ")", "if", "original", "!=", "window", ":", "self", ".", "switch_to_window", "(", "original", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.window_opened_by
Get the window that has been opened by the passed lambda. It will wait for it to be opened (in the same way as other Capybara methods wait). It's better to use this method than ``windows[-1]`` `as order of windows isn't defined in some drivers`__. __ https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 Args: trigger_func (func): The function that should trigger the opening of a new window. wait (int | float, optional): Maximum wait time. Defaults to :data:`capybara.default_max_wait_time`. Returns: Window: The window that has been opened within the lambda. Raises: WindowError: If lambda passed to window hasn't opened window or opened more than one window.
capybara/session.py
def window_opened_by(self, trigger_func, wait=None): """ Get the window that has been opened by the passed lambda. It will wait for it to be opened (in the same way as other Capybara methods wait). It's better to use this method than ``windows[-1]`` `as order of windows isn't defined in some drivers`__. __ https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 Args: trigger_func (func): The function that should trigger the opening of a new window. wait (int | float, optional): Maximum wait time. Defaults to :data:`capybara.default_max_wait_time`. Returns: Window: The window that has been opened within the lambda. Raises: WindowError: If lambda passed to window hasn't opened window or opened more than one window. """ old_handles = set(self.driver.window_handles) trigger_func() @self.document.synchronize(wait=wait, errors=(WindowError,)) def get_new_window(): opened_handles = set(self.driver.window_handles) - old_handles if len(opened_handles) != 1: raise WindowError("lambda passed to `window_opened_by` " "opened {0} windows instead of 1".format(len(opened_handles))) return Window(self, list(opened_handles)[0]) return get_new_window()
def window_opened_by(self, trigger_func, wait=None): """ Get the window that has been opened by the passed lambda. It will wait for it to be opened (in the same way as other Capybara methods wait). It's better to use this method than ``windows[-1]`` `as order of windows isn't defined in some drivers`__. __ https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 Args: trigger_func (func): The function that should trigger the opening of a new window. wait (int | float, optional): Maximum wait time. Defaults to :data:`capybara.default_max_wait_time`. Returns: Window: The window that has been opened within the lambda. Raises: WindowError: If lambda passed to window hasn't opened window or opened more than one window. """ old_handles = set(self.driver.window_handles) trigger_func() @self.document.synchronize(wait=wait, errors=(WindowError,)) def get_new_window(): opened_handles = set(self.driver.window_handles) - old_handles if len(opened_handles) != 1: raise WindowError("lambda passed to `window_opened_by` " "opened {0} windows instead of 1".format(len(opened_handles))) return Window(self, list(opened_handles)[0]) return get_new_window()
[ "Get", "the", "window", "that", "has", "been", "opened", "by", "the", "passed", "lambda", ".", "It", "will", "wait", "for", "it", "to", "be", "opened", "(", "in", "the", "same", "way", "as", "other", "Capybara", "methods", "wait", ")", ".", "It", "s", "better", "to", "use", "this", "method", "than", "windows", "[", "-", "1", "]", "as", "order", "of", "windows", "isn", "t", "defined", "in", "some", "drivers", "__", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L413-L445
[ "def", "window_opened_by", "(", "self", ",", "trigger_func", ",", "wait", "=", "None", ")", ":", "old_handles", "=", "set", "(", "self", ".", "driver", ".", "window_handles", ")", "trigger_func", "(", ")", "@", "self", ".", "document", ".", "synchronize", "(", "wait", "=", "wait", ",", "errors", "=", "(", "WindowError", ",", ")", ")", "def", "get_new_window", "(", ")", ":", "opened_handles", "=", "set", "(", "self", ".", "driver", ".", "window_handles", ")", "-", "old_handles", "if", "len", "(", "opened_handles", ")", "!=", "1", ":", "raise", "WindowError", "(", "\"lambda passed to `window_opened_by` \"", "\"opened {0} windows instead of 1\"", ".", "format", "(", "len", "(", "opened_handles", ")", ")", ")", "return", "Window", "(", "self", ",", "list", "(", "opened_handles", ")", "[", "0", "]", ")", "return", "get_new_window", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.execute_script
Execute the given script, not returning a result. This is useful for scripts that return complex objects, such as jQuery statements. ``execute_script`` should be used over :meth:`evaluate_script` whenever possible. Args: script (str): A string of JavaScript to execute. *args: Variable length argument list to pass to the executed JavaScript string.
capybara/session.py
def execute_script(self, script, *args): """ Execute the given script, not returning a result. This is useful for scripts that return complex objects, such as jQuery statements. ``execute_script`` should be used over :meth:`evaluate_script` whenever possible. Args: script (str): A string of JavaScript to execute. *args: Variable length argument list to pass to the executed JavaScript string. """ args = [arg.base if isinstance(arg, Base) else arg for arg in args] self.driver.execute_script(script, *args)
def execute_script(self, script, *args): """ Execute the given script, not returning a result. This is useful for scripts that return complex objects, such as jQuery statements. ``execute_script`` should be used over :meth:`evaluate_script` whenever possible. Args: script (str): A string of JavaScript to execute. *args: Variable length argument list to pass to the executed JavaScript string. """ args = [arg.base if isinstance(arg, Base) else arg for arg in args] self.driver.execute_script(script, *args)
[ "Execute", "the", "given", "script", "not", "returning", "a", "result", ".", "This", "is", "useful", "for", "scripts", "that", "return", "complex", "objects", "such", "as", "jQuery", "statements", ".", "execute_script", "should", "be", "used", "over", ":", "meth", ":", "evaluate_script", "whenever", "possible", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L447-L459
[ "def", "execute_script", "(", "self", ",", "script", ",", "*", "args", ")", ":", "args", "=", "[", "arg", ".", "base", "if", "isinstance", "(", "arg", ",", "Base", ")", "else", "arg", "for", "arg", "in", "args", "]", "self", ".", "driver", ".", "execute_script", "(", "script", ",", "*", "args", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.evaluate_script
Evaluate the given JavaScript and return the result. Be careful when using this with scripts that return complex objects, such as jQuery statements. :meth:`execute_script` might be a better alternative. Args: script (str): A string of JavaScript to evaluate. *args: Variable length argument list to pass to the executed JavaScript string. Returns: object: The result of the evaluated JavaScript (may be driver specific).
capybara/session.py
def evaluate_script(self, script, *args): """ Evaluate the given JavaScript and return the result. Be careful when using this with scripts that return complex objects, such as jQuery statements. :meth:`execute_script` might be a better alternative. Args: script (str): A string of JavaScript to evaluate. *args: Variable length argument list to pass to the executed JavaScript string. Returns: object: The result of the evaluated JavaScript (may be driver specific). """ args = [arg.base if isinstance(arg, Base) else arg for arg in args] result = self.driver.evaluate_script(script, *args) return self._wrap_element_script_result(result)
def evaluate_script(self, script, *args): """ Evaluate the given JavaScript and return the result. Be careful when using this with scripts that return complex objects, such as jQuery statements. :meth:`execute_script` might be a better alternative. Args: script (str): A string of JavaScript to evaluate. *args: Variable length argument list to pass to the executed JavaScript string. Returns: object: The result of the evaluated JavaScript (may be driver specific). """ args = [arg.base if isinstance(arg, Base) else arg for arg in args] result = self.driver.evaluate_script(script, *args) return self._wrap_element_script_result(result)
[ "Evaluate", "the", "given", "JavaScript", "and", "return", "the", "result", ".", "Be", "careful", "when", "using", "this", "with", "scripts", "that", "return", "complex", "objects", "such", "as", "jQuery", "statements", ".", ":", "meth", ":", "execute_script", "might", "be", "a", "better", "alternative", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L461-L477
[ "def", "evaluate_script", "(", "self", ",", "script", ",", "*", "args", ")", ":", "args", "=", "[", "arg", ".", "base", "if", "isinstance", "(", "arg", ",", "Base", ")", "else", "arg", "for", "arg", "in", "args", "]", "result", "=", "self", ".", "driver", ".", "evaluate_script", "(", "script", ",", "*", "args", ")", "return", "self", ".", "_wrap_element_script_result", "(", "result", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.accept_alert
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.
capybara/session.py
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
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
[ "Execute", "the", "wrapped", "code", "accepting", "an", "alert", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L497-L512
[ "def", "accept_alert", "(", "self", ",", "text", "=", "None", ",", "wait", "=", "None", ")", ":", "wait", "=", "wait", "or", "capybara", ".", "default_max_wait_time", "with", "self", ".", "driver", ".", "accept_modal", "(", "\"alert\"", ",", "text", "=", "text", ",", "wait", "=", "wait", ")", ":", "yield" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.accept_confirm
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.
capybara/session.py
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
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
[ "Execute", "the", "wrapped", "code", "accepting", "a", "confirm", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L515-L529
[ "def", "accept_confirm", "(", "self", ",", "text", "=", "None", ",", "wait", "=", "None", ")", ":", "with", "self", ".", "driver", ".", "accept_modal", "(", "\"confirm\"", ",", "text", "=", "text", ",", "wait", "=", "wait", ")", ":", "yield" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.dismiss_confirm
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.
capybara/session.py
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
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
[ "Execute", "the", "wrapped", "code", "dismissing", "a", "confirm", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L532-L546
[ "def", "dismiss_confirm", "(", "self", ",", "text", "=", "None", ",", "wait", "=", "None", ")", ":", "with", "self", ".", "driver", ".", "dismiss_modal", "(", "\"confirm\"", ",", "text", "=", "text", ",", "wait", "=", "wait", ")", ":", "yield" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.accept_prompt
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.
capybara/session.py
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
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
[ "Execute", "the", "wrapped", "code", "accepting", "a", "prompt", "optionally", "responding", "to", "the", "prompt", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L549-L564
[ "def", "accept_prompt", "(", "self", ",", "text", "=", "None", ",", "response", "=", "None", ",", "wait", "=", "None", ")", ":", "with", "self", ".", "driver", ".", "accept_modal", "(", "\"prompt\"", ",", "text", "=", "text", ",", "response", "=", "response", ",", "wait", "=", "wait", ")", ":", "yield" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.dismiss_prompt
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.
capybara/session.py
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
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
[ "Execute", "the", "wrapped", "code", "dismissing", "a", "prompt", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L567-L581
[ "def", "dismiss_prompt", "(", "self", ",", "text", "=", "None", ",", "wait", "=", "None", ")", ":", "with", "self", ".", "driver", ".", "dismiss_modal", "(", "\"prompt\"", ",", "text", "=", "text", ",", "wait", "=", "wait", ")", ":", "yield" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.save_page
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.
capybara/session.py
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
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
[ "Save", "a", "snapshot", "of", "the", "page", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L583-L603
[ "def", "save_page", "(", "self", ",", "path", "=", "None", ")", ":", "path", "=", "_prepare_path", "(", "path", ",", "\"html\"", ")", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "f", ":", "f", ".", "write", "(", "encode_string", "(", "self", ".", "body", ")", ")", "return", "path" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.save_screenshot
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.
capybara/session.py
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
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
[ "Save", "a", "screenshot", "of", "the", "page", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L605-L623
[ "def", "save_screenshot", "(", "self", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "_prepare_path", "(", "path", ",", "\"png\"", ")", "self", ".", "driver", ".", "save_screenshot", "(", "path", ",", "*", "*", "kwargs", ")", "return", "path" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.reset
Reset the session (i.e., remove cookies and navigate to a blank page). This method does not: * accept modal dialogs if they are present (the Selenium driver does, but others may not), * clear the browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc., or * modify the state of the driver/underlying browser in any other way as doing so would result in performance downsides and it's not needed to do everything from the list above for most apps. If you want to do anything from the list above on a general basis you can write a test teardown method.
capybara/session.py
def reset(self): """ Reset the session (i.e., remove cookies and navigate to a blank page). This method does not: * accept modal dialogs if they are present (the Selenium driver does, but others may not), * clear the browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc., or * modify the state of the driver/underlying browser in any other way as doing so would result in performance downsides and it's not needed to do everything from the list above for most apps. If you want to do anything from the list above on a general basis you can write a test teardown method. """ self.driver.reset() if self.server: self.server.wait_for_pending_requests() self.raise_server_error()
def reset(self): """ Reset the session (i.e., remove cookies and navigate to a blank page). This method does not: * accept modal dialogs if they are present (the Selenium driver does, but others may not), * clear the browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc., or * modify the state of the driver/underlying browser in any other way as doing so would result in performance downsides and it's not needed to do everything from the list above for most apps. If you want to do anything from the list above on a general basis you can write a test teardown method. """ self.driver.reset() if self.server: self.server.wait_for_pending_requests() self.raise_server_error()
[ "Reset", "the", "session", "(", "i", ".", "e", ".", "remove", "cookies", "and", "navigate", "to", "a", "blank", "page", ")", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L625-L644
[ "def", "reset", "(", "self", ")", ":", "self", ".", "driver", ".", "reset", "(", ")", "if", "self", ".", "server", ":", "self", ".", "server", ".", "wait_for_pending_requests", "(", ")", "self", ".", "raise_server_error", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Session.raise_server_error
Raise errors encountered by the server.
capybara/session.py
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()
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()
[ "Raise", "errors", "encountered", "by", "the", "server", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/session.py#L646-L653
[ "def", "raise_server_error", "(", "self", ")", ":", "if", "self", ".", "server", "and", "self", ".", "server", ".", "error", ":", "try", ":", "if", "capybara", ".", "raise_server_errors", ":", "raise", "self", ".", "server", ".", "error", "finally", ":", "self", ".", "server", ".", "reset_error", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
NodeFilter.matches
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.
capybara/selector/node_filter.py
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)
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)
[ "Returns", "whether", "the", "given", "node", "matches", "the", "filter", "rule", "with", "the", "given", "value", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/node_filter.py#L7-L34
[ "def", "matches", "(", "self", ",", "node", ",", "value", ")", ":", "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", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
get_version
str: The package version.
setup.py
def get_version(): """ str: The package version. """ global_vars = {} # Compile and execute the individual file to prevent # the package from being automatically loaded. source = read(os.path.join("capybara", "version.py")) code = compile(source, "version.py", "exec") exec(code, global_vars) return global_vars['__version__']
def get_version(): """ str: The package version. """ global_vars = {} # Compile and execute the individual file to prevent # the package from being automatically loaded. source = read(os.path.join("capybara", "version.py")) code = compile(source, "version.py", "exec") exec(code, global_vars) return global_vars['__version__']
[ "str", ":", "The", "package", "version", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/setup.py#L41-L52
[ "def", "get_version", "(", ")", ":", "global_vars", "=", "{", "}", "# Compile and execute the individual file to prevent", "# the package from being automatically loaded.", "source", "=", "read", "(", "os", ".", "path", ".", "join", "(", "\"capybara\"", ",", "\"version.py\"", ")", ")", "code", "=", "compile", "(", "source", ",", "\"version.py\"", ",", "\"exec\"", ")", "exec", "(", "code", ",", "global_vars", ")", "return", "global_vars", "[", "'__version__'", "]" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
TitleQuery.resolves_for
Resolves this query relative to the given node. Args: node (node.Document): The node to be evaluated. Returns: bool: Whether the given node matches this query.
capybara/queries/title_query.py
def resolves_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Document): The node to be evaluated. Returns: bool: Whether the given node matches this query. """ self.actual_title = normalize_text(node.title) return bool(self.search_regexp.search(self.actual_title))
def resolves_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Document): The node to be evaluated. Returns: bool: Whether the given node matches this query. """ self.actual_title = normalize_text(node.title) return bool(self.search_regexp.search(self.actual_title))
[ "Resolves", "this", "query", "relative", "to", "the", "given", "node", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/title_query.py#L28-L40
[ "def", "resolves_for", "(", "self", ",", "node", ")", ":", "self", ".", "actual_title", "=", "normalize_text", "(", "node", ".", "title", ")", "return", "bool", "(", "self", ".", "search_regexp", ".", "search", "(", "self", ".", "actual_title", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Base.frame_title
str: The title for the current frame.
capybara/driver/base.py
def frame_title(self): """ str: The title for the current frame. """ elements = self._find_xpath("/html/head/title") titles = [element.all_text for element in elements] return titles[0] if len(titles) else ""
def frame_title(self): """ str: The title for the current frame. """ elements = self._find_xpath("/html/head/title") titles = [element.all_text for element in elements] return titles[0] if len(titles) else ""
[ "str", ":", "The", "title", "for", "the", "current", "frame", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/driver/base.py#L38-L42
[ "def", "frame_title", "(", "self", ")", ":", "elements", "=", "self", ".", "_find_xpath", "(", "\"/html/head/title\"", ")", "titles", "=", "[", "element", ".", "all_text", "for", "element", "in", "elements", "]", "return", "titles", "[", "0", "]", "if", "len", "(", "titles", ")", "else", "\"\"" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
Simple.value
str: The value of the form element.
capybara/node/simple.py
def value(self): """ str: The value of the form element. """ if self.tag_name == "textarea": return inner_content(self.native) elif self.tag_name == "select": if self["multiple"] == "multiple": selected_options = self._find_xpath(".//option[@selected='selected']") return [_get_option_value(option) for option in selected_options] else: options = ( self._find_xpath(".//option[@selected='selected']") + self._find_xpath(".//option")) return _get_option_value(options[0]) if options else None elif self.tag_name == "input" and self["type"] in ["checkbox", "radio"]: return self["value"] or "on" else: return self["value"]
def value(self): """ str: The value of the form element. """ if self.tag_name == "textarea": return inner_content(self.native) elif self.tag_name == "select": if self["multiple"] == "multiple": selected_options = self._find_xpath(".//option[@selected='selected']") return [_get_option_value(option) for option in selected_options] else: options = ( self._find_xpath(".//option[@selected='selected']") + self._find_xpath(".//option")) return _get_option_value(options[0]) if options else None elif self.tag_name == "input" and self["type"] in ["checkbox", "radio"]: return self["value"] or "on" else: return self["value"]
[ "str", ":", "The", "value", "of", "the", "form", "element", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/simple.py#L60-L77
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "tag_name", "==", "\"textarea\"", ":", "return", "inner_content", "(", "self", ".", "native", ")", "elif", "self", ".", "tag_name", "==", "\"select\"", ":", "if", "self", "[", "\"multiple\"", "]", "==", "\"multiple\"", ":", "selected_options", "=", "self", ".", "_find_xpath", "(", "\".//option[@selected='selected']\"", ")", "return", "[", "_get_option_value", "(", "option", ")", "for", "option", "in", "selected_options", "]", "else", ":", "options", "=", "(", "self", ".", "_find_xpath", "(", "\".//option[@selected='selected']\"", ")", "+", "self", ".", "_find_xpath", "(", "\".//option\"", ")", ")", "return", "_get_option_value", "(", "options", "[", "0", "]", ")", "if", "options", "else", "None", "elif", "self", ".", "tag_name", "==", "\"input\"", "and", "self", "[", "\"type\"", "]", "in", "[", "\"checkbox\"", ",", "\"radio\"", "]", ":", "return", "self", "[", "\"value\"", "]", "or", "\"on\"", "else", ":", "return", "self", "[", "\"value\"", "]" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
add_filter_set
Builds and registers a global :class:`FilterSet`. Args: name (str): The name of the set. Yields: FilterSetFactory: A configurable factory for building a :class:`FilterSet`.
capybara/selector/filter_set.py
def add_filter_set(name): """ Builds and registers a global :class:`FilterSet`. Args: name (str): The name of the set. Yields: FilterSetFactory: A configurable factory for building a :class:`FilterSet`. """ factory = FilterSetFactory(name) yield factory filter_sets[name] = factory.build_filter_set()
def add_filter_set(name): """ Builds and registers a global :class:`FilterSet`. Args: name (str): The name of the set. Yields: FilterSetFactory: A configurable factory for building a :class:`FilterSet`. """ factory = FilterSetFactory(name) yield factory filter_sets[name] = factory.build_filter_set()
[ "Builds", "and", "registers", "a", "global", ":", "class", ":", "FilterSet", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/filter_set.py#L89-L102
[ "def", "add_filter_set", "(", "name", ")", ":", "factory", "=", "FilterSetFactory", "(", "name", ")", "yield", "factory", "filter_sets", "[", "name", "]", "=", "factory", ".", "build_filter_set", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
current_session
Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app.
capybara/__init__.py
def current_session(): """ Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app. """ driver = current_driver or default_driver session_key = "{driver}:{session}:{app}".format( driver=driver, session=session_name, app=str(id(app))) session = _session_pool.get(session_key, None) if session is None: from capybara.session import Session session = Session(driver, app) _session_pool[session_key] = session return session
def current_session(): """ Returns the :class:`Session` for the current driver and app, instantiating one if needed. Returns: Session: The :class:`Session` for the current driver and app. """ driver = current_driver or default_driver session_key = "{driver}:{session}:{app}".format( driver=driver, session=session_name, app=str(id(app))) session = _session_pool.get(session_key, None) if session is None: from capybara.session import Session session = Session(driver, app) _session_pool[session_key] = session return session
[ "Returns", "the", ":", "class", ":", "Session", "for", "the", "current", "driver", "and", "app", "instantiating", "one", "if", "needed", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/__init__.py#L170-L189
[ "def", "current_session", "(", ")", ":", "driver", "=", "current_driver", "or", "default_driver", "session_key", "=", "\"{driver}:{session}:{app}\"", ".", "format", "(", "driver", "=", "driver", ",", "session", "=", "session_name", ",", "app", "=", "str", "(", "id", "(", "app", ")", ")", ")", "session", "=", "_session_pool", ".", "get", "(", "session_key", ",", "None", ")", "if", "session", "is", "None", ":", "from", "capybara", ".", "session", "import", "Session", "session", "=", "Session", "(", "driver", ",", "app", ")", "_session_pool", "[", "session_key", "]", "=", "session", "return", "session" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.has_all_of_selectors
Checks if allof the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_all_of_selectors("custom", "Tom", "Joe", visible="all") page.has_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
capybara/node/matchers.py
def has_all_of_selectors(self, selector, *locators, **kwargs): """ Checks if allof the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_all_of_selectors("custom", "Tom", "Joe", visible="all") page.has_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ return self.assert_all_of_selectors(selector, *locators, **kwargs)
def has_all_of_selectors(self, selector, *locators, **kwargs): """ Checks if allof the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_all_of_selectors("custom", "Tom", "Joe", visible="all") page.has_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ return self.assert_all_of_selectors(selector, *locators, **kwargs)
[ "Checks", "if", "allof", "the", "provided", "selectors", "are", "present", "on", "the", "given", "page", "or", "descendants", "of", "the", "current", "node", ".", "If", "options", "are", "provided", "the", "assertion", "will", "check", "that", "each", "locator", "is", "present", "with", "those", "options", "as", "well", "(", "other", "than", "wait", ")", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L97-L121
[ "def", "has_all_of_selectors", "(", "self", ",", "selector", ",", "*", "locators", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "assert_all_of_selectors", "(", "selector", ",", "*", "locators", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.has_none_of_selectors
Checks if none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_none_of_selectors("custom", "Tom", "Joe", visible="all") page.has_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
capybara/node/matchers.py
def has_none_of_selectors(self, selector, *locators, **kwargs): """ Checks if none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_none_of_selectors("custom", "Tom", "Joe", visible="all") page.has_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ return self.assert_none_of_selectors(selector, *locators, **kwargs)
def has_none_of_selectors(self, selector, *locators, **kwargs): """ Checks if none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.has_none_of_selectors("custom", "Tom", "Joe", visible="all") page.has_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ return self.assert_none_of_selectors(selector, *locators, **kwargs)
[ "Checks", "if", "none", "of", "the", "provided", "selectors", "are", "present", "on", "the", "given", "page", "or", "descendants", "of", "the", "current", "node", ".", "If", "options", "are", "provided", "the", "assertion", "will", "check", "that", "each", "locator", "is", "present", "with", "those", "options", "as", "well", "(", "other", "than", "wait", ")", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L124-L148
[ "def", "has_none_of_selectors", "(", "self", ",", "selector", ",", "*", "locators", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "assert_none_of_selectors", "(", "selector", ",", "*", "locators", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_selector
Asserts that a given selector is on the page or a descendant of the current node. :: page.assert_selector("p#foo") By default it will check if the expression occurs at least once, but a different number can be specified. :: page.assert_selector("p.foo", count=4) This will check if the expression occurs exactly 4 times. See :meth:`find_all` for other available result size options. If a ``count`` of 0 is specified, it will behave like :meth:`assert_no_selector`; however, use of that method is preferred over this one. It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: page.assert_selector("li", text="Horse", visible=True) ``assert_selector`` can also accept XPath expressions generated by the ``xpath-py`` package:: from xpath import dsl as x page.assert_selector("xpath", x.descendant("p")) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector did not match.
capybara/node/matchers.py
def assert_selector(self, *args, **kwargs): """ Asserts that a given selector is on the page or a descendant of the current node. :: page.assert_selector("p#foo") By default it will check if the expression occurs at least once, but a different number can be specified. :: page.assert_selector("p.foo", count=4) This will check if the expression occurs exactly 4 times. See :meth:`find_all` for other available result size options. If a ``count`` of 0 is specified, it will behave like :meth:`assert_no_selector`; however, use of that method is preferred over this one. It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: page.assert_selector("li", text="Horse", visible=True) ``assert_selector`` can also accept XPath expressions generated by the ``xpath-py`` package:: from xpath import dsl as x page.assert_selector("xpath", x.descendant("p")) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector did not match. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_selector(): result = query.resolve_for(self) if not (result.matches_count and (len(result) > 0 or expects_none(query.options))): raise ExpectationNotMet(result.failure_message) return True return assert_selector()
def assert_selector(self, *args, **kwargs): """ Asserts that a given selector is on the page or a descendant of the current node. :: page.assert_selector("p#foo") By default it will check if the expression occurs at least once, but a different number can be specified. :: page.assert_selector("p.foo", count=4) This will check if the expression occurs exactly 4 times. See :meth:`find_all` for other available result size options. If a ``count`` of 0 is specified, it will behave like :meth:`assert_no_selector`; however, use of that method is preferred over this one. It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: page.assert_selector("li", text="Horse", visible=True) ``assert_selector`` can also accept XPath expressions generated by the ``xpath-py`` package:: from xpath import dsl as x page.assert_selector("xpath", x.descendant("p")) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector did not match. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_selector(): result = query.resolve_for(self) if not (result.matches_count and (len(result) > 0 or expects_none(query.options))): raise ExpectationNotMet(result.failure_message) return True return assert_selector()
[ "Asserts", "that", "a", "given", "selector", "is", "on", "the", "page", "or", "a", "descendant", "of", "the", "current", "node", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L181-L233
[ "def", "assert_selector", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "SelectorQuery", "(", "*", "args", ",", "*", "*", "kwargs", ")", "@", "self", ".", "synchronize", "(", "wait", "=", "query", ".", "wait", ")", "def", "assert_selector", "(", ")", ":", "result", "=", "query", ".", "resolve_for", "(", "self", ")", "if", "not", "(", "result", ".", "matches_count", "and", "(", "len", "(", "result", ")", ">", "0", "or", "expects_none", "(", "query", ".", "options", ")", ")", ")", ":", "raise", "ExpectationNotMet", "(", "result", ".", "failure_message", ")", "return", "True", "return", "assert_selector", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_style
Asserts that an element has the specified CSS styles. :: element.assert_style({"color": "rgb(0,0,255)", "font-size": re.compile(r"px")}) Args: styles (Dict[str, str | RegexObject]): The expected styles. Returns: True Raises: ExpectationNotMet: The element doesn't have the specified styles.
capybara/node/matchers.py
def assert_style(self, styles, **kwargs): """ Asserts that an element has the specified CSS styles. :: element.assert_style({"color": "rgb(0,0,255)", "font-size": re.compile(r"px")}) Args: styles (Dict[str, str | RegexObject]): The expected styles. Returns: True Raises: ExpectationNotMet: The element doesn't have the specified styles. """ query = StyleQuery(styles, **kwargs) @self.synchronize(wait=query.wait) def assert_style(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) return True return assert_style()
def assert_style(self, styles, **kwargs): """ Asserts that an element has the specified CSS styles. :: element.assert_style({"color": "rgb(0,0,255)", "font-size": re.compile(r"px")}) Args: styles (Dict[str, str | RegexObject]): The expected styles. Returns: True Raises: ExpectationNotMet: The element doesn't have the specified styles. """ query = StyleQuery(styles, **kwargs) @self.synchronize(wait=query.wait) def assert_style(): if not query.resolves_for(self): raise ExpectationNotMet(query.failure_message) return True return assert_style()
[ "Asserts", "that", "an", "element", "has", "the", "specified", "CSS", "styles", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L235-L260
[ "def", "assert_style", "(", "self", ",", "styles", ",", "*", "*", "kwargs", ")", ":", "query", "=", "StyleQuery", "(", "styles", ",", "*", "*", "kwargs", ")", "@", "self", ".", "synchronize", "(", "wait", "=", "query", ".", "wait", ")", "def", "assert_style", "(", ")", ":", "if", "not", "query", ".", "resolves_for", "(", "self", ")", ":", "raise", "ExpectationNotMet", "(", "query", ".", "failure_message", ")", "return", "True", "return", "assert_style", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_all_of_selectors
Asserts that all of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_all_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
capybara/node/matchers.py
def assert_all_of_selectors(self, selector, *locators, **kwargs): """ Asserts that all of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_all_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ wait = kwargs['wait'] if 'wait' in kwargs else capybara.default_max_wait_time if not isinstance(selector, Hashable) or selector not in selectors: locators = (selector,) + locators selector = capybara.default_selector @self.synchronize(wait=wait) def assert_all_of_selectors(): for locator in locators: self.assert_selector(selector, locator, **kwargs) return True return assert_all_of_selectors()
def assert_all_of_selectors(self, selector, *locators, **kwargs): """ Asserts that all of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_all_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_all_of_selectors("css", "#my_dif", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so all of the locators must be present within ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ wait = kwargs['wait'] if 'wait' in kwargs else capybara.default_max_wait_time if not isinstance(selector, Hashable) or selector not in selectors: locators = (selector,) + locators selector = capybara.default_selector @self.synchronize(wait=wait) def assert_all_of_selectors(): for locator in locators: self.assert_selector(selector, locator, **kwargs) return True return assert_all_of_selectors()
[ "Asserts", "that", "all", "of", "the", "provided", "selectors", "are", "present", "on", "the", "given", "page", "or", "descendants", "of", "the", "current", "node", ".", "If", "options", "are", "provided", "the", "assertion", "will", "check", "that", "each", "locator", "is", "present", "with", "those", "options", "as", "well", "(", "other", "than", "wait", ")", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L262-L299
[ "def", "assert_all_of_selectors", "(", "self", ",", "selector", ",", "*", "locators", ",", "*", "*", "kwargs", ")", ":", "wait", "=", "kwargs", "[", "'wait'", "]", "if", "'wait'", "in", "kwargs", "else", "capybara", ".", "default_max_wait_time", "if", "not", "isinstance", "(", "selector", ",", "Hashable", ")", "or", "selector", "not", "in", "selectors", ":", "locators", "=", "(", "selector", ",", ")", "+", "locators", "selector", "=", "capybara", ".", "default_selector", "@", "self", ".", "synchronize", "(", "wait", "=", "wait", ")", "def", "assert_all_of_selectors", "(", ")", ":", "for", "locator", "in", "locators", ":", "self", ".", "assert_selector", "(", "selector", ",", "locator", ",", "*", "*", "kwargs", ")", "return", "True", "return", "assert_all_of_selectors", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_none_of_selectors
Asserts that none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_none_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
capybara/node/matchers.py
def assert_none_of_selectors(self, selector, *locators, **kwargs): """ Asserts that none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_none_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ wait = kwargs['wait'] if 'wait' in kwargs else capybara.default_max_wait_time if not isinstance(selector, Hashable) or selector not in selectors: locators = (selector,) + locators selector = capybara.default_selector @self.synchronize(wait=wait) def assert_none_of_selectors(): for locator in locators: self.assert_no_selector(selector, locator, **kwargs) return True return assert_none_of_selectors()
def assert_none_of_selectors(self, selector, *locators, **kwargs): """ Asserts that none of the provided selectors are present on the given page or descendants of the current node. If options are provided, the assertion will check that each locator is present with those options as well (other than ``wait``). :: page.assert_none_of_selectors("custom", "Tom", "Joe", visible="all") page.assert_none_of_selectors("css", "#my_div", "a.not_clicked") It accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. The ``wait`` option applies to all of the selectors as a group, so none of the locators must be present with ``wait`` (defaults to :data:`capybara.default_max_wait_time`) seconds. If the given selector is not a valid selector, the first argument is assumed to be a locator and the default selector will be used. Args: selector (str, optional): The name of the selector to use. Defaults to :data:`capybara.default_selector`. *locators (str): Variable length list of locators. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. """ wait = kwargs['wait'] if 'wait' in kwargs else capybara.default_max_wait_time if not isinstance(selector, Hashable) or selector not in selectors: locators = (selector,) + locators selector = capybara.default_selector @self.synchronize(wait=wait) def assert_none_of_selectors(): for locator in locators: self.assert_no_selector(selector, locator, **kwargs) return True return assert_none_of_selectors()
[ "Asserts", "that", "none", "of", "the", "provided", "selectors", "are", "present", "on", "the", "given", "page", "or", "descendants", "of", "the", "current", "node", ".", "If", "options", "are", "provided", "the", "assertion", "will", "check", "that", "each", "locator", "is", "present", "with", "those", "options", "as", "well", "(", "other", "than", "wait", ")", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L301-L337
[ "def", "assert_none_of_selectors", "(", "self", ",", "selector", ",", "*", "locators", ",", "*", "*", "kwargs", ")", ":", "wait", "=", "kwargs", "[", "'wait'", "]", "if", "'wait'", "in", "kwargs", "else", "capybara", ".", "default_max_wait_time", "if", "not", "isinstance", "(", "selector", ",", "Hashable", ")", "or", "selector", "not", "in", "selectors", ":", "locators", "=", "(", "selector", ",", ")", "+", "locators", "selector", "=", "capybara", ".", "default_selector", "@", "self", ".", "synchronize", "(", "wait", "=", "wait", ")", "def", "assert_none_of_selectors", "(", ")", ":", "for", "locator", "in", "locators", ":", "self", ".", "assert_no_selector", "(", "selector", ",", "locator", ",", "*", "*", "kwargs", ")", "return", "True", "return", "assert_none_of_selectors", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_no_selector
Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to :meth:`assert_selector`. Query options such as ``count``, ``minimum``, and ``between`` are considered to be an integral part of the selector. This will return True, for example, if a page contains 4 anchors but the query expects 5:: page.assert_no_selector("a", minimum=1) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=4) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=5) # Not Found, returns True Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector matched.
capybara/node/matchers.py
def assert_no_selector(self, *args, **kwargs): """ Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to :meth:`assert_selector`. Query options such as ``count``, ``minimum``, and ``between`` are considered to be an integral part of the selector. This will return True, for example, if a page contains 4 anchors but the query expects 5:: page.assert_no_selector("a", minimum=1) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=4) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=5) # Not Found, returns True Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector matched. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_no_selector(): result = query.resolve_for(self) if result.matches_count and ( len(result) > 0 or expects_none(query.options)): raise ExpectationNotMet(result.negative_failure_message) return True return assert_no_selector()
def assert_no_selector(self, *args, **kwargs): """ Asserts that a given selector is not on the page or a descendant of the current node. Usage is identical to :meth:`assert_selector`. Query options such as ``count``, ``minimum``, and ``between`` are considered to be an integral part of the selector. This will return True, for example, if a page contains 4 anchors but the query expects 5:: page.assert_no_selector("a", minimum=1) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=4) # Found, raises ExpectationNotMet page.assert_no_selector("a", count=5) # Not Found, returns True Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: The given selector matched. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_no_selector(): result = query.resolve_for(self) if result.matches_count and ( len(result) > 0 or expects_none(query.options)): raise ExpectationNotMet(result.negative_failure_message) return True return assert_no_selector()
[ "Asserts", "that", "a", "given", "selector", "is", "not", "on", "the", "page", "or", "a", "descendant", "of", "the", "current", "node", ".", "Usage", "is", "identical", "to", ":", "meth", ":", "assert_selector", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L339-L375
[ "def", "assert_no_selector", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "SelectorQuery", "(", "*", "args", ",", "*", "*", "kwargs", ")", "@", "self", ".", "synchronize", "(", "wait", "=", "query", ".", "wait", ")", "def", "assert_no_selector", "(", ")", ":", "result", "=", "query", ".", "resolve_for", "(", "self", ")", "if", "result", ".", "matches_count", "and", "(", "len", "(", "result", ")", ">", "0", "or", "expects_none", "(", "query", ".", "options", ")", ")", ":", "raise", "ExpectationNotMet", "(", "result", ".", "negative_failure_message", ")", "return", "True", "return", "assert_no_selector", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_matches_selector
Asserts that the current node matches a given selector. :: node.assert_matches_selector("p#foo") node.assert_matches_selector("xpath", "//p[@id='foo']") It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: node.assert_matches_selector("li", text="Horse", visible=True) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: If the selector does not match.
capybara/node/matchers.py
def assert_matches_selector(self, *args, **kwargs): """ Asserts that the current node matches a given selector. :: node.assert_matches_selector("p#foo") node.assert_matches_selector("xpath", "//p[@id='foo']") It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: node.assert_matches_selector("li", text="Horse", visible=True) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: If the selector does not match. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_matches_selector(): result = query.resolve_for(self.find_first("xpath", "./parent::*", minimum=0) or self.query_scope) if self not in result: raise ExpectationNotMet("Item does not match the provided selector") return True return assert_matches_selector()
def assert_matches_selector(self, *args, **kwargs): """ Asserts that the current node matches a given selector. :: node.assert_matches_selector("p#foo") node.assert_matches_selector("xpath", "//p[@id='foo']") It also accepts all options that :meth:`find_all` accepts, such as ``text`` and ``visible``. :: node.assert_matches_selector("li", text="Horse", visible=True) Args: *args: Variable length argument list for :class:`SelectorQuery`. **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`. Returns: True Raises: ExpectationNotMet: If the selector does not match. """ query = SelectorQuery(*args, **kwargs) @self.synchronize(wait=query.wait) def assert_matches_selector(): result = query.resolve_for(self.find_first("xpath", "./parent::*", minimum=0) or self.query_scope) if self not in result: raise ExpectationNotMet("Item does not match the provided selector") return True return assert_matches_selector()
[ "Asserts", "that", "the", "current", "node", "matches", "a", "given", "selector", ".", "::" ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L380-L414
[ "def", "assert_matches_selector", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "SelectorQuery", "(", "*", "args", ",", "*", "*", "kwargs", ")", "@", "self", ".", "synchronize", "(", "wait", "=", "query", ".", "wait", ")", "def", "assert_matches_selector", "(", ")", ":", "result", "=", "query", ".", "resolve_for", "(", "self", ".", "find_first", "(", "\"xpath\"", ",", "\"./parent::*\"", ",", "minimum", "=", "0", ")", "or", "self", ".", "query_scope", ")", "if", "self", "not", "in", "result", ":", "raise", "ExpectationNotMet", "(", "\"Item does not match the provided selector\"", ")", "return", "True", "return", "assert_matches_selector", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.has_checked_field
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.
capybara/node/matchers.py
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)
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)
[ "Checks", "if", "the", "page", "or", "current", "node", "has", "a", "radio", "button", "or", "checkbox", "with", "the", "given", "label", "value", "or", "id", "that", "is", "currently", "checked", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L614-L628
[ "def", "has_checked_field", "(", "self", ",", "locator", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"checked\"", "]", "=", "True", "return", "self", ".", "has_selector", "(", "\"field\"", ",", "locator", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.has_no_checked_field
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.
capybara/node/matchers.py
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)
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)
[ "Checks", "if", "the", "page", "or", "current", "node", "has", "no", "radio", "button", "or", "checkbox", "with", "the", "given", "label", "value", "or", "id", "that", "is", "currently", "checked", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L630-L644
[ "def", "has_no_checked_field", "(", "self", ",", "locator", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"checked\"", "]", "=", "True", "return", "self", ".", "has_no_selector", "(", "\"field\"", ",", "locator", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.has_unchecked_field
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.
capybara/node/matchers.py
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)
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)
[ "Checks", "if", "the", "page", "or", "current", "node", "has", "a", "radio", "button", "or", "checkbox", "with", "the", "given", "label", "value", "or", "id", "that", "is", "currently", "unchecked", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L784-L798
[ "def", "has_unchecked_field", "(", "self", ",", "locator", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"checked\"", "]", "=", "False", "return", "self", ".", "has_selector", "(", "\"field\"", ",", "locator", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.has_no_unchecked_field
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.
capybara/node/matchers.py
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)
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)
[ "Checks", "if", "the", "page", "or", "current", "node", "has", "no", "radio", "button", "or", "checkbox", "with", "the", "given", "label", "value", "or", "id", "that", "is", "currently", "unchecked", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L800-L814
[ "def", "has_no_unchecked_field", "(", "self", ",", "locator", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"checked\"", "]", "=", "False", "return", "self", ".", "has_no_selector", "(", "\"field\"", ",", "locator", ",", "*", "*", "kwargs", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_text
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.
capybara/node/matchers.py
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()
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()
[ "Asserts", "that", "the", "page", "or", "current", "node", "has", "the", "given", "text", "content", "ignoring", "any", "HTML", "tags", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L816-L843
[ "def", "assert_text", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
MatchersMixin.assert_no_text
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.
capybara/node/matchers.py
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()
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()
[ "Asserts", "that", "the", "page", "or", "current", "node", "doesn", "t", "have", "the", "given", "text", "content", "ignoring", "any", "HTML", "tags", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L845-L873
[ "def", "assert_no_text", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
DocumentMatchersMixin.assert_title
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.
capybara/node/document_matchers.py
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()
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()
[ "Asserts", "that", "the", "page", "has", "the", "given", "title", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/document_matchers.py#L6-L30
[ "def", "assert_title", "(", "self", ",", "title", ",", "*", "*", "kwargs", ")", ":", "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", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
DocumentMatchersMixin.assert_no_title
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.
capybara/node/document_matchers.py
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()
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()
[ "Asserts", "that", "the", "page", "doesn", "t", "have", "the", "given", "title", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/document_matchers.py#L32-L56
[ "def", "assert_no_title", "(", "self", ",", "title", ",", "*", "*", "kwargs", ")", ":", "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", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
DocumentMatchersMixin.has_title
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.
capybara/node/document_matchers.py
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
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
[ "Checks", "if", "the", "page", "has", "the", "given", "title", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/document_matchers.py#L58-L74
[ "def", "has_title", "(", "self", ",", "title", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "assert_title", "(", "title", ",", "*", "*", "kwargs", ")", "return", "True", "except", "ExpectationNotMet", ":", "return", "False" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
DocumentMatchersMixin.has_no_title
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.
capybara/node/document_matchers.py
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
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
[ "Checks", "if", "the", "page", "doesn", "t", "have", "the", "given", "title", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/document_matchers.py#L76-L92
[ "def", "has_no_title", "(", "self", ",", "title", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "assert_no_title", "(", "title", ",", "*", "*", "kwargs", ")", "return", "True", "except", "ExpectationNotMet", ":", "return", "False" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
FindersMixin.find_all
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.
capybara/node/finders.py
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()
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()
[ "Find", "all", "elements", "on", "the", "page", "matching", "the", "given", "selector", "and", "options", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/finders.py#L150-L208
[ "def", "find_all", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", "(", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
FindersMixin.find_first
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.
capybara/node/finders.py
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
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
[ "Find", "the", "first", "element", "on", "the", "page", "matching", "the", "given", "selector", "and", "options", "or", "None", "if", "no", "element", "matches", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/finders.py#L210-L234
[ "def", "find_first", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
TextQuery.resolve_for
Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found.
capybara/queries/text_query.py
def resolve_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_text = normalize_text( node.visible_text if self.query_type == "visible" else node.all_text) self.count = len(re.findall(self.search_regexp, self.actual_text)) return self.count
def resolve_for(self, node): """ Resolves this query relative to the given node. Args: node (node.Base): The node to be evaluated. Returns: int: The number of matches found. """ self.node = node self.actual_text = normalize_text( node.visible_text if self.query_type == "visible" else node.all_text) self.count = len(re.findall(self.search_regexp, self.actual_text)) return self.count
[ "Resolves", "this", "query", "relative", "to", "the", "given", "node", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/text_query.py#L68-L84
[ "def", "resolve_for", "(", "self", ",", "node", ")", ":", "self", ".", "node", "=", "node", "self", ".", "actual_text", "=", "normalize_text", "(", "node", ".", "visible_text", "if", "self", ".", "query_type", "==", "\"visible\"", "else", "node", ".", "all_text", ")", "self", ".", "count", "=", "len", "(", "re", ".", "findall", "(", "self", ".", "search_regexp", ",", "self", ".", "actual_text", ")", ")", "return", "self", ".", "count" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
inner_content
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.
capybara/utils.py
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))
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))
[ "Returns", "the", "inner", "content", "of", "a", "given", "XML", "node", "including", "tags", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/utils.py#L75-L99
[ "def", "inner_content", "(", "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", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c
test
inner_text
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.
capybara/utils.py
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)))
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)))
[ "Returns", "the", "inner", "text", "of", "a", "given", "XML", "node", "excluding", "tags", "." ]
elliterate/capybara.py
python
https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/utils.py#L102-L126
[ "def", "inner_text", "(", "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", ")", ")", ")" ]
0c6ae449cc37e4445ec3cd6af95674533beedc6c