Best Python code snippet using molotov_python
constants.py
Source:constants.py  
1# pseudo-constant magic2#################################################################3# utility functions4def _getString(str, server, reverse=0):5    if reverse:6        if str == 0:7            return ''8        else:9            return server.getstring(str).data.replace('\0','')10    else:11        # check if it's already a handle, too12        if not server:13            return str, _getString14        try:15            str.upper()16        except:17            return str, _getString18        return server.getString(str), _getString19def _getFont(str, server, reverse=0):20    if reverse:21        return str22    else:23        if not server:24            return str, _getFont25        try:26            str.upper()27        except:28            return str, _getFont29        return server.getFont(str), _getFont30def _getBitmap(str, server, reverse=0):31    if reverse:32        return str33    else:34        return server.mkbitmap(str), _getBitmap35def _getSize(s, server, reverse=0):36    if reverse:37        return s38    else:39        # This converts fractions of the form "numerator/denominator"40        # into pgserver 8:8 bit fractions if necessary.41        # Also, allow "None" to indicate automatic sizing,42        # represented in the server by -1.43        if s == None:44            return 0xFFFFFFFFL, _getSize45        fraction = str(s).split('/')46        if len(fraction) > 1:47            return (int(fraction[0])<<8) | int(fraction[1]), _getSize48        return int(s), _getSize49def _pairAt16bits(p, server, reverse=0):50    if reverse:51        return p >> 16, p & 0xffff52    else:53        return (p[0] << 16) + p[1], {}54def _gropseq(seq, server):55    # not reversable56    try:57        seq = seq.all()58    except:59        pass60    return tuple(seq), _stop61#################################################################62# unique values63_stop = ((),)64_default = -165#################################################################66# tables67_color_consts = {68            'black':            (0x000000, {}),69            'green':            (0x008000, {}),70            'silver':           (0xC0C0C0, {}),71            'lime':             (0x00FF00, {}),72            'gray':             (0x808080, {}),73            'olive':            (0x808000, {}),74            'white':            (0xFFFFFF, {}),75            'yellow':           (0xFFFF00, {}),76            'maroon':           (0x800000, {}),77            'navy':             (0x000080, {}),78            'red':              (0xFF0000, {}),79            'blue':             (0x0000FF, {}),80            'purple':           (0x800080, {}),81            'teal':             (0x008080, {}),82            'fuchsia':          (0xFF00FF, {}),83            'aqua':             (0x00FFFF, {}),84    }85_thobj_consts = {86            'default':			(0, {}),87            'base interactive':		(1, {}),88            'base container':		(2, {}),89            'button':			(3, {}),90            'button hilight':		(4, {}),91            'button on':		(5, {}),92            'toolbar':			(6, {}),93            'scroll':			(7, {}),94            'scroll hilight':		(8, {}),95            'indicator':		(9, {}),96            'panel':			(10, {}),97            'panelbar':			(11, {}),98            'popup':			(12, {}),99            'background':		(13, {}),100            'base display':		(14, {}),101            'base tlcontainer':		(15, {}),102            'themeinfo':		(16, {}),103            'label':			(17, {}),104            'field':			(18, {}),105            'bitmap':			(19, {}),106            'scroll on':		(20, {}),107            'label scroll':		(21, {}),108            'panelbar hilight':		(22, {}),109            'panelbar on':		(23, {}),110            'box':			(24, {}),111            'label dlgtitle':		(25, {}),112            'label dlgtext':		(26, {}),113            'closebtn':			(27, {}),114            'closebtn on':		(28, {}),115            'closebtn hilight':		(29, {}),116            'base panelbtn':		(30, {}),117            'rotatebtn':		(31, {}),118            'rotatebtn on':		(32, {}),119            'rotatebtn hilight':	(33, {}),120            'zoombtn':			(34, {}),121            'zoombtn on':		(35, {}),122            'zoombtn hilight':		(36, {}),123            'popup menu':		(37, {}),124            'popup messagedlg':		(38, {}),125            'menuitem':			(39, {}),126            'menuitem hilight':		(40, {}),127            'checkbox':			(41, {}),128            'checkbox hilight':		(42, {}),129            'checkbox on':		(43, {}),130            'flatbutton':		(44, {}),131            'flatbutton hilight':	(45, {}),132            'flatbutton on':		(46, {}),133            'listitem':			(47, {}),134            'listitem hilight':		(48, {}),135            'listitem on':		(49, {}),136            'checkbox on nohilight':	(50, {}),137            'submenuitem':		(51, {}),138            'submenuitem hilight':	(52, {}),139            'radiobutton':		(53, {}),140            'radiobutton hilight':	(54, {}),141            'radiobutton on':		(55, {}),142            'radiobutton on nohilight':	(56, {}),143            'textbox':			(57, {}),144            'terminal':			(58, {}),145            'menubutton':		(60, {}),146            'menubutton on':		(61, {}),147            'menubutton hilight':	(62, {}),148            'label hilight':		(63, {}),149            'box hilight':		(64, {}),150            'indicator h':		(65, {}),151            'indicator v':		(66, {}),152            'scroll h':			(67, {}),153            'scroll v':			(68, {}),154            'scroll h on':		(69, {}),155            'scroll h hilight':		(70, {}),156            'scroll v on':		(71, {}),157            'scroll v hilight':		(72, {}),158            'panelbar h':		(73, {}),159            'panelbar v':		(74, {}),160            'panelbar h on':		(75, {}),161            'panelbar h hilight':	(76, {}),162            'panelbar v on':		(77, {}),163            'panelbar v hilight':	(78, {}),164            'textedit':			(79, {}),165            'managedwindow':		(80, {}),166            'tab page':			(81, {}),167            'tab bar':			(82, {}),168            'tab':			(83, {}),169            'tab hilight':		(84, {}),170            'tab on':			(85, {}),171            'tab on nohilight':		(86, {}),172    }173_wtype_consts = {174            'toolbar':		(0, {}),175            'label':		(1, {}),176            'scroll':		(2, {}),177            'indicator':	(3, {}),178            'managedwindow':	(4, {}),179            'button':		(5, {}),180            'panel':		(6, {}),181            'popup':		(7, {}),182            'box':		(8, {}),183            'field':		(9, {}),184            'background':	(10, {}),185            'menuitem':		(11, {}),	# a variation on button186            'terminal':		(12, {}),	# a full terminal emulator187            'canvas':		(13, {}),188            'checkbox':		(14, {}),	# another variation of button189            'flatbutton':	(15, {}),	# yet another customized button190            'listitem':		(16, {}),	# still yet another...191            'submenuitem':	(17, {}),	# menuitem with a submenu arrow192            'radiobutton':	(18, {}),	# like a check box, but exclusive193            'textbox':		(19, {}),	# client-side text layout194            'panelbar':		(20, {}),	# draggable bar and container195            'simplemenu':	(21, {}),	# create a simple menu from a string or array196            'dialogbox':        (22, {}),       # a type of popup that is always autosized and has a title197            'messagedialog':    (23, {}),       # a type of dialogbox that displays a message and gets feedback198            'scrollbox':        (24, {}),       # box widget with built-in horizontal and/or vertical scrollbars199            'textedit':         (25, {}),200            'tabpage':          (26, {}),201    }202import keys203_key_consts = {}204for name, code in keys.keys.items():205    _key_consts[name] = (code, {})206_modifier_consts = {}207for name, code in keys.mods.items():208    _modifier_consts[name] = (code, {})209_constants = {210    'attachwidget': {211        'after':	(1, {}),212        'inside':	(2, {}),213        'before':	(3, {}),214    },215    'createwidget': _wtype_consts,216    'mkwidget': {217        'after':	(1, _wtype_consts),218        'inside':	(2, _wtype_consts),219        'before':	(3, _wtype_consts),220    },221    'get': 'set',222    'mkfont': ( # first argument (family) is string and should pass trough223        {224            'fixed':			((1<<0), {}),	# fixed width225            'default':			((1<<1), {}),	# the default font in its category, fixed or proportional.226            'symbol':			((1<<2), {}),	# font contains nonstandard chars and will not be chosen227                                                        # unless specifically requested228            'subset':			((1<<3), {}),	# font does not contain all the ascii chars before 127, and229                                                        # shouldn't be used unless requested230            'encoding isolatin1':	((1<<4), {}),	# iso latin-1 encoding231            'encoding ibm':		((1<<5), {}),	# ibm-pc extended characters232            'doublespace':		((1<<7), {}),	# add extra space between lines233            'bold':			((1<<8), {}),	# use or simulate a bold version of the font234            'italic':			((1<<9), {}),	# use or simulate an italic version of the font235            'underline':		((1<<10), {}),	# underlined text236            'strikeout':		((1<<11), {}),	# strikeout, a line through the middle of the text237            'flush':			((1<<14), {}),	# disable the margin that picogui puts around text238            'doublewidth':		((1<<15), {}),	# add extra space between characters239            'italic2':			((1<<16), {}),	# twice the slant of the default italic240            'encoding unicode':		((1<<17), {}),	# unicode encoding241    },),242    'register': _getString,243    'getresource': {244        'default font':			(0, {}),245        'string ok':			(1, {}),246        'string cancel':		(2, {}),247        'string yes':			(3, {}),248        'string no':			(4, {}),249        'string segfault':		(5, {}),250        'string matherr':		(6, {}),251        'string pguierr':		(7, {}),252        'string pguiwarn':		(8, {}),253        'string pguierrdlg':		(9, {}),254        'string pguicompat':		(10, {}),255        'default textcolors':		(11, {}),256        'infilter touchscreen': 	(12, {}),257        'infilter key preprocess':	(13, {}),258        'infilter pntr preprocess':	(14, {}),259        'infilter magic':		(15, {}),260        'infilter key dispatch':	(16, {}),261        'infilter pntr dispatch':	(17, {}),262        'default cursorbitmap': 	(18, {}),263        'default cursorbitmask': 	(19, {}),264        'background widget':    	(20, {}),265        'infilter hotspot':     	(21, {}),266        'infilter key alpha':    	(22, {}),267        'infilter pntr normalize': 	(23, {}),268    },269    'set': {270        'size':				(1,271            _getSize),272        'side':				(2, {273            'top':	(1<<3, {}),	# stick to the top edge274            'bottom':	(1<<4, {}),	# stick to the bottom edge275            'left':	(1<<5, {}),	# stick to the left edge276            'right':	(1<<6, {}),	# stick to the right edge277            'all':	(1<<11, {}),	# occupy all available space278        }),279        'align':			(3, {280            'center':	(0, {}),	# center in the available space281            'top':	(1, {}),	# stick to the top-center of the available space282            'left':	(2, {}),	# stick to the left-center of the available space283            'bottom':	(3, {}),	# stick to the bottom-center of the available space284            'right':	(4, {}),	# stick to the right-center of the available space285            'nw':	(5, {}),	# stick to the northwest corner286            'sw':	(6, {}),	# stick to the southwest corner287            'ne':	(7, {}),	# stick to the northeast corner288            'se':	(8, {}),	# stick to the southeast corner289            'all':	(9, {}),	# occupy all available space (good for tiled bitmaps)290        }),291        'bgcolor':			(4,292            _color_consts),293        'color':			(5,294            _color_consts),295        'sizemode':			(6, {296            'pixel':	(0, {}),297            'percent':	(1<<2, {}),298            'cntfrac':	(1<<15, {}),               # Container fraction299            'container fraction':  (1<<15, {}),    # Less stupidly named version of the same300        }),301        'text':				(7,302            _getString),303        'font':				(8,304            _getFont),305        'transparent':			(9, {}),306        'bordercolor':			(10,307            _color_consts),308        'image':			(12,309            _getBitmap),310        'bitmap':			'image',311        'lgop':				(13, {312        }),313        'value':			(14, {314        }),315        'bitmask':			(15,316            _getBitmap),317        'bind':				(16, {318        }),319        'scroll x':			(17, {	# horizontal and vertical scrolling amount320        }),321        'scroll y':			(18, {322        }),323        'hotkey':			(19, 324	    _key_consts),325        'extdevents':			(20, {	# mask of extra events to send326            'pointer up':      (0x0001, {}),327            'pointer down':    (0x0002, {}),328            'noclick':         (0x0004, {}),329            'pointer move':    (0x0008, {}),330            'pointer':         (0x0009, {}),331            'key':             (0x0010, {}),332            'char':            (0x0020, {}),333            'kbd':	       (0x0030, {}),334            'toggle':          (0x0040, {}),335            'exclusive':       (0x0080, {}),336            'focus':           (0x0100, {}),337            'no hotspot':      (0x0200, {}),338            'none':	       (0, {}),339            _default:	       (0, {}),340        }),341        'direction':			(21, {342            'horizontal':	(0, {}),343            'vertical':		(90, {}),344            'antihorizontal':	(180, {}),345        }),346        'absolutex':			(22, {	# read-only, relative to screen347        }),348        'absolutey':			(23, {349        }),350        'on':				(24, {  # on-off state of button/checkbox/etc351        }),352        'thobj':			(25,    # set a widget's theme object353            _thobj_consts),354        'name':				(26,    # a widget's name (for named containers, etc)355            _getString),356        'publicbox':			(27, {  # set to 1 to allow other apps to make widgets in this container357        }),358        'disabled':			(28, {  # for buttons, grays out text and prevents clicking359        }),360        'margin':			(29, {	# for boxes, overrides the default margin361        }),362        'textformat':			(30, 	# for the textbox, defines a format for text.363            _getString),364        'triggermask':			(31, {	# mask of extra triggers accepted (self->trigger_mask)365        }),366        'hilighted':			(32, {	# widget property to hilight a widget and all it's children367        }),368        'selected':			(33, {	# list property to select a row.369        }),370        'selected handle':		(34, {	# list property to return a handle to the selected row371        }),372        'autoscroll':			(35, {	# for the textbox or terminal, scroll to any new text that's inserted373        }),374        'lines':			(36, {	# height, in lines375        }),376        'preferred w':			(37, {	# read only (for now) properties to get any widget's preferred size377        }),378        'preferred h':			(38, {379        }),380        'panelbar':			(39, {	# read-only property for panels returns a handle to its embedded381                                                # panelbar widget382        }),383        'auto orientation':		(40, {	# automatically reorient child widgets when side changes384        }),385        'thobj button':			(41, 	# these four theme properties set the theme objects used for the386                                              	# three possible states of the button widget.387            _thobj_consts),388        'thobj button hilight':		(42,389            _thobj_consts),390        'thobj button on':		(43,391            _thobj_consts),392        'thobj button on nohilight':	(44,393            _thobj_consts),394        'panelbar label':		(45, {	# more read-only panelbar properties to get the built-in panelbar widgets395        }),396        'panelbar close':		(46, {397        }),398        'panelbar rotate':		(47, {399        }),400        'panelbar zoom':		(48, {401        }),402        'imageside':			(49, {403            'top':	(1<<3, {}),	# stick to the top edge404            'bottom':	(1<<4, {}),	# stick to the bottom edge405            'left':	(1<<5, {}),	# stick to the left edge406            'right':	(1<<6, {}),	# stick to the right edge407            'all':	(1<<11, {}),	# occupy all available space408        }),409        'bitmapside':			'imageside',410        'password':			(50, {411        }),412        'hotkey flags':			(51, {	# keyboard event flags for the hotkey413        }),414        'hotkey consume':		(52, {	# flag indicating whether to consume the key event when a hotkey comes in415        }),416        'width':			(53, {417        }),418        'height':			(54, {419        }),420        'spacing':			(55, {421        }),422        'minimum':			(56, {423        }),424        'multiline':			(57, {425        }),426        'selection':			(58,427            _getString),428        'readonly':			(59, {429        }),430        'insertmode':			(60, {431            'overwrite':   (0, {}),	# Replace all text432            'append':	   (1, {}),	# Add to the end433            'prepend':	   (2, {}),	# Add to the beginning434            'atcursor':	   (3, {}),	# Add at the current cursor435        }),436        'type':				(61,437            _wtype_consts),438        'tab':				(62, {439        }),440        'tab bar':			(63, {441        }),442        'popup is menu':		(64, {443        }),444        'popup is submenu':		(65, {445        }),446        'cursor position':		(66,447            _pairAt16bits),448        'hotkey modifiers':		(67,449	    _modifier_consts),    450    },451    'traversewidget': {452        'children':	(1, {}),	# starting with first child, traverse forward453        'forward':	(2, {}),454        'backward':	(3, {}),	# much slower than forward, avoid it455        'container':	(4, {}),	# 'count' is thenumber of container levels to traverse up456    },457    'writedata': _stop,458    'writecmd': ({459        'nuke':			(1, _stop),460        'grop':			(2, {461            'rect':		  (0x00, _stop),462            'frame':		  (0x10, _stop),463            'slab':		  (0x20, _stop),464            'bar':		  (0x30, _stop),465            'pixel':		  (0x40, _stop),466            'line':		  (0x50, _stop),467            'ellipse':		  (0x60, _stop),468            'fellipse':		  (0x70, _stop),469            'text':		  (0x04, ((_getString,),)),470            'bitmap':		  (0x14, _stop),471            'tilebitmap':	  (0x24, _stop),472            'fpolygon':		  (0x34, _stop),473            'blur':		  (0x44, _stop),474            'rotatebitmap':	  (0x74, _stop),475            'arc':		  (0x08, _stop),476            'resetclip':	  (0x13, _stop),477            'setoffset':	  (0x01, _stop),478            'setclip':		  (0x11, _stop),479            'setsrc':		  (0x21, _stop),480            'setmapping':	  (0x05, {481                'none':		    (0, _stop),482                'scale':	    (1, _stop),483                'squarescale':	    (2, _stop),484                'center':	    (3, _stop),485                _default:	    (0, _stop), # so you can use None486            }),487            'setcolor':		  (0x07, _stop),488            'setfont':		  (0x17, _getFont),489            'setlgop':		  (0x27, {490                'null':		    (0, _stop),491                'none':		    (1, _stop),492                'or':		    (2, _stop),493                'and':		    (3, _stop),494                'xor':		    (4, _stop),495                'invert':	    (5, _stop),496                'invert or':	    (6, _stop),497                'invert and':	    (7, _stop),498                'invert xor':	    (8, _stop),499                'add':		    (9, _stop),500                'subtract':	    (10, _stop),501                'multiply':	    (11, _stop),502                'stipple':	    (12, _stop),503                'alpha':	    (13, _stop),504                _default:	    (1, _stop), # so you can use None505            }),506            'setangle':		  (0x37, _stop),507        }),508        'execfill':		(3, _stop),509        'findgrop':		(4, _stop),510        'setgrop':		(5, _stop),511        'movegrop':		(6, _stop),512        'mutategrop':		(7, _stop),513        'defaultflags':		(8, _stop),514        'gropflags':		(9, _stop),515        'redraw':		(10, _stop),516        'incremental':		(11, _stop),517        'scroll':		(12, _stop),518        'inputmapping':		(13, {519            'none':		  (0, _stop),520            'scale':		  (1, _stop),521            'squarescale':	  (2, _stop),522            'center':		  (3, _stop),523        }),524        'gridsize':		(14, _stop),525        'gropseq':		(15, _gropseq),526        _default:       _stop,527    },),528}529#################################################################530# some useful stuff for importing531# names of all properties532propnames = [name for name in _constants['set'].keys() if type(name) is str]533# namespace for property values, to pass to resolve()534def prop_ns(name):535    return _constants['set'][name][1]536# names of all commands537cmdnames = [name for name in _constants['writecmd'][0].keys() if type(name) is str]538# namespace for command arguments, to pass to resolve()539def cmd_ns(name):540    t = _constants['writecmd'][0][name]541    if t is _stop:542        return {}543    return t[1]544def cmd_code(name):545    t = _constants['writecmd'][0][name]546    if t is _stop:547        return None548    return t[0]549#################################################################550# external API551def resolve(name, namespace=_constants, server=None):552    if namespace is _stop:553        return name, namespace554    if type(namespace) is tuple:555        # for cases where the argument is really supposed to be a string, yet there are contstants after this556        return name, namespace[0]557    if callable(namespace):558        # for cases when we need even stranger processing559        return namespace(name, server)560    if type(name) in (tuple, list):561        # multiple names are or'ed together; namespace returned is the last one562        value = 0563        ns = namespace564        for n in name:565            v, ns = resolve(n, namespace)566            value |= v567        return value, ns568    try:569        lname = name.lower()570    except AttributeError:571        # not a string572        r = namespace.get(_default, (name, namespace))573    else:574        try:575            r = namespace[lname]576        except KeyError:577            r = namespace.get(_default, (name, namespace))578    if r is _stop:579        return name, _stop580    if type(r) == tuple and len(r) == 2:581        if r[1]:582            return r583        else:584            # stay in the same namespace if we hit a "leaf"585            return r[0], namespace586    try:587        r.lower()588        isstr = 1589    except AttributeError:590        isstr = 0591    if isstr:592        # it's an alias593        return resolve(r, namespace)594    # otherwise, it's just a namespace595    return None, r596def unresolve(name, namespace=_constants, server=None):597    if callable(namespace):598        # If we need additional processing,599        # call the namespace with the reverse flag on600        return namespace(name, server, 1)601    for n in namespace.keys():602        if namespace[n][0] == name:603            return n...timeout.py
Source:timeout.py  
1#!/usr/bin/env python22# -*- coding: utf-8 -*-3"""4Timeout encapsulation, complete with countdowns and scope managers.5"""6import time7import pwnlib8class _DummyContextClass(object):9    def __enter__(self):   pass10    def __exit__(self,*a): pass11_DummyContext = _DummyContextClass()12class _countdown_handler(object):13    def __init__(self, obj, timeout):14        self.obj     = obj15        self.timeout = timeout16    def __enter__(self):17        self.old_timeout  = self.obj._timeout18        self.old_stop     = self.obj._stop19        self.obj._stop    = time.time() + self.timeout20        if self.old_stop:21            self.obj._stop = min(self.obj._stop, self.old_stop)22        self.obj._timeout = self.timeout23    def __exit__(self, *a):24        self.obj._timeout = self.old_timeout25        self.obj._stop    = self.old_stop26class _local_handler(object):27    def __init__(self, obj, timeout):28        self.obj     = obj29        self.timeout = timeout30    def __enter__(self):31        self.old_timeout  = self.obj._timeout32        self.old_stop     = self.obj._stop33        self.obj._stop    = 034        self.obj._timeout = self.timeout # leverage validation35        self.obj.timeout_change()36    def __exit__(self, *a):37        self.obj._timeout = self.old_timeout38        self.obj._stop    = self.old_stop39        self.obj.timeout_change()40class TimeoutDefault(object):41    def __repr__(self): return "pwnlib.timeout.Timeout.default"42    def __str__(self): return "<default timeout>"43class Timeout(object):44    """45    Implements a basic class which has a timeout, and support for46    scoped timeout countdowns.47    Valid timeout values are:48    - ``Timeout.default`` use the global default value (``context.default``)49    - ``Timeout.forever`` or ``None`` never time out50    - Any positive float, indicates timeouts in seconds51    Example:52        >>> context.timeout = 3053        >>> t = Timeout()54        >>> t.timeout == 3055        True56        >>> t = Timeout(5)57        >>> t.timeout == 558        True59        >>> i = 060        >>> with t.countdown():61        ...     print (4 <= t.timeout and t.timeout <= 5)62        ...63        True64        >>> with t.countdown(0.5):65        ...     while t.timeout:66        ...         print round(t.timeout,1)67        ...         time.sleep(0.1)68        0.569        0.470        0.371        0.272        0.173        >>> print t.timeout74        5.075        >>> with t.local(0.5):76        ...     for i in range(5):77        ...         print round(t.timeout,1)78        ...         time.sleep(0.1)79        0.580        0.581        0.582        0.583        0.584        >>> print t.timeout85        5.086    """87    #: Value indicating that the timeout should not be changed88    default = TimeoutDefault()89    #: Value indicating that a timeout should not ever occur90    forever = None91    #: Maximum value for a timeout.  Used to get around platform issues92    #: with very large timeouts.93    #:94    #: OSX does not permit setting socket timeouts to 2**22.95    #: Assume that if we receive a timeout of 2**21 or greater,96    #: that the value is effectively infinite.97    maximum = float(2**20)98    def __init__(self, timeout=default):99        self._stop    = 0100        self.timeout = self._get_timeout_seconds(timeout)101    @property102    def timeout(self):103        """104        Timeout for obj operations.  By default, uses ``context.timeout``.105        """106        timeout = self._timeout107        stop    = self._stop108        if not stop:109            return timeout110        return max(stop-time.time(), 0)111    @timeout.setter112    def timeout(self, value):113        assert not self._stop114        self._timeout = self._get_timeout_seconds(value)115        self.timeout_change()116    def _get_timeout_seconds(self, value):117        if value is self.default:118            value = pwnlib.context.context.timeout119        elif value is self.forever:120            value = self.maximum121        else:122            value = float(value)123            if value is value < 0:124                raise AttributeError("timeout: Timeout cannot be negative")125            if value > self.maximum:126                value = self.maximum127        return value128    def countdown_active(self):129        return (self._stop == 0) or (self._stop > time.time())130    def timeout_change(self):131        """132        Callback for subclasses to hook a timeout change.133        """134        pass135    def countdown(self, timeout = default):136        """137        Scoped timeout setter.  Sets the timeout within the scope,138        and restores it when leaving the scope.139        When accessing :attr:`timeout` within the scope, it will be140        calculated against the time when the scope was entered, in a141        countdown fashion.142        If ``None`` is specified for ``timeout``, then the current143        timeout is used is made.  This allows ``None`` to be specified144        as a default argument with less complexity.145        """146        # Don't count down from infinity147        if timeout is self.maximum:148            return _DummyContext149        if timeout is self.default and self.timeout is self.maximum:150            return _DummyContext151        if timeout is self.default:152            timeout = self._timeout153        return _countdown_handler(self, timeout)154    def local(self, timeout):155        """156        Scoped timeout setter.  Sets the timeout within the scope,157        and restores it when leaving the scope.158        """159        if timeout is self.default or timeout == self.timeout:160            return _DummyContext...treeslice.py
Source:treeslice.py  
1#!/usr/bin/env python2#coding:utf-83# Author:  mozman -- <mozman@gmx.at>4# Purpose: TreeSlice5# Created: 11.04.20116# Copyright (c) 2010-2013 by Manfred Moitzi7# License: MIT License8class TreeSlice(object):9    __slots__ = ['_tree', '_start', '_stop']10    def __init__(self, tree, start, stop):11        self._tree = tree12        self._start = start13        self._stop = stop14    def __repr__(self):15        tpl = "%s({%s})" % (self._tree.__class__.__name__, '%s')16        return tpl % ", ".join( ("%r: %r" % item for item in self.items()) )17    def __contains__(self, key):18        if self._inrange(key):19            return key in self._tree20        else:21            return False22    def _inrange(self, key):23        if self._start is not None and key < self._start:24                return False25        if self._stop is not None and key >= self._stop:26                return False27        return True28    def __getitem__(self, key):29        if isinstance(key, slice):30            return self._subslice(key.start, key.stop)31        if self._inrange(key):32            return self._tree[key]33        else:34            raise KeyError(key)35    def _subslice(self, start, stop):36        def newstart():37            if start is None:38                return self._start39            elif self._start is None:40                return start41            else:42                return max(start, self._start)43        def newstop():44            if stop is None:45                return self._stop46            elif self._stop is None:47                return stop48            else:49                return min(stop, self._stop)50        return TreeSlice(self._tree, newstart(), newstop())51    def keys(self):52        return self._tree.keyslice(self._start, self._stop)53    __iter__ = keys54    def values(self):55        return self._tree.valueslice(self._start, self._stop)56    def items(self):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
