idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
26,000
def _zom_name ( lexer ) : tok = next ( lexer ) if isinstance ( tok , DOT ) : first = _expect_token ( lexer , { NameToken } ) . value rest = _zom_name ( lexer ) return ( first , ) + rest else : lexer . unpop_token ( tok ) return tuple ( )
Return zero or more names .
26,001
def _indices ( lexer ) : first = _expect_token ( lexer , { IntegerToken } ) . value rest = _zom_index ( lexer ) return ( first , ) + rest
Return a tuple of indices .
26,002
def _zom_index ( lexer ) : tok = next ( lexer ) if isinstance ( tok , COMMA ) : first = _expect_token ( lexer , { IntegerToken } ) . value rest = _zom_index ( lexer ) return ( first , ) + rest else : lexer . unpop_token ( tok ) return tuple ( )
Return zero or more indices .
26,003
def subword ( w ) : w = w . reshape ( 4 , 8 ) return SBOX [ w [ 0 ] ] + SBOX [ w [ 1 ] ] + SBOX [ w [ 2 ] ] + SBOX [ w [ 3 ] ]
Function used in the Key Expansion routine that takes a four - byte input word and applies an S - box to each of the four bytes to produce an output word .
26,004
def multiply ( a , col ) : a = a . reshape ( 4 , 4 , 4 ) col = col . reshape ( 4 , 8 ) return fcat ( rowxcol ( a [ 0 ] , col ) , rowxcol ( a [ 1 ] , col ) , rowxcol ( a [ 2 ] , col ) , rowxcol ( a [ 3 ] , col ) , )
Multiply a matrix by one column .
26,005
def rowxcol ( row , col ) : row = row . reshape ( 4 , 4 ) col = col . reshape ( 4 , 8 ) ret = uint2exprs ( 0 , 8 ) for i in range ( 4 ) : for j in range ( 4 ) : if row [ i , j ] : ret ^= xtime ( col [ i ] , j ) return ret
Multiply one row and one column .
26,006
def shift_rows ( state ) : state = state . reshape ( 4 , 4 , 8 ) return fcat ( state [ 0 ] [ 0 ] , state [ 1 ] [ 1 ] , state [ 2 ] [ 2 ] , state [ 3 ] [ 3 ] , state [ 1 ] [ 0 ] , state [ 2 ] [ 1 ] , state [ 3 ] [ 2 ] , state [ 0 ] [ 3 ] , state [ 2 ] [ 0 ] , state [ 3 ] [ 1 ] , state [ 0 ] [ 2 ] , state [ 1 ] [ 3 ] , s...
Transformation in the Cipher that processes the State by cyclically shifting the last three rows of the State by different offsets .
26,007
def key_expand ( key , Nk = 4 ) : assert Nk in { 4 , 6 , 8 } Nr = Nk + 6 key = key . reshape ( Nk , 32 ) rkey = exprzeros ( 4 * ( Nr + 1 ) , 32 ) for i in range ( Nk ) : rkey [ i ] = key [ i ] for i in range ( Nk , 4 * ( Nr + 1 ) ) : if i % Nk == 0 : rkey [ i ] = rkey [ i - Nk ] ^ subword ( rotword ( rkey [ i - 1 ] ) )...
Expand the key into the round key .
26,008
def cipher ( rkey , pt , Nk = 4 ) : assert Nk in { 4 , 6 , 8 } Nr = Nk + 6 rkey = rkey . reshape ( 4 * ( Nr + 1 ) , 32 ) pt = pt . reshape ( 128 ) state = add_round_key ( pt , rkey [ 0 : 4 ] ) for i in range ( 1 , Nr ) : state = sub_bytes ( state ) state = shift_rows ( state ) state = mix_columns ( state ) state = add_...
AES encryption cipher .
26,009
def inv_cipher ( rkey , ct , Nk = 4 ) : assert Nk in { 4 , 6 , 8 } Nr = Nk + 6 rkey = rkey . reshape ( 4 * ( Nr + 1 ) , 32 ) ct = ct . reshape ( 128 ) state = add_round_key ( ct , rkey [ 4 * Nr : 4 * ( Nr + 1 ) ] ) for i in range ( Nr - 1 , 0 , - 1 ) : state = inv_shift_rows ( state ) state = inv_sub_bytes ( state ) st...
AES decryption cipher .
26,010
def encrypt ( key , pt , Nk = 4 ) : assert Nk in { 4 , 6 , 8 } rkey = key_expand ( key , Nk ) ct = cipher ( rkey , pt , Nk ) return ct
Encrypt a plain text block .
26,011
def decrypt ( key , ct , Nk = 4 ) : assert Nk in { 4 , 6 , 8 } rkey = key_expand ( key , Nk ) pt = inv_cipher ( rkey , ct , Nk ) return pt
Decrypt a plain text block .
26,012
def gray2bin ( G ) : return farray ( [ G [ i : ] . uxor ( ) for i , _ in enumerate ( G ) ] )
Convert a gray - coded vector into a binary - coded vector .
26,013
def _assume2point ( ) : point = dict ( ) for lit in _ASSUMPTIONS : if isinstance ( lit , Complement ) : point [ ~ lit ] = 0 elif isinstance ( lit , Variable ) : point [ lit ] = 1 return point
Convert global assumptions to a point .
26,014
def exprvar ( name , index = None ) : r bvar = boolfunc . var ( name , index ) try : var = _LITS [ bvar . uniqid ] except KeyError : var = _LITS [ bvar . uniqid ] = Variable ( bvar ) return var
r Return a unique Expression variable .
26,015
def _exprcomp ( node ) : try : comp = _LITS [ node . data ( ) ] except KeyError : comp = _LITS [ node . data ( ) ] = Complement ( node ) return comp
Return a unique Expression complement .
26,016
def expr ( obj , simplify = True ) : if isinstance ( obj , Expression ) : return obj elif isinstance ( obj , int ) and obj in { 0 , 1 } : return _CONSTS [ obj ] elif isinstance ( obj , str ) : ast = pyeda . parsing . boolexpr . parse ( obj ) ex = ast2expr ( ast ) if simplify : ex = ex . simplify ( ) return ex else : re...
Convert an arbitrary object into an Expression .
26,017
def ast2expr ( ast ) : if ast [ 0 ] == 'const' : return _CONSTS [ ast [ 1 ] ] elif ast [ 0 ] == 'var' : return exprvar ( ast [ 1 ] , ast [ 2 ] ) else : xs = [ ast2expr ( x ) for x in ast [ 1 : ] ] return ASTOPS [ ast [ 0 ] ] ( * xs , simplify = False )
Convert an abstract syntax tree to an Expression .
26,018
def expr2dimacscnf ( ex ) : litmap , nvars , clauses = ex . encode_cnf ( ) return litmap , DimacsCNF ( nvars , clauses )
Convert an expression into an equivalent DIMACS CNF .
26,019
def expr2dimacssat ( ex ) : if not ex . simple : raise ValueError ( "expected ex to be simplified" ) litmap , nvars = ex . encode_inputs ( ) formula = _expr2sat ( ex , litmap ) if 'xor' in formula : if '=' in formula : fmt = 'satex' else : fmt = 'satx' elif '=' in formula : fmt = 'sate' else : fmt = 'sat' return "p {} ...
Convert an expression into an equivalent DIMACS SAT string .
26,020
def _expr2sat ( ex , litmap ) : if isinstance ( ex , Literal ) : return str ( litmap [ ex ] ) elif isinstance ( ex , NotOp ) : return "-(" + _expr2sat ( ex . x , litmap ) + ")" elif isinstance ( ex , OrOp ) : return "+(" + " " . join ( _expr2sat ( x , litmap ) for x in ex . xs ) + ")" elif isinstance ( ex , AndOp ) : r...
Convert an expression to a DIMACS SAT string .
26,021
def upoint2exprpoint ( upoint ) : point = dict ( ) for uniqid in upoint [ 0 ] : point [ _LITS [ uniqid ] ] = 0 for uniqid in upoint [ 1 ] : point [ _LITS [ uniqid ] ] = 1 return point
Convert an untyped point into an Expression point .
26,022
def Not ( x , simplify = True ) : x = Expression . box ( x ) . node y = exprnode . not_ ( x ) if simplify : y = y . simplify ( ) return _expr ( y )
Expression negation operator
26,023
def Equal ( * xs , simplify = True ) : xs = [ Expression . box ( x ) . node for x in xs ] y = exprnode . eq ( * xs ) if simplify : y = y . simplify ( ) return _expr ( y )
Expression equality operator
26,024
def Implies ( p , q , simplify = True ) : p = Expression . box ( p ) . node q = Expression . box ( q ) . node y = exprnode . impl ( p , q ) if simplify : y = y . simplify ( ) return _expr ( y )
Expression implication operator
26,025
def Unequal ( * xs , simplify = True ) : xs = [ Expression . box ( x ) . node for x in xs ] y = exprnode . not_ ( exprnode . eq ( * xs ) ) if simplify : y = y . simplify ( ) return _expr ( y )
Expression inequality operator
26,026
def OneHot0 ( * xs , simplify = True , conj = True ) : xs = [ Expression . box ( x ) . node for x in xs ] terms = list ( ) if conj : for x0 , x1 in itertools . combinations ( xs , 2 ) : terms . append ( exprnode . or_ ( exprnode . not_ ( x0 ) , exprnode . not_ ( x1 ) ) ) y = exprnode . and_ ( * terms ) else : for _xs i...
Return an expression that means at most one input function is true .
26,027
def OneHot ( * xs , simplify = True , conj = True ) : xs = [ Expression . box ( x ) . node for x in xs ] terms = list ( ) if conj : for x0 , x1 in itertools . combinations ( xs , 2 ) : terms . append ( exprnode . or_ ( exprnode . not_ ( x0 ) , exprnode . not_ ( x1 ) ) ) terms . append ( exprnode . or_ ( * xs ) ) y = ex...
Return an expression that means exactly one input function is true .
26,028
def NHot ( n , * xs , simplify = True ) : if not isinstance ( n , int ) : raise TypeError ( "expected n to be an int" ) if not 0 <= n <= len ( xs ) : fstr = "expected 0 <= n <= {}, got {}" raise ValueError ( fstr . format ( len ( xs ) , n ) ) xs = [ Expression . box ( x ) . node for x in xs ] num = len ( xs ) terms = l...
Return an expression that means exactly N input functions are true .
26,029
def Majority ( * xs , simplify = True , conj = False ) : xs = [ Expression . box ( x ) . node for x in xs ] if conj : terms = list ( ) for _xs in itertools . combinations ( xs , ( len ( xs ) + 1 ) // 2 ) : terms . append ( exprnode . or_ ( * _xs ) ) y = exprnode . and_ ( * terms ) else : terms = list ( ) for _xs in ite...
Return an expression that means the majority of input functions are true .
26,030
def Mux ( fs , sel , simplify = True ) : if isinstance ( sel , Expression ) : sel = [ sel ] if len ( sel ) < clog2 ( len ( fs ) ) : fstr = "expected at least {} select bits, got {}" raise ValueError ( fstr . format ( clog2 ( len ( fs ) ) , len ( sel ) ) ) it = boolfunc . iter_terms ( sel ) y = exprnode . or_ ( * [ expr...
Return an expression that multiplexes a sequence of input functions over a sequence of select functions .
26,031
def _backtrack ( ex ) : if ex is Zero : return None elif ex is One : return dict ( ) else : v = ex . top points = { v : 0 } , { v : 1 } for point in points : soln = _backtrack ( ex . restrict ( point ) ) if soln is not None : soln . update ( point ) return soln return None
If this function is satisfiable return a satisfying input upoint . Otherwise return None .
26,032
def _iter_backtrack ( ex , rand = False ) : if ex is One : yield dict ( ) elif ex is not Zero : if rand : v = random . choice ( ex . inputs ) if rand else ex . top else : v = ex . top points = [ { v : 0 } , { v : 1 } ] if rand : random . shuffle ( points ) for point in points : for soln in _iter_backtrack ( ex . restri...
Iterate through all satisfying points using backtrack algorithm .
26,033
def _tseitin ( ex , auxvarname , auxvars = None ) : if isinstance ( ex , Literal ) : return ex , list ( ) else : if auxvars is None : auxvars = list ( ) lits = list ( ) constraints = list ( ) for x in ex . xs : lit , subcons = _tseitin ( x , auxvarname , auxvars ) lits . append ( lit ) constraints . extend ( subcons ) ...
Convert a factored expression to a literal and a list of constraints .
26,034
def eq ( self , other ) : other_node = self . box ( other ) . node return _expr ( exprnode . eq ( self . node , other_node ) )
Boolean equal operator .
26,035
def pushdown_not ( self ) : node = self . node . pushdown_not ( ) if node is self . node : return self else : return _expr ( node )
Return an expression with NOT operators pushed down thru dual ops .
26,036
def simplify ( self ) : node = self . node . simplify ( ) if node is self . node : return self else : return _expr ( node )
Return a simplified expression .
26,037
def to_binary ( self ) : node = self . node . to_binary ( ) if node is self . node : return self else : return _expr ( node )
Convert N - ary operators to binary operators .
26,038
def to_nnf ( self ) : node = self . node . to_nnf ( ) if node is self . node : return self else : return _expr ( node )
Return an equivalent expression is negation normal form .
26,039
def to_dnf ( self ) : node = self . node . to_dnf ( ) if node is self . node : return self else : return _expr ( node )
Return an equivalent expression in disjunctive normal form .
26,040
def to_cnf ( self ) : node = self . node . to_cnf ( ) if node is self . node : return self else : return _expr ( node )
Return an equivalent expression in conjunctive normal form .
26,041
def complete_sum ( self ) : node = self . node . complete_sum ( ) if node is self . node : return self else : return _expr ( node )
Return an equivalent DNF expression that includes all prime implicants .
26,042
def expand ( self , vs = None , conj = False ) : vs = self . _expect_vars ( vs ) if vs : outer , inner = ( And , Or ) if conj else ( Or , And ) terms = [ inner ( self . restrict ( p ) , * boolfunc . point2term ( p , conj ) ) for p in boolfunc . iter_points ( vs ) ] if conj : terms = [ term for term in terms if term is ...
Return the Shannon expansion with respect to a list of variables .
26,043
def encode_inputs ( self ) : litmap = dict ( ) nvars = 0 for i , v in enumerate ( self . inputs , start = 1 ) : litmap [ v ] = i litmap [ ~ v ] = - i litmap [ i ] = v litmap [ - i ] = ~ v nvars += 1 return litmap , nvars
Return a compact encoding for input variables .
26,044
def tseitin ( self , auxvarname = 'aux' ) : if self . is_cnf ( ) : return self _ , constraints = _tseitin ( self . to_nnf ( ) , auxvarname ) fst = constraints [ - 1 ] [ 1 ] rst = [ Equal ( v , ex ) . to_cnf ( ) for v , ex in constraints [ : - 1 ] ] return And ( fst , * rst )
Convert the expression to Tseitin s encoding .
26,045
def equivalent ( self , other ) : f = Xor ( self , self . box ( other ) ) return f . satisfy_one ( ) is None
Return True if this expression is equivalent to other .
26,046
def reduce ( self ) : support = frozenset ( range ( 1 , self . nvars + 1 ) ) new_clauses = set ( ) for clause in self . clauses : vs = list ( support - { abs ( uniqid ) for uniqid in clause } ) if vs : for num in range ( 1 << len ( vs ) ) : new_part = { v if bit_on ( num , i ) else ~ v for i , v in enumerate ( vs ) } n...
Reduce to a canonical form .
26,047
def decode ( self , litmap ) : return Or ( * [ And ( * [ litmap [ idx ] for idx in clause ] ) for clause in self . clauses ] )
Convert the DNF to an expression .
26,048
def satisfy_one ( self , assumptions = None , ** params ) : verbosity = params . get ( 'verbosity' , 0 ) default_phase = params . get ( 'default_phase' , 2 ) propagation_limit = params . get ( 'propagation_limit' , - 1 ) decision_limit = params . get ( 'decision_limit' , - 1 ) seed = params . get ( 'seed' , 1 ) return ...
If the input CNF is satisfiable return a satisfying input point . A contradiction will return None .
26,049
def satisfy_all ( self , ** params ) : verbosity = params . get ( 'verbosity' , 0 ) default_phase = params . get ( 'default_phase' , 2 ) propagation_limit = params . get ( 'propagation_limit' , - 1 ) decision_limit = params . get ( 'decision_limit' , - 1 ) seed = params . get ( 'seed' , 1 ) yield from picosat . satisfy...
Iterate through all satisfying input points .
26,050
def soln2point ( soln , litmap ) : return { litmap [ i ] : int ( val > 0 ) for i , val in enumerate ( soln , start = 1 ) }
Convert a solution vector to a point .
26,051
def _cover2exprs ( inputs , noutputs , cover ) : fs = list ( ) for i in range ( noutputs ) : terms = list ( ) for invec , outvec in cover : if outvec [ i ] : term = list ( ) for j , v in enumerate ( inputs ) : if invec [ j ] == 1 : term . append ( ~ v ) elif invec [ j ] == 2 : term . append ( v ) terms . append ( term ...
Convert a cover to a tuple of Expression instances .
26,052
def fcat ( * fs ) : items = list ( ) for f in fs : if isinstance ( f , boolfunc . Function ) : items . append ( f ) elif isinstance ( f , farray ) : items . extend ( f . flat ) else : raise TypeError ( "expected Function or farray" ) return farray ( items )
Concatenate a sequence of farrays .
26,053
def _dims2shape ( * dims ) : if not dims : raise ValueError ( "expected at least one dimension spec" ) shape = list ( ) for dim in dims : if isinstance ( dim , int ) : dim = ( 0 , dim ) if isinstance ( dim , tuple ) and len ( dim ) == 2 : if dim [ 0 ] < 0 : raise ValueError ( "expected low dimension to be >= 0" ) if di...
Convert input dimensions to a shape .
26,054
def _volume ( shape ) : prod = 1 for start , stop in shape : prod *= stop - start return prod
Return the volume of a shape .
26,055
def _zeros ( ftype , * dims ) : shape = _dims2shape ( * dims ) objs = [ ftype . box ( 0 ) for _ in range ( _volume ( shape ) ) ] return farray ( objs , shape , ftype )
Return a new farray filled with zeros .
26,056
def _vars ( ftype , name , * dims ) : shape = _dims2shape ( * dims ) objs = list ( ) for indices in itertools . product ( * [ range ( i , j ) for i , j in shape ] ) : objs . append ( _VAR [ ftype ] ( name , indices ) ) return farray ( objs , shape , ftype )
Return a new farray filled with Boolean variables .
26,057
def _uint2objs ( ftype , num , length = None ) : if num == 0 : objs = [ ftype . box ( 0 ) ] else : _num = num objs = list ( ) while _num != 0 : objs . append ( ftype . box ( _num & 1 ) ) _num >>= 1 if length : if length < len ( objs ) : fstr = "overflow: num = {} requires length >= {}, got length = {}" raise ValueError...
Convert an unsigned integer to a list of constant expressions .
26,058
def _uint2farray ( ftype , num , length = None ) : if num < 0 : raise ValueError ( "expected num >= 0" ) else : objs = _uint2objs ( ftype , num , length ) return farray ( objs )
Convert an unsigned integer to an farray .
26,059
def _int2farray ( ftype , num , length = None ) : if num < 0 : req_length = clog2 ( abs ( num ) ) + 1 objs = _uint2objs ( ftype , 2 ** req_length + num ) else : req_length = clog2 ( num + 1 ) + 1 objs = _uint2objs ( ftype , num , req_length ) if length : if length < req_length : fstr = "overflow: num = {} requires leng...
Convert a signed integer to an farray .
26,060
def _itemize ( objs ) : if not isinstance ( objs , collections . Sequence ) : raise TypeError ( "expected a sequence of Function" ) isseq = [ isinstance ( obj , collections . Sequence ) for obj in objs ] if not any ( isseq ) : ftype = None for obj in objs : if ftype is None : if isinstance ( obj , BinaryDecisionDiagram...
Recursive helper function for farray .
26,061
def _check_shape ( shape ) : if isinstance ( shape , tuple ) : for dim in shape : if ( isinstance ( dim , tuple ) and len ( dim ) == 2 and isinstance ( dim [ 0 ] , int ) and isinstance ( dim [ 1 ] , int ) ) : if dim [ 0 ] < 0 : raise ValueError ( "expected low dimension to be >= 0" ) if dim [ 1 ] < 0 : raise ValueError...
Verify that a shape has the right format .
26,062
def _norm_index ( dim , index , start , stop ) : length = stop - start if - length <= index < 0 : normindex = index + length elif start <= index < stop : normindex = index - start else : fstr = "expected dim {} index in range [{}, {})" raise IndexError ( fstr . format ( dim , start , stop ) ) return normindex
Return an index normalized to an farray start index .
26,063
def _norm_slice ( sl , start , stop ) : length = stop - start if sl . start is None : normstart = 0 else : if sl . start < 0 : if sl . start < - length : normstart = 0 else : normstart = sl . start + length else : if sl . start > stop : normstart = length else : normstart = sl . start - start if sl . stop is None : nor...
Return a slice normalized to an farray start index .
26,064
def _filtdim ( items , shape , dim , nsl ) : normshape = tuple ( stop - start for start , stop in shape ) nsl_type = type ( nsl ) newitems = list ( ) num = reduce ( operator . mul , normshape [ : dim + 1 ] ) size = len ( items ) // num n = normshape [ dim ] if nsl_type is int : for i in range ( num ) : if i % n == nsl ...
Return items shape filtered by a dimension slice .
26,065
def _iter_coords ( nsls ) : ranges = list ( ) for nsl in nsls : if isinstance ( nsl , int ) : ranges . append ( range ( nsl , nsl + 1 ) ) else : ranges . append ( range ( nsl . start , nsl . stop ) ) yield from itertools . product ( * ranges )
Iterate through all matching coordinates in a sequence of slices .
26,066
def restrict ( self , point ) : items = [ f . restrict ( point ) for f in self . _items ] return self . __class__ ( items , self . shape , self . ftype )
Apply the restrict method to all functions .
26,067
def compose ( self , mapping ) : items = [ f . compose ( mapping ) for f in self . _items ] return self . __class__ ( items , self . shape , self . ftype )
Apply the compose method to all functions .
26,068
def reshape ( self , * dims ) : shape = _dims2shape ( * dims ) if _volume ( shape ) != self . size : raise ValueError ( "expected shape with equal volume" ) return self . __class__ ( self . _items , shape , self . ftype )
Return an equivalent farray with a modified shape .
26,069
def to_uint ( self ) : num = 0 for i , f in enumerate ( self . _items ) : if f . is_zero ( ) : pass elif f . is_one ( ) : num += 1 << i else : fstr = "expected all functions to be a constant (0 or 1) form" raise ValueError ( fstr ) return num
Convert vector to an unsigned integer if possible .
26,070
def to_int ( self ) : num = self . to_uint ( ) if num and self . _items [ - 1 ] . unbox ( ) : return num - ( 1 << self . size ) else : return num
Convert vector to an integer if possible .
26,071
def uor ( self ) : return reduce ( operator . or_ , self . _items , self . ftype . box ( 0 ) )
Unary OR reduction operator
26,072
def uand ( self ) : return reduce ( operator . and_ , self . _items , self . ftype . box ( 1 ) )
Unary AND reduction operator
26,073
def uxor ( self ) : return reduce ( operator . xor , self . _items , self . ftype . box ( 0 ) )
Unary XOR reduction operator
26,074
def _keys2sls ( self , keys , key2sl ) : sls = list ( ) if isinstance ( keys , tuple ) : for key in keys : sls . append ( key2sl ( key ) ) else : sls . append ( key2sl ( keys ) ) if len ( sls ) > self . ndim : fstr = "expected <= {0.ndim} slice dimensions, got {1}" raise ValueError ( fstr . format ( self , len ( sls ) ...
Convert an input key to a list of slices .
26,075
def _coord2offset ( self , coord ) : size = self . size offset = 0 for dim , index in enumerate ( coord ) : size //= self . _normshape [ dim ] offset += size * index return offset
Convert a normalized coordinate to an item offset .
26,076
def _op_shape ( self , other ) : if isinstance ( other , farray ) : if self . shape == other . shape : return self . shape elif self . size == other . size : return None else : raise ValueError ( "expected operand sizes to match" ) else : raise TypeError ( "expected farray input" )
Return shape that will be used by farray constructor .
26,077
def delete_records ( keep = 20 ) : sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}" . format ( keep ) assert isinstance ( g . db , sqlite3 . Connection ) c = g . db . cursor ( ) c . execute ( sql ) rows = c . fetchall ( ) for row in rows : name = row [ 1 ] xmind = join ( app . confi...
Clean up files on server and mark the record as deleted
26,078
def check_expected_errors ( self , test_method ) : f = lambda key , default = [ ] : getattr ( test_method , key , default ) expected_error_page = f ( EXPECTED_ERROR_PAGE , default = None ) allowed_error_pages = f ( ALLOWED_ERROR_PAGES ) expected_error_messages = f ( EXPECTED_ERROR_MESSAGES ) allowed_error_messages = f ...
This method is called after each test . It will read decorated informations and check if there are expected errors .
26,079
def get_error_page ( self ) : try : error_page = self . get_elm ( class_name = 'error-page' ) except NoSuchElementException : pass else : header = error_page . get_elm ( tag_name = 'h1' ) return header . text
Method returning error page . Should return string .
26,080
def get_error_traceback ( self ) : try : error_page = self . get_elm ( class_name = 'error-page' ) traceback = error_page . get_elm ( class_name = 'traceback' ) except NoSuchElementException : pass else : return traceback . text
Method returning traceback of error page .
26,081
def get_error_messages ( self ) : try : error_elms = self . get_elms ( class_name = 'error' ) except NoSuchElementException : return [ ] else : try : error_values = [ error_elm . get_attribute ( 'error' ) for error_elm in error_elms ] except Exception : error_values = [ error_elm . text for error_elm in error_elms ] fi...
Method returning error messages . Should return list of messages .
26,082
def check_expected_infos ( self , test_method ) : f = lambda key , default = [ ] : getattr ( test_method , key , default ) expected_info_messages = f ( EXPECTED_INFO_MESSAGES ) allowed_info_messages = f ( ALLOWED_INFO_MESSAGES ) self . check_infos ( expected_info_messages , allowed_info_messages )
This method is called after each test . It will read decorated informations and check if there are expected infos .
26,083
def get_info_messages ( self ) : try : info_elms = self . get_elms ( class_name = 'info' ) except NoSuchElementException : return [ ] else : try : info_values = [ info_elm . get_attribute ( 'info' ) for info_elm in info_elms ] except Exception : info_values = [ info_elm . text for info_elm in info_elms ] finally : retu...
Method returning info messages . Should return list of messages .
26,084
def _make_instance ( cls , element_class , webelement ) : if isinstance ( webelement , FirefoxWebElement ) : element_class = copy . deepcopy ( element_class ) element_class . __bases__ = tuple ( FirefoxWebElement if base is WebElement else base for base in element_class . __bases__ ) return element_class ( webelement )
Firefox uses another implementation of element . This method switch base of wrapped element to firefox one .
26,085
def html ( self ) : try : body = self . get_elm ( tag_name = 'body' ) except selenium_exc . NoSuchElementException : return None else : return body . get_attribute ( 'innerHTML' )
Returns innerHTML of whole page . On page have to be tag body .
26,086
def switch_to_window ( self , window_name = None , title = None , url = None ) : if window_name : self . switch_to . window ( window_name ) return if url : url = self . get_url ( path = url ) for window_handle in self . window_handles : self . switch_to . window ( window_handle ) if title and self . title == title : re...
WebDriver implements switching to other window only by it s name . With wrapper there is also option to switch by title of window or URL . URL can be also relative path .
26,087
def close_window ( self , window_name = None , title = None , url = None ) : main_window_handle = self . current_window_handle self . switch_to_window ( window_name , title , url ) self . close ( ) self . switch_to_window ( main_window_handle )
WebDriver implements only closing current window . If you want to close some window without having to switch to it use this method .
26,088
def close_other_windows ( self ) : main_window_handle = self . current_window_handle for window_handle in self . window_handles : if window_handle == main_window_handle : continue self . switch_to_window ( window_handle ) self . close ( ) self . switch_to_window ( main_window_handle )
Closes all not current windows . Useful for tests - after each test you can automatically close all windows .
26,089
def close_alert ( self , ignore_exception = False ) : try : alert = self . get_alert ( ) alert . accept ( ) except : if not ignore_exception : raise
JS alerts all blocking . This method closes it . If there is no alert method raises exception . In tests is good to call this method with ignore_exception setted to True which will ignore any exception .
26,090
def wait_for_alert ( self , timeout = None ) : if not timeout : timeout = self . default_wait_timeout alert = Alert ( self ) def alert_shown ( driver ) : try : alert . text return True except selenium_exc . NoAlertPresentException : return False self . wait ( timeout ) . until ( alert_shown ) return alert
Shortcut for waiting for alert . If it not ends with exception it returns that alert . Detault timeout is ~ . default_wait_timeout .
26,091
def type_name ( self ) -> T . Optional [ str ] : return self . args [ 1 ] if len ( self . args ) > 1 else None
Return type name associated with given docstring metadata .
26,092
def params ( self ) -> T . List [ DocstringParam ] : return [ DocstringParam . from_meta ( meta ) for meta in self . meta if meta . args [ 0 ] in { "param" , "parameter" , "arg" , "argument" , "key" , "keyword" } ]
Return parameters indicated in docstring .
26,093
def raises ( self ) -> T . List [ DocstringRaises ] : return [ DocstringRaises . from_meta ( meta ) for meta in self . meta if meta . args [ 0 ] in { "raises" , "raise" , "except" , "exception" } ]
Return exceptions indicated in docstring .
26,094
def returns ( self ) -> T . Optional [ DocstringReturns ] : try : return next ( DocstringReturns . from_meta ( meta ) for meta in self . meta if meta . args [ 0 ] in { "return" , "returns" , "yield" , "yields" } ) except StopIteration : return None
Return return information indicated in docstring .
26,095
def _build_meta ( text : str , title : str ) -> DocstringMeta : meta = _sections [ title ] if meta == "returns" and ":" not in text . split ( ) [ 0 ] : return DocstringMeta ( [ meta ] , description = text ) before , desc = text . split ( ":" , 1 ) if desc : desc = desc [ 1 : ] if desc [ 0 ] == " " else desc if "\n" in ...
Build docstring element .
26,096
def parse ( text : str ) -> Docstring : ret = Docstring ( ) if not text : return ret text = inspect . cleandoc ( text ) match = _titles_re . search ( text ) if match : desc_chunk = text [ : match . start ( ) ] meta_chunk = text [ match . start ( ) : ] else : desc_chunk = text meta_chunk = "" parts = desc_chunk . split ...
Parse the Google - style docstring into its components .
26,097
def _determine_tool ( files ) : for file in files : linker_ext = file . split ( '.' ) [ - 1 ] if "sct" in linker_ext or "lin" in linker_ext : yield ( str ( file ) , "uvision" ) elif "ld" in linker_ext : yield ( str ( file ) , "make_gcc_arm" ) elif "icf" in linker_ext : yield ( str ( file ) , "iar_arm" )
Yields tuples in the form of ( linker file tool the file links for
26,098
def _get_option ( self , settings , find_key ) : for option in settings : if option [ 'name' ] == find_key : return settings . index ( option )
Return index for provided key
26,099
def _ewp_flags_set ( self , ewp_dic_subset , project_dic , flag_type , flag_dic ) : try : if flag_type in project_dic [ 'misc' ] . keys ( ) : index_option = self . _get_option ( ewp_dic_subset , flag_dic [ 'enable' ] ) self . _set_option ( ewp_dic_subset [ index_option ] , '1' ) index_option = self . _get_option ( ewp_...
Flags from misc to set to ewp project