idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
62,700
def edit_secondary_name_server ( self , zone_name , primary = None , backup = None , second_backup = None ) : name_server_info = { } if primary is not None : name_server_info [ 'nameServerIp1' ] = { 'ip' : primary } if backup is not None : name_server_info [ 'nameServerIp2' ] = { 'ip' : backup } if second_backup is not None : name_server_info [ 'nameServerIp3' ] = { 'ip' : second_backup } name_server_ip_list = { "nameServerIpList" : name_server_info } secondary_zone_info = { "primaryNameServers" : name_server_ip_list } zone_data = { "secondaryCreateInfo" : secondary_zone_info } return self . rest_api_connection . patch ( "/v1/zones/" + zone_name , json . dumps ( zone_data ) )
Edit the axfr name servers of a secondary zone .
62,701
def get_rrsets ( self , zone_name , q = None , ** kwargs ) : uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params ( q , kwargs ) return self . rest_api_connection . get ( uri , params )
Returns the list of RRSets in the specified zone .
62,702
def create_rrset ( self , zone_name , rtype , owner_name , ttl , rdata ) : if type ( rdata ) is not list : rdata = [ rdata ] rrset = { "ttl" : ttl , "rdata" : rdata } return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name , json . dumps ( rrset ) )
Creates a new RRSet in the specified zone .
62,703
def edit_rrset ( self , zone_name , rtype , owner_name , ttl , rdata , profile = None ) : if type ( rdata ) is not list : rdata = [ rdata ] rrset = { "ttl" : ttl , "rdata" : rdata } if profile : rrset [ "profile" ] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self . rest_api_connection . put ( uri , json . dumps ( rrset ) )
Updates an existing RRSet in the specified zone .
62,704
def edit_rrset_rdata ( self , zone_name , rtype , owner_name , rdata , profile = None ) : if type ( rdata ) is not list : rdata = [ rdata ] rrset = { "rdata" : rdata } method = "patch" if profile : rrset [ "profile" ] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr ( self . rest_api_connection , method ) ( uri , json . dumps ( rrset ) )
Updates an existing RRSet s Rdata in the specified zone .
62,705
def delete_rrset ( self , zone_name , rtype , owner_name ) : return self . rest_api_connection . delete ( "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name )
Deletes an RRSet .
62,706
def create_web_forward ( self , zone_name , request_to , redirect_to , forward_type ) : web_forward = { "requestTo" : request_to , "defaultRedirectTo" : redirect_to , "defaultForwardType" : forward_type } return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/webforwards" , json . dumps ( web_forward ) )
Create a web forward record .
62,707
def create_sb_pool ( self , zone_name , owner_name , ttl , pool_info , rdata_info , backup_record_list ) : rrset = self . _build_sb_rrset ( backup_record_list , pool_info , rdata_info , ttl ) return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/A/" + owner_name , json . dumps ( rrset ) )
Creates a new SB Pool .
62,708
def create_tc_pool ( self , zone_name , owner_name , ttl , pool_info , rdata_info , backup_record ) : rrset = self . _build_tc_rrset ( backup_record , pool_info , rdata_info , ttl ) return self . rest_api_connection . post ( "/v1/zones/" + zone_name + "/rrsets/A/" + owner_name , json . dumps ( rrset ) )
Creates a new TC Pool .
62,709
def remove ( self , other ) : if other is FullSpace : return TrivialSpace if other is TrivialSpace : return self if isinstance ( other , ProductSpace ) : oops = set ( other . operands ) else : oops = { other } return ProductSpace . create ( * sorted ( set ( self . operands ) . difference ( oops ) ) )
Remove a particular factor from a tensor product space .
62,710
def intersect ( self , other ) : if other is FullSpace : return self if other is TrivialSpace : return TrivialSpace if isinstance ( other , ProductSpace ) : other_ops = set ( other . operands ) else : other_ops = { other } return ProductSpace . create ( * sorted ( set ( self . operands ) . intersection ( other_ops ) ) )
Find the mutual tensor factors of two Hilbert spaces .
62,711
def _isinstance ( expr , classname ) : for cls in type ( expr ) . __mro__ : if cls . __name__ == classname : return True return False
Check whether expr is an instance of the class with name classname
62,712
def decompose_space ( H , A ) : return OperatorTrace . create ( OperatorTrace . create ( A , over_space = H . operands [ - 1 ] ) , over_space = ProductSpace . create ( * H . operands [ : - 1 ] ) )
Simplifies OperatorTrace expressions over tensor - product spaces by turning it into iterated partial traces .
62,713
def factor_coeff ( cls , ops , kwargs ) : coeffs , nops = zip ( * map ( _coeff_term , ops ) ) coeff = 1 for c in coeffs : coeff *= c if coeff == 1 : return nops , coeffs else : return coeff * cls . create ( * nops , ** kwargs )
Factor out coefficients of all factors .
62,714
def doit ( self , classes = None , recursive = True , ** kwargs ) : return super ( ) . doit ( classes , recursive , ** kwargs )
Write out commutator
62,715
def _attrprint ( d , delimiter = ', ' ) : return delimiter . join ( ( '"%s"="%s"' % item ) for item in sorted ( d . items ( ) ) )
Print a dictionary of attributes in the DOT format
62,716
def _styleof ( expr , styles ) : style = dict ( ) for expr_filter , sty in styles : if expr_filter ( expr ) : style . update ( sty ) return style
Merge style dictionaries in order
62,717
def _git_version ( ) : import subprocess import os def _minimal_ext_cmd ( cmd ) : env = { } for k in [ 'SYSTEMROOT' , 'PATH' ] : v = os . environ . get ( k ) if v is not None : env [ k ] = v env [ 'LANGUAGE' ] = 'C' env [ 'LANG' ] = 'C' env [ 'LC_ALL' ] = 'C' FNULL = open ( os . devnull , 'w' ) cwd = os . path . dirname ( os . path . realpath ( __file__ ) ) proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = FNULL , env = env , cwd = cwd ) out = proc . communicate ( ) [ 0 ] return out try : out = _minimal_ext_cmd ( [ 'git' , 'rev-parse' , 'HEAD' ] ) return out . strip ( ) . decode ( 'ascii' ) except OSError : return "unknown"
If installed with pip installe - e . from inside a git repo the current git revision as a string
62,718
def pad_with_identity ( circuit , k , n ) : circuit_n = circuit . cdim combined_circuit = circuit + circuit_identity ( n ) permutation = ( list ( range ( k ) ) + list ( range ( circuit_n , circuit_n + n ) ) + list ( range ( k , circuit_n ) ) ) return ( CPermutation . create ( invert_permutation ( permutation ) ) << combined_circuit << CPermutation . create ( permutation ) )
Pad a circuit by adding a n - channel identity circuit at index k
62,719
def move_drive_to_H ( slh , which = None , expand_simplify = True ) : r if which is None : which = [ ] scalarcs = [ ] for jj , L in enumerate ( slh . Ls ) : if not which or jj in which : scalarcs . append ( - get_coeffs ( L . expand ( ) ) [ IdentityOperator ] ) else : scalarcs . append ( 0 ) if np . all ( np . array ( scalarcs ) == 0 ) : return slh new_slh = SLH ( identity_matrix ( slh . cdim ) , scalarcs , 0 ) << slh if expand_simplify : return new_slh . expand ( ) . simplify_scalar ( ) return new_slh
r Move coherent drives from the Lindblad operators to the Hamiltonian .
62,720
def prepare_adiabatic_limit ( slh , k = None ) : if k is None : k = symbols ( 'k' , positive = True ) Ld = slh . L . dag ( ) LdL = ( Ld * slh . L ) [ 0 , 0 ] K = ( - LdL / 2 + I * slh . H ) . expand ( ) . simplify_scalar ( ) N = slh . S . dag ( ) B , A , Y = K . series_expand ( k , 0 , 2 ) G , F = Ld . series_expand ( k , 0 , 1 ) return Y , A , B , F , G , N
Prepare the adiabatic elimination on an SLH object
62,721
def eval_adiabatic_limit ( YABFGN , Ytilde , P0 ) : Y , A , B , F , G , N = YABFGN Klim = ( P0 * ( B - A * Ytilde * A ) * P0 ) . expand ( ) . simplify_scalar ( ) Hlim = ( ( Klim - Klim . dag ( ) ) / 2 / I ) . expand ( ) . simplify_scalar ( ) Ldlim = ( P0 * ( G - A * Ytilde * F ) * P0 ) . expand ( ) . simplify_scalar ( ) dN = identity_matrix ( N . shape [ 0 ] ) + F . H * Ytilde * F Nlim = ( P0 * N * dN * P0 ) . expand ( ) . simplify_scalar ( ) return SLH ( Nlim . dag ( ) , Ldlim . dag ( ) , Hlim . dag ( ) )
Compute the limiting SLH model for the adiabatic approximation
62,722
def try_adiabatic_elimination ( slh , k = None , fock_trunc = 6 , sub_P0 = True ) : ops = prepare_adiabatic_limit ( slh , k ) Y = ops [ 0 ] if isinstance ( Y . space , LocalSpace ) : try : b = Y . space . basis_labels if len ( b ) > fock_trunc : b = b [ : fock_trunc ] except BasisNotSetError : b = range ( fock_trunc ) projectors = set ( LocalProjector ( ll , hs = Y . space ) for ll in b ) Id_trunc = sum ( projectors , ZeroOperator ) Yprojection = ( ( ( Id_trunc * Y ) . expand ( ) * Id_trunc ) . expand ( ) . simplify_scalar ( ) ) termcoeffs = get_coeffs ( Yprojection ) terms = set ( termcoeffs . keys ( ) ) for term in terms - projectors : cannot_eliminate = ( not isinstance ( term , LocalSigma ) or not term . operands [ 1 ] == term . operands [ 2 ] ) if cannot_eliminate : raise CannotEliminateAutomatically ( "Proj. Y operator has off-diagonal term: ~{}" . format ( term ) ) P0 = sum ( projectors - terms , ZeroOperator ) if P0 == ZeroOperator : raise CannotEliminateAutomatically ( "Empty null-space of Y!" ) Yinv = sum ( t / termcoeffs [ t ] for t in terms & projectors ) assert ( ( Yprojection * Yinv ) . expand ( ) . simplify_scalar ( ) == ( Id_trunc - P0 ) . expand ( ) ) slhlim = eval_adiabatic_limit ( ops , Yinv , P0 ) if sub_P0 : slhlim = slhlim . substitute ( { P0 : IdentityOperator } ) . expand ( ) . simplify_scalar ( ) return slhlim else : raise CannotEliminateAutomatically ( "Currently only single degree of freedom Y-operators supported" )
Attempt to automatically do adiabatic elimination on an SLH object
62,723
def index_in_block ( self , channel_index : int ) -> int : if channel_index < 0 or channel_index >= self . cdim : raise ValueError ( ) struct = self . block_structure if len ( struct ) == 1 : return channel_index , 0 i = 1 while sum ( struct [ : i ] ) <= channel_index and i < self . cdim : i += 1 block_index = i - 1 index_in_block = channel_index - sum ( struct [ : block_index ] ) return index_in_block , block_index
Return the index a channel has within the subblock it belongs to
62,724
def get_blocks ( self , block_structure = None ) : if block_structure is None : block_structure = self . block_structure try : return self . _get_blocks ( block_structure ) except IncompatibleBlockStructures as e : raise e
For a reducible circuit get a sequence of subblocks that when concatenated again yield the original circuit . The block structure given has to be compatible with the circuits actual block structure i . e . it can only be more coarse - grained .
62,725
def show ( self ) : from IPython . display import Image , display fname = self . render ( ) display ( Image ( filename = fname ) )
Show the circuit expression in an IPython notebook .
62,726
def render ( self , fname = '' ) : import qnet . visualization . circuit_pyx as circuit_visualization from tempfile import gettempdir from time import time , sleep if not fname : tmp_dir = gettempdir ( ) fname = os . path . join ( tmp_dir , "tmp_{}.png" . format ( hash ( time ) ) ) if circuit_visualization . draw_circuit ( self , fname ) : done = False for k in range ( 20 ) : if os . path . exists ( fname ) : done = True break else : sleep ( .5 ) if done : return fname raise CannotVisualize ( )
Render the circuit expression and store the result in a file
62,727
def space ( self ) : args_spaces = ( self . S . space , self . L . space , self . H . space ) return ProductSpace . create ( * args_spaces )
Total Hilbert space
62,728
def free_symbols ( self ) : return set . union ( self . S . free_symbols , self . L . free_symbols , self . H . free_symbols )
Set of all symbols occcuring in S L or H
62,729
def expand ( self ) : return SLH ( self . S . expand ( ) , self . L . expand ( ) , self . H . expand ( ) )
Expand out all operator expressions within S L and H
62,730
def simplify_scalar ( self , func = sympy . simplify ) : return SLH ( self . S . simplify_scalar ( func = func ) , self . L . simplify_scalar ( func = func ) , self . H . simplify_scalar ( func = func ) )
Simplify all scalar expressions within S L and H
62,731
def symbolic_master_equation ( self , rho = None ) : L , H = self . L , self . H if rho is None : rho = OperatorSymbol ( 'rho' , hs = self . space ) return ( - I * ( H * rho - rho * H ) + sum ( Lk * rho * adjoint ( Lk ) - ( adjoint ( Lk ) * Lk * rho + rho * adjoint ( Lk ) * Lk ) / 2 for Lk in L . matrix . ravel ( ) ) )
Compute the symbolic Liouvillian acting on a state rho
62,732
def symbolic_heisenberg_eom ( self , X = None , noises = None , expand_simplify = True ) : L , H = self . L , self . H if X is None : X = OperatorSymbol ( 'X' , hs = ( L . space | H . space ) ) summands = [ I * ( H * X - X * H ) , ] for Lk in L . matrix . ravel ( ) : summands . append ( adjoint ( Lk ) * X * Lk ) summands . append ( - ( adjoint ( Lk ) * Lk * X + X * adjoint ( Lk ) * Lk ) / 2 ) if noises is not None : if not isinstance ( noises , Matrix ) : noises = Matrix ( noises ) LambdaT = ( noises . adjoint ( ) . transpose ( ) * noises . transpose ( ) ) . transpose ( ) assert noises . shape == L . shape S = self . S summands . append ( ( adjoint ( noises ) * S . adjoint ( ) * ( X * L - L * X ) ) . expand ( ) [ 0 , 0 ] ) summand = ( ( ( L . adjoint ( ) * X - X * L . adjoint ( ) ) * S * noises ) . expand ( ) [ 0 , 0 ] ) summands . append ( summand ) if len ( S . space & X . space ) : comm = ( S . adjoint ( ) * X * S - X ) summands . append ( ( comm * LambdaT ) . expand ( ) . trace ( ) ) ret = OperatorPlus . create ( * summands ) if expand_simplify : ret = ret . expand ( ) . simplify_scalar ( ) return ret
Compute the symbolic Heisenberg equations of motion of a system operator X . If no X is given an OperatorSymbol is created in its place . If no noises are given this correspnds to the ensemble - averaged Heisenberg equation of motion .
62,733
def block_perms ( self ) : if not self . _block_perms : self . _block_perms = permutation_to_block_permutations ( self . permutation ) return self . _block_perms
If the circuit is reducible into permutations within subranges of the full range of channels this yields a tuple with the internal permutations for each such block .
62,734
def series_with_permutation ( self , other ) : combined_permutation = tuple ( [ self . permutation [ p ] for p in other . permutation ] ) return CPermutation . create ( combined_permutation )
Compute the series product with another channel permutation circuit
62,735
def save ( self , data , chart_type , options = None , filename = 'chart' , w = 800 , h = 420 , overwrite = True ) : html = self . render ( data = data , chart_type = chart_type , options = options , div_id = filename , head = self . head , w = w , h = h ) if overwrite : with open ( filename . replace ( " " , "_" ) + '.html' , 'w' ) as f : f . write ( html ) else : if not os . path . exists ( filename . replace ( " " , "_" ) + '.html' ) : with open ( filename . replace ( " " , "_" ) + '.html' , 'w' ) as f : f . write ( html ) else : raise IOError ( 'File Already Exists!' )
Save the rendered html to a file in the same directory as the notebook .
62,736
def _unicode_sub_super ( string , mapping , max_len = None ) : string = str ( string ) if string . startswith ( '(' ) and string . endswith ( ')' ) : len_string = len ( string ) - 2 else : len_string = len ( string ) if max_len is not None : if len_string > max_len : raise KeyError ( "max_len exceeded" ) unicode_letters = [ ] for letter in string : unicode_letters . append ( mapping [ letter ] ) return '' . join ( unicode_letters )
Try to render a subscript or superscript string in unicode fall back on ascii if this is not possible
62,737
def _translate_symbols ( string ) : res = [ ] string = str ( string ) for s in re . split ( r'(\W+)' , string , flags = re . UNICODE ) : tex_str = _GREEK_DICTIONARY . get ( s ) if tex_str : res . append ( tex_str ) elif s . lower ( ) in _GREEK_DICTIONARY : res . append ( _GREEK_DICTIONARY [ s ] ) else : res . append ( s ) return "" . join ( res )
Given a description of a Greek letter or other special character return the appropriate unicode letter .
62,738
def plot_and_save ( self , data , w = 800 , h = 420 , filename = 'chart' , overwrite = True ) : self . save ( data , filename , overwrite ) return IFrame ( filename + '.html' , w , h )
Save the rendered html to a file and returns an IFrame to display the plot in the notebook .
62,739
def _get_from_cache ( self , expr ) : is_cached , res = super ( ) . _get_from_cache ( expr ) if is_cached : indent_str = " " * self . _print_level return True , indent ( res , indent_str ) else : return False , None
Obtain cached result prepend with the keyname if necessary and indent for the current level
62,740
def _write_to_cache ( self , expr , res ) : res = dedent ( res ) super ( ) . _write_to_cache ( expr , res )
Store the cached result without indentation and without the keyname
62,741
def _translate_symbols ( string ) : res = [ ] for s in re . split ( r'([,.:\s=]+)' , string ) : tex_str = _TEX_GREEK_DICTIONARY . get ( s ) if tex_str : res . append ( tex_str ) elif s . lower ( ) in greek_letters_set : res . append ( "\\" + s . lower ( ) ) elif s in other_symbols : res . append ( "\\" + s ) else : if re . match ( r'^[a-zA-Z]{4,}$' , s ) : res . append ( r'\text{' + s + '}' ) else : res . append ( s ) return "" . join ( res )
Given a description of a Greek letter or other special character return the appropriate latex .
62,742
def _render_str ( self , string ) : if isinstance ( string , StrLabel ) : string = string . _render ( string . expr ) string = str ( string ) if len ( string ) == 0 : return '' name , supers , subs = split_super_sub ( string ) return render_latex_sub_super ( name , subs , supers , translate_symbols = True )
Returned a texified version of the string
62,743
def is_symbol ( string ) : return ( is_int ( string ) or is_float ( string ) or is_constant ( string ) or is_unary ( string ) or is_binary ( string ) or ( string == '(' ) or ( string == ')' ) )
Return true if the string is a mathematical symbol .
62,744
def find_word_groups ( string , words ) : scale_pattern = '|' . join ( words ) regex = re . compile ( r'(?:(?:\d+)\s+(?:' + scale_pattern + r')*\s*)+(?:\d+|' + scale_pattern + r')+' ) result = regex . findall ( string ) return result
Find matches for words in the format 3 thousand 6 hundred 2 . The words parameter should be the list of words to check for such as hundred .
62,745
def replace_word_tokens ( string , language ) : words = mathwords . word_groups_for_language ( language ) operators = words [ 'binary_operators' ] . copy ( ) if 'unary_operators' in words : operators . update ( words [ 'unary_operators' ] ) for operator in list ( operators . keys ( ) ) : if operator in string : string = string . replace ( operator , operators [ operator ] ) numbers = words [ 'numbers' ] for number in list ( numbers . keys ( ) ) : if number in string : string = string . replace ( number , str ( numbers [ number ] ) ) scales = words [ 'scales' ] end_index_characters = mathwords . BINARY_OPERATORS end_index_characters . add ( '(' ) word_matches = find_word_groups ( string , list ( scales . keys ( ) ) ) for match in word_matches : string = string . replace ( match , '(' + match + ')' ) for scale in list ( scales . keys ( ) ) : for _ in range ( 0 , string . count ( scale ) ) : start_index = string . find ( scale ) - 1 end_index = len ( string ) while is_int ( string [ start_index - 1 ] ) and start_index > 0 : start_index -= 1 end_index = string . find ( ' ' , start_index ) + 1 end_index = string . find ( ' ' , end_index ) + 1 add = ' + ' if string [ end_index ] in end_index_characters : add = '' string = string [ : start_index ] + '(' + string [ start_index : ] string = string . replace ( scale , '* ' + str ( scales [ scale ] ) + ')' + add , 1 ) string = string . replace ( ') (' , ') + (' ) return string
Given a string and an ISO 639 - 2 language code return the string with the words replaced with an operational equivalent .
62,746
def to_postfix ( tokens ) : precedence = { '/' : 4 , '*' : 4 , '+' : 3 , '-' : 3 , '^' : 2 , '(' : 1 } postfix = [ ] opstack = [ ] for token in tokens : if is_int ( token ) : postfix . append ( int ( token ) ) elif is_float ( token ) : postfix . append ( float ( token ) ) elif token in mathwords . CONSTANTS : postfix . append ( mathwords . CONSTANTS [ token ] ) elif is_unary ( token ) : opstack . append ( token ) elif token == '(' : opstack . append ( token ) elif token == ')' : top_token = opstack . pop ( ) while top_token != '(' : postfix . append ( top_token ) top_token = opstack . pop ( ) else : while ( opstack != [ ] ) and ( precedence [ opstack [ - 1 ] ] >= precedence [ token ] ) : postfix . append ( opstack . pop ( ) ) opstack . append ( token ) while opstack != [ ] : postfix . append ( opstack . pop ( ) ) return postfix
Convert a list of evaluatable tokens to postfix format .
62,747
def evaluate_postfix ( tokens ) : stack = [ ] for token in tokens : total = None if is_int ( token ) or is_float ( token ) or is_constant ( token ) : stack . append ( token ) elif is_unary ( token ) : a = stack . pop ( ) total = mathwords . UNARY_FUNCTIONS [ token ] ( a ) elif len ( stack ) : b = stack . pop ( ) a = stack . pop ( ) if token == '+' : total = a + b elif token == '-' : total = a - b elif token == '*' : total = a * b elif token == '^' : total = a ** b elif token == '/' : if Decimal ( str ( b ) ) == 0 : total = 'undefined' else : total = Decimal ( str ( a ) ) / Decimal ( str ( b ) ) else : raise PostfixTokenEvaluationException ( 'Unknown token {}' . format ( token ) ) if total is not None : stack . append ( total ) if not stack : raise PostfixTokenEvaluationException ( 'The postfix expression resulted in an empty stack' ) return stack . pop ( )
Given a list of evaluatable tokens in postfix format calculate a solution .
62,748
def tokenize ( string , language = None , escape = ' ' ) : string = string . lower ( ) if len ( string ) and not string [ - 1 ] . isalnum ( ) : character = string [ - 1 ] string = string [ : - 1 ] + ' ' + character string = string . replace ( '(' , ' ( ' ) string = string . replace ( ')' , ' ) ' ) if language : words = mathwords . words_for_language ( language ) for phrase in words : escaped_phrase = phrase . replace ( ' ' , escape ) string = string . replace ( phrase , escaped_phrase ) tokens = string . split ( ) for index , token in enumerate ( tokens ) : tokens [ index ] = token . replace ( escape , ' ' ) return tokens
Given a string return a list of math symbol tokens
62,749
def parse ( string , language = None ) : if language : string = replace_word_tokens ( string , language ) tokens = tokenize ( string ) postfix = to_postfix ( tokens ) return evaluate_postfix ( postfix )
Return a solution to the equation in the input string .
62,750
def expr_order_key ( expr ) : if hasattr ( expr , '_order_key' ) : return expr . _order_key try : if isinstance ( expr . kwargs , OrderedDict ) : key_vals = expr . kwargs . values ( ) else : key_vals = [ expr . kwargs [ key ] for key in sorted ( expr . kwargs ) ] return KeyTuple ( ( expr . __class__ . __name__ , ) + tuple ( map ( expr_order_key , expr . args ) ) + tuple ( map ( expr_order_key , key_vals ) ) ) except AttributeError : return str ( expr )
A default order key for arbitrary expressions
62,751
def Sum ( idx , * args , ** kwargs ) : from qnet . algebra . core . hilbert_space_algebra import LocalSpace from qnet . algebra . core . scalar_algebra import ScalarValue from qnet . algebra . library . spin_algebra import SpinSpace dispatch_table = { tuple ( ) : _sum_over_fockspace , ( LocalSpace , ) : _sum_over_fockspace , ( SpinSpace , ) : _sum_over_fockspace , ( list , ) : _sum_over_list , ( tuple , ) : _sum_over_list , ( int , ) : _sum_over_range , ( int , int ) : _sum_over_range , ( int , int , int ) : _sum_over_range , } key = tuple ( ( type ( arg ) for arg in args ) ) try : idx_range_func = dispatch_table [ key ] except KeyError : raise TypeError ( "No implementation for args of type %s" % str ( key ) ) def sum ( term ) : if isinstance ( term , ScalarValue . _val_types ) : term = ScalarValue . create ( term ) idx_range = idx_range_func ( term , idx , * args , ** kwargs ) return term . _indexed_sum_cls . create ( term , idx_range ) return sum
Instantiator for an arbitrary indexed sum .
62,752
def diff ( self , sym : Symbol , n : int = 1 , expand_simplify : bool = True ) : if not isinstance ( sym , sympy . Basic ) : raise TypeError ( "%s needs to be a Sympy symbol" % sym ) if sym . free_symbols . issubset ( self . free_symbols ) : deriv = QuantumDerivative . create ( self , derivs = { sym : n } , vals = None ) if not deriv . is_zero and expand_simplify : deriv = deriv . expand ( ) . simplify_scalar ( ) return deriv else : return self . __class__ . _zero
Differentiate by scalar parameter sym .
62,753
def series_expand ( self , param : Symbol , about , order : int ) -> tuple : r expansion = self . _series_expand ( param , about , order ) res = [ ] for v in expansion : if v == 0 or v . is_zero : v = self . _zero elif v == 1 : v = self . _one assert isinstance ( v , self . _base_cls ) res . append ( v ) return tuple ( res )
r Expand the expression as a truncated power series in a scalar parameter .
62,754
def factor_for_space ( self , spc ) : if spc == TrivialSpace : ops_on_spc = [ o for o in self . operands if o . space is TrivialSpace ] ops_not_on_spc = [ o for o in self . operands if o . space > TrivialSpace ] else : ops_on_spc = [ o for o in self . operands if ( o . space & spc ) > TrivialSpace ] ops_not_on_spc = [ o for o in self . operands if ( o . space & spc ) is TrivialSpace ] return ( self . __class__ . _times_cls . create ( * ops_on_spc ) , self . __class__ . _times_cls . create ( * ops_not_on_spc ) )
Return a tuple of two products where the first product contains the given Hilbert space and the second product is disjunct from it .
62,755
def evaluate_at ( self , vals ) : new_vals = self . _vals . copy ( ) new_vals . update ( vals ) return self . __class__ ( self . operand , derivs = self . _derivs , vals = new_vals )
Evaluate the derivative at a specific point
62,756
def bound_symbols ( self ) : if self . _bound_symbols is None : res = set ( ) self . _bound_symbols = res . union ( * [ sym . free_symbols for sym in self . _vals . keys ( ) ] ) return self . _bound_symbols
Set of Sympy symbols that are eliminated by evaluation .
62,757
def render_dot ( self , code , options , format , prefix = 'graphviz' ) : graphviz_dot = options . get ( 'graphviz_dot' , self . builder . config . graphviz_dot ) hashkey = ( code + str ( options ) + str ( graphviz_dot ) + str ( self . builder . config . graphviz_dot_args ) ) . encode ( 'utf-8' ) fname = '%s-%s.%s' % ( prefix , sha1 ( hashkey ) . hexdigest ( ) , format ) relfn = posixpath . join ( self . builder . imgpath , fname ) outfn = path . join ( self . builder . outdir , self . builder . imagedir , fname ) if path . isfile ( outfn ) : return relfn , outfn if ( hasattr ( self . builder , '_graphviz_warned_dot' ) and self . builder . _graphviz_warned_dot . get ( graphviz_dot ) ) : return None , None ensuredir ( path . dirname ( outfn ) ) if isinstance ( code , text_type ) : code = code . encode ( 'utf-8' ) dot_args = [ graphviz_dot ] dot_args . extend ( self . builder . config . graphviz_dot_args ) dot_args . extend ( [ '-T' + format , '-o' + outfn ] ) if format == 'png' : dot_args . extend ( [ '-Tcmapx' , '-o%s.map' % outfn ] ) try : p = Popen ( dot_args , stdout = PIPE , stdin = PIPE , stderr = PIPE ) except OSError as err : if err . errno != ENOENT : raise logger . warning ( __ ( 'dot command %r cannot be run (needed for graphviz ' 'output), check the graphviz_dot setting' ) , graphviz_dot ) if not hasattr ( self . builder , '_graphviz_warned_dot' ) : self . builder . _graphviz_warned_dot = { } self . builder . _graphviz_warned_dot [ graphviz_dot ] = True return None , None try : stdout , stderr = p . communicate ( code ) except ( OSError , IOError ) as err : if err . errno not in ( EPIPE , EINVAL ) : raise stdout , stderr = p . stdout . read ( ) , p . stderr . read ( ) p . wait ( ) if p . returncode != 0 : raise GraphvizError ( __ ( 'dot exited with error:\n[stderr]\n%s\n' '[stdout]\n%s' ) % ( stderr , stdout ) ) if not path . isfile ( outfn ) : raise GraphvizError ( __ ( 'dot did not produce an output file:\n[stderr]\n%s\n' '[stdout]\n%s' ) % ( stderr , stdout ) ) return relfn , outfn
Render graphviz code into a PNG or PDF output file .
62,758
def generate_clickable_map ( self ) : if self . clickable : return '\n' . join ( [ self . content [ 0 ] ] + self . clickable + [ self . content [ - 1 ] ] ) else : return ''
Generate clickable map tags if clickable item exists .
62,759
def next_basis_label_or_index ( self , label_or_index , n = 1 ) : if isinstance ( label_or_index , int ) : new_index = label_or_index + n if new_index < 0 : raise IndexError ( "index %d < 0" % new_index ) if new_index >= self . dimension : raise IndexError ( "index %d out of range for basis %s" % ( new_index , self . _basis ) ) return self . basis_labels [ new_index ] elif isinstance ( label_or_index , str ) : label_index = self . basis_labels . index ( label_or_index ) new_index = label_index + n if ( new_index < 0 ) or ( new_index >= len ( self . _basis ) ) : raise IndexError ( "index %d out of range for basis %s" % ( new_index , self . _basis ) ) return self . basis_labels [ new_index ] elif isinstance ( label_or_index , SpinIndex ) : return label_or_index . __class__ ( expr = label_or_index . expr + n )
Given the label or index of a basis state return the label the next basis state .
62,760
def texinfo_visit_inheritance_diagram ( self , node ) : graph = node [ 'graph' ] graph_hash = get_graph_hash ( node ) name = 'inheritance%s' % graph_hash dotcode = graph . generate_dot ( name , env = self . builder . env , graph_attrs = { 'size' : '"6.0,6.0"' } ) render_dot_texinfo ( self , node , dotcode , { } , 'inheritance' ) raise nodes . SkipNode
Output the graph for Texinfo . This will insert a PNG .
62,761
def class_name ( self , cls , parts = 0 , aliases = None ) : module = cls . __module__ if module in ( '__builtin__' , 'builtins' ) : fullname = cls . __name__ else : fullname = '%s.%s' % ( module , cls . __name__ ) if parts == 0 : result = fullname else : name_parts = fullname . split ( '.' ) result = '.' . join ( name_parts [ - parts : ] ) if aliases is not None and result in aliases : return aliases [ result ] return result
Given a class object return a fully - qualified name .
62,762
def codemirror_settings_update ( configs , parameters , on = None , names = None ) : output = copy . deepcopy ( configs ) if names : output = { k : output [ k ] for k in names } if not on : on = output . keys ( ) for k in on : output [ k ] . update ( parameters ) return output
Return a new dictionnary of configs updated with given parameters .
62,763
def lhs ( self ) : lhs = self . _lhs i = 0 while lhs is None : i -= 1 lhs = self . _prev_lhs [ i ] return lhs
The left - hand - side of the equation
62,764
def set_tag ( self , tag ) : return Eq ( self . _lhs , self . _rhs , tag = tag , _prev_lhs = self . _prev_lhs , _prev_rhs = self . _prev_rhs , _prev_tags = self . _prev_tags )
Return a copy of the equation with a new tag
62,765
def apply ( self , func , * args , cont = False , tag = None , ** kwargs ) : new_lhs = func ( self . lhs , * args , ** kwargs ) if new_lhs == self . lhs and cont : new_lhs = None new_rhs = func ( self . rhs , * args , ** kwargs ) new_tag = tag return self . _update ( new_lhs , new_rhs , new_tag , cont )
Apply func to both sides of the equation
62,766
def apply_mtd ( self , mtd , * args , cont = False , tag = None , ** kwargs ) : new_lhs = getattr ( self . lhs , mtd ) ( * args , ** kwargs ) if new_lhs == self . lhs and cont : new_lhs = None new_rhs = getattr ( self . rhs , mtd ) ( * args , ** kwargs ) new_tag = tag return self . _update ( new_lhs , new_rhs , new_tag , cont )
Call the method mtd on both sides of the equation
62,767
def substitute ( self , var_map , cont = False , tag = None ) : return self . apply ( substitute , var_map = var_map , cont = cont , tag = tag )
Substitute sub - expressions both on the lhs and rhs
62,768
def verify ( self , func = None , * args , ** kwargs ) : res = ( self . lhs . expand ( ) . simplify_scalar ( ) - self . rhs . expand ( ) . simplify_scalar ( ) ) if func is not None : return func ( res , * args , ** kwargs ) else : return res
Subtract the rhs from the lhs of the equation
62,769
def copy ( self ) : return Eq ( self . _lhs , self . _rhs , tag = self . _tag , _prev_lhs = self . _prev_lhs , _prev_rhs = self . _prev_rhs , _prev_tags = self . _prev_tags )
Return a copy of the equation
62,770
def free_symbols ( self ) : try : lhs_syms = self . lhs . free_symbols except AttributeError : lhs_syms = set ( ) try : rhs_syms = self . rhs . free_symbols except AttributeError : rhs_syms = set ( ) return lhs_syms | rhs_syms
Set of free SymPy symbols contained within the equation .
62,771
def bound_symbols ( self ) : try : lhs_syms = self . lhs . bound_symbols except AttributeError : lhs_syms = set ( ) try : rhs_syms = self . rhs . bound_symbols except AttributeError : rhs_syms = set ( ) return lhs_syms | rhs_syms
Set of bound SymPy symbols contained within the equation .
62,772
def SympyCreate ( n ) : a = sympy . zeros ( n ) for i in range ( 1 , n ) : a += sympy . sqrt ( i ) * basis_state ( i , n ) * basis_state ( i - 1 , n ) . H return a
Creation operator for a Hilbert space of dimension n as an instance of sympy . Matrix
62,773
def formfield_for_dbfield ( self , db_field , ** kwargs ) : overrides = self . formfield_overrides . get ( db_field . name ) if overrides : kwargs . update ( overrides ) field = super ( AbstractEntryBaseAdmin , self ) . formfield_for_dbfield ( db_field , ** kwargs ) if db_field . name == 'author' : field . user = kwargs [ 'request' ] . user return field
Allow formfield_overrides to contain field names too .
62,774
def _split_op ( self , identifier , hs_label = None , dagger = False , args = None ) : if self . _isinstance ( identifier , 'SymbolicLabelBase' ) : identifier = QnetAsciiDefaultPrinter ( ) . _print_SCALAR_TYPES ( identifier . expr ) name , total_subscript = self . _split_identifier ( identifier ) total_superscript = '' if ( hs_label not in [ None , '' ] ) : if self . _settings [ 'show_hs_label' ] == 'subscript' : if len ( total_subscript ) == 0 : total_subscript = '(' + hs_label + ')' else : total_subscript += ',(' + hs_label + ')' else : total_superscript += '(' + hs_label + ')' if dagger : total_superscript += self . _dagger_sym args_str = '' if ( args is not None ) and ( len ( args ) > 0 ) : args_str = ( self . _parenth_left + "," . join ( [ self . doprint ( arg ) for arg in args ] ) + self . _parenth_right ) return name , total_subscript , total_superscript , args_str
Return name total subscript total superscript and arguments str . All of the returned strings are fully rendered .
62,775
def _render_hs_label ( self , hs ) : if isinstance ( hs . __class__ , Singleton ) : return self . _render_str ( hs . label ) else : return self . _tensor_sym . join ( [ self . _render_str ( ls . label ) for ls in hs . local_factors ] )
Return the label of the given Hilbert space as a string
62,776
def parenthesize ( self , expr , level , * args , strict = False , ** kwargs ) : needs_parenths = ( ( precedence ( expr ) < level ) or ( strict and precedence ( expr ) == level ) ) if needs_parenths : return ( self . _parenth_left + self . doprint ( expr , * args , ** kwargs ) + self . _parenth_right ) else : return self . doprint ( expr , * args , ** kwargs )
Render expr and wrap the result in parentheses if the precedence of expr is below the given level ( or at the given level if strict is True . Extra args and kwargs are passed to the internal doit renderer
62,777
def draw_circuit ( circuit , filename , direction = 'lr' , hunit = HUNIT , vunit = VUNIT , rhmargin = RHMARGIN , rvmargin = RVMARGIN , rpermutation_length = RPLENGTH , draw_boxes = True , permutation_arrows = False ) : if direction == 'lr' : hunit = abs ( hunit ) elif direction == 'rl' : hunit = - abs ( hunit ) try : c , dims , c_in , c_out = draw_circuit_canvas ( circuit , hunit = hunit , vunit = vunit , rhmargin = rhmargin , rvmargin = rvmargin , rpermutation_length = rpermutation_length , draw_boxes = draw_boxes , permutation_arrows = permutation_arrows ) except ValueError as e : print ( ( "No graphics returned for circuit {!r}" . format ( circuit ) ) ) return False ps_suffixes = [ '.pdf' , '.eps' , '.ps' ] gs_suffixes = [ '.png' , '.jpg' ] if any ( filename . endswith ( suffix ) for suffix in ps_suffixes ) : c . writetofile ( filename ) elif any ( filename . endswith ( suffix ) for suffix in gs_suffixes ) : if GS is None : raise FileNotFoundError ( "No Ghostscript executable available. Ghostscript is required for " "rendering to {}." . format ( ", " . join ( gs_suffixes ) ) ) c . writeGSfile ( filename , gs = GS ) return True
Generate a graphic representation of circuit and store them in a file . The graphics format is determined from the file extension .
62,778
def nested_tuple ( container ) : if isinstance ( container , OrderedDict ) : return tuple ( map ( nested_tuple , container . items ( ) ) ) if isinstance ( container , Mapping ) : return tuple ( sorted_if_possible ( map ( nested_tuple , container . items ( ) ) ) ) if not isinstance ( container , ( str , bytes ) ) : if isinstance ( container , Sequence ) : return tuple ( map ( nested_tuple , container ) ) if ( isinstance ( container , Container ) and isinstance ( container , Iterable ) and isinstance ( container , Sized ) ) : return tuple ( sorted_if_possible ( map ( nested_tuple , container ) ) ) return container
Recursively transform a container structure to a nested tuple .
62,779
def precedence ( item ) : try : mro = item . __class__ . __mro__ except AttributeError : return PRECEDENCE [ "Atom" ] for i in mro : n = i . __name__ if n in PRECEDENCE_FUNCTIONS : return PRECEDENCE_FUNCTIONS [ n ] ( item ) elif n in PRECEDENCE_VALUES : return PRECEDENCE_VALUES [ n ] return PRECEDENCE [ "Atom" ]
Returns the precedence of a given object .
62,780
def callback_prototype ( prototype ) : protosig = signature ( prototype ) positional , keyword = [ ] , [ ] for name , param in protosig . parameters . items ( ) : if param . kind in ( Parameter . VAR_POSITIONAL , Parameter . VAR_KEYWORD ) : raise TypeError ( "*args/**kwargs not supported in prototypes" ) if ( param . default is not Parameter . empty ) or ( param . kind == Parameter . KEYWORD_ONLY ) : keyword . append ( name ) else : positional . append ( name ) kwargs = dict . fromkeys ( keyword ) def adapt ( callback ) : sig = signature ( callback ) try : sig . bind ( * positional , ** kwargs ) return callback except TypeError : pass unmatched_pos = positional [ : ] unmatched_kw = kwargs . copy ( ) unrecognised = [ ] for name , param in sig . parameters . items ( ) : if param . kind == Parameter . POSITIONAL_ONLY : if len ( unmatched_pos ) > 0 : unmatched_pos . pop ( 0 ) else : unrecognised . append ( name ) elif param . kind == Parameter . POSITIONAL_OR_KEYWORD : if ( param . default is not Parameter . empty ) and ( name in unmatched_kw ) : unmatched_kw . pop ( name ) elif len ( unmatched_pos ) > 0 : unmatched_pos . pop ( 0 ) else : unrecognised . append ( name ) elif param . kind == Parameter . VAR_POSITIONAL : unmatched_pos = [ ] elif param . kind == Parameter . KEYWORD_ONLY : if name in unmatched_kw : unmatched_kw . pop ( name ) else : unrecognised . append ( name ) else : unmatched_kw = { } if unrecognised : raise TypeError ( "Function {!r} had unmatched arguments: {}" . format ( callback , unrecognised ) ) n_positional = len ( positional ) - len ( unmatched_pos ) @ wraps ( callback ) def adapted ( * args , ** kwargs ) : args = args [ : n_positional ] for name in unmatched_kw : kwargs . pop ( name ) return callback ( * args , ** kwargs ) return adapted prototype . adapt = adapt return prototype
Decorator to process a callback prototype . A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question . The original function will be returned with a prototype . adapt attribute which can be used to prepare third party callbacks .
62,781
def published ( self , for_user = None ) : if appsettings . FLUENT_BLOGS_FILTER_SITE_ID : qs = self . parent_site ( settings . SITE_ID ) else : qs = self if for_user is not None and for_user . is_staff : return qs return qs . filter ( status = self . model . PUBLISHED ) . filter ( Q ( publication_date__isnull = True ) | Q ( publication_date__lte = now ( ) ) ) . filter ( Q ( publication_end_date__isnull = True ) | Q ( publication_end_date__gte = now ( ) ) )
Return only published entries for the current site .
62,782
def authors ( self , * usernames ) : if len ( usernames ) == 1 : return self . filter ( ** { "author__{}" . format ( User . USERNAME_FIELD ) : usernames [ 0 ] } ) else : return self . filter ( ** { "author__{}__in" . format ( User . USERNAME_FIELD ) : usernames } )
Return the entries written by the given usernames When multiple tags are provided they operate as OR query .
62,783
def categories ( self , * category_slugs ) : categories_field = getattr ( self . model , 'categories' , None ) if categories_field is None : raise AttributeError ( "The {0} does not include CategoriesEntryMixin" . format ( self . model . __name__ ) ) if issubclass ( categories_field . rel . model , TranslatableModel ) : filters = { 'categories__translations__slug__in' : category_slugs , } languages = self . _get_active_rel_languages ( ) if languages : if len ( languages ) == 1 : filters [ 'categories__translations__language_code' ] = languages [ 0 ] else : filters [ 'categories__translations__language_code__in' ] = languages return self . filter ( ** filters ) . distinct ( ) else : return self . filter ( categories__slug = category_slugs )
Return the entries with the given category slugs . When multiple tags are provided they operate as OR query .
62,784
def tagged ( self , * tag_slugs ) : if getattr ( self . model , 'tags' , None ) is None : raise AttributeError ( "The {0} does not include TagsEntryMixin" . format ( self . model . __name__ ) ) if len ( tag_slugs ) == 1 : return self . filter ( tags__slug = tag_slugs [ 0 ] ) else : return self . filter ( tags__slug__in = tag_slugs ) . distinct ( )
Return the items which are tagged with a specific tag . When multiple tags are provided they operate as OR query .
62,785
def format ( self , ** kwargs ) : name = self . name . format ( ** kwargs ) subs = [ ] if self . sub is not None : subs = [ self . sub . format ( ** kwargs ) ] supers = [ ] if self . sup is not None : supers = [ self . sup . format ( ** kwargs ) ] return render_unicode_sub_super ( name , subs , supers , sub_first = True , translate_symbols = True , unicode_sub_super = self . unicode_sub_super )
Format and combine the name subscript and superscript
62,786
def _render_str ( self , string ) : if isinstance ( string , StrLabel ) : string = string . _render ( string . expr ) string = str ( string ) if len ( string ) == 0 : return '' name , supers , subs = split_super_sub ( string ) return render_unicode_sub_super ( name , subs , supers , sub_first = True , translate_symbols = True , unicode_sub_super = self . _settings [ 'unicode_sub_super' ] )
Returned a unicodified version of the string
62,787
def PauliX ( local_space , states = None ) : r local_space , states = _get_pauli_args ( local_space , states ) g , e = states return ( LocalSigma . create ( g , e , hs = local_space ) + LocalSigma . create ( e , g , hs = local_space ) )
r Pauli - type X - operator
62,788
def PauliY ( local_space , states = None ) : r local_space , states = _get_pauli_args ( local_space , states ) g , e = states return I * ( - LocalSigma . create ( g , e , hs = local_space ) + LocalSigma . create ( e , g , hs = local_space ) )
r Pauli - type Y - operator
62,789
def PauliZ ( local_space , states = None ) : r local_space , states = _get_pauli_args ( local_space , states ) g , e = states return ( LocalProjector ( g , hs = local_space ) - LocalProjector ( e , hs = local_space ) )
r Pauli - type Z - operator
62,790
def render_head_repr ( expr : Any , sub_render = None , key_sub_render = None ) -> str : head_repr_fmt = r'{head}({args}{kwargs})' if sub_render is None : sub_render = render_head_repr if key_sub_render is None : key_sub_render = sub_render if isinstance ( expr . __class__ , Singleton ) : return repr ( expr ) if isinstance ( expr , Expression ) : args = expr . args keys = expr . minimal_kwargs . keys ( ) kwargs = '' if len ( keys ) > 0 : kwargs = ", " . join ( [ "%s=%s" % ( key , key_sub_render ( expr . kwargs [ key ] ) ) for key in keys ] ) if len ( args ) > 0 : kwargs = ", " + kwargs return head_repr_fmt . format ( head = expr . __class__ . __name__ , args = ", " . join ( [ sub_render ( arg ) for arg in args ] ) , kwargs = kwargs ) elif isinstance ( expr , ( tuple , list ) ) : delims = ( "(" , ")" ) if isinstance ( expr , tuple ) else ( "[" , "]" ) if len ( expr ) == 1 : delims = ( delims [ 0 ] , "," + delims [ 1 ] ) return ( delims [ 0 ] + ", " . join ( [ render_head_repr ( v , sub_render = sub_render , key_sub_render = key_sub_render ) for v in expr ] ) + delims [ 1 ] ) else : return sympy_srepr ( expr )
Render a textual representation of expr using Positional and keyword arguments are recursively rendered using sub_render which defaults to render_head_repr by default . If desired a different renderer may be used for keyword arguments by giving key_sub_renderer
62,791
def check_rules_dict ( rules ) : from qnet . algebra . pattern_matching import Pattern , ProtoExpr if hasattr ( rules , 'items' ) : items = rules . items ( ) else : items = rules keys = set ( ) for key_rule in items : try : key , rule = key_rule except ValueError : raise TypeError ( "rules does not contain (key, rule) tuples" ) if not isinstance ( key , str ) : raise TypeError ( "Key '%s' is not a string" % key ) if key in keys : raise ValueError ( "Duplicate key '%s'" % key ) else : keys . add ( key ) try : pat , replacement = rule except TypeError : raise TypeError ( "Rule in '%s' is not a (pattern, replacement) tuple" % key ) if not isinstance ( pat , Pattern ) : raise TypeError ( "Pattern in '%s' is not a Pattern instance" % key ) if pat . head is not ProtoExpr : raise ValueError ( "Pattern in '%s' does not match a ProtoExpr" % key ) if not callable ( replacement ) : raise ValueError ( "replacement in '%s' is not callable" % key ) else : arg_names = inspect . signature ( replacement ) . parameters . keys ( ) if not arg_names == pat . wc_names : raise ValueError ( "arguments (%s) of replacement function differ from the " "wildcard names (%s) in pattern" % ( ", " . join ( sorted ( arg_names ) ) , ", " . join ( sorted ( pat . wc_names ) ) ) ) return OrderedDict ( rules )
Verify the rules that classes may use for the _rules or _binary_rules class attribute .
62,792
def derationalize_denom ( expr ) : r_pos = - 1 p_pos = - 1 numerator = S . Zero denom_sq = S . One post_factors = [ ] if isinstance ( expr , Mul ) : for pos , factor in enumerate ( expr . args ) : if isinstance ( factor , Rational ) and r_pos < 0 : r_pos = pos numerator , denom_sq = factor . p , factor . q elif isinstance ( factor , Pow ) and r_pos >= 0 : if factor == sqrt ( denom_sq ) : p_pos = pos else : post_factors . append ( factor ) else : post_factors . append ( factor ) if r_pos >= 0 and p_pos >= 0 : return numerator , denom_sq , Mul ( * post_factors ) else : raise ValueError ( "Cannot derationalize" ) else : raise ValueError ( "expr is not a Mul instance" )
Try to de - rationalize the denominator of the given expression .
62,793
def entries ( self ) : EntryModel = get_entry_model ( ) qs = get_entry_model ( ) . objects . order_by ( '-publication_date' ) if issubclass ( EntryModel , TranslatableModel ) : admin_form_language = self . get_current_language ( ) qs = qs . active_translations ( admin_form_language ) . language ( admin_form_language ) return qs
Return the entries that are published under this node .
62,794
def get_entry_url ( self , entry ) : with switch_language ( self , entry . get_current_language ( ) ) : return self . get_absolute_url ( ) + entry . get_relative_url ( )
Return the URL of a blog entry relative to this page .
62,795
def create_placeholder ( self , slot = "blog_contents" , role = 'm' , title = None ) : return Placeholder . objects . create_for_object ( self , slot , role = role , title = title )
Create a placeholder on this blog entry .
62,796
def save_as_png ( self , filename , width = 300 , height = 250 , render_time = 1 ) : self . driver . set_window_size ( width , height ) self . driver . get ( 'file://{path}/{filename}' . format ( path = os . getcwd ( ) , filename = filename + ".html" ) ) time . sleep ( render_time ) self . driver . save_screenshot ( filename + ".png" )
Open saved html file in an virtual browser and save a screen shot to PNG format .
62,797
def get_version ( filename ) : with open ( filename ) as in_fh : for line in in_fh : if line . startswith ( '__version__' ) : return line . split ( '=' ) [ 1 ] . strip ( ) [ 1 : - 1 ] raise ValueError ( "Cannot extract version from %s" % filename )
Extract the package version
62,798
def format_year ( year ) : if isinstance ( year , ( date , datetime ) ) : return unicode ( year . year ) else : return unicode ( year )
Format the year value of the YearArchiveView which can be a integer or date object .
62,799
def free_symbols ( self ) : return set ( [ sym for sym in self . term . free_symbols if sym not in self . bound_symbols ] )
Set of all free symbols