idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
25,400 | def run ( self , shots = 1 , targetT = 0.02 , verbose = False ) : if self . qubo != [ ] : self . qi ( ) J = self . reJ ( ) N = len ( J ) itetemp = 100 Rtemp = 0.75 self . E = [ ] qq = [ ] for i in range ( shots ) : T = self . Ts q = np . random . choice ( [ - 1 , 1 ] , N ) EE = [ ] EE . append ( Ei ( q , self . J ) + self . ep ) while T > targetT : x_list = np . random . randint ( 0 , N , itetemp ) for x in x_list : q2 = np . ones ( N ) * q [ x ] q2 [ x ] = 1 dE = - 2 * sum ( q * q2 * J [ : , x ] ) if dE < 0 or np . exp ( - dE / T ) > np . random . random_sample ( ) : q [ x ] *= - 1 EE . append ( Ei ( q , self . J ) + self . ep ) T *= Rtemp self . E . append ( EE ) qtemp = ( np . asarray ( q , int ) + 1 ) / 2 qq . append ( [ int ( s ) for s in qtemp ] ) if verbose == True : print ( i , ':' , [ int ( s ) for s in qtemp ] ) if shots == 1 : qq = qq [ 0 ] if shots == 1 : self . E = self . E [ 0 ] return qq | Run SA with provided QUBO . Set qubo attribute in advance of calling this method . |
25,401 | def _str_targets ( self ) : def _slice_to_str ( obj ) : if isinstance ( obj , slice ) : start = "" if obj . start is None else str ( obj . start . __index__ ( ) ) stop = "" if obj . stop is None else str ( obj . stop . __index__ ( ) ) if obj . step is None : return f"{start}:{stop}" else : step = str ( obj . step . __index__ ( ) ) return f"{start}:{stop}:{step}" else : return obj . __index__ ( ) if isinstance ( self . targets , tuple ) : return f"[{', '.join(_slice_to_str(idx for idx in self.targets))}]" else : return f"[{_slice_to_str(self.targets)}]" | Returns printable string of targets . |
25,402 | def get_scipy_minimizer ( ** kwargs ) : def minimizer ( objective , n_params ) : params = [ random . random ( ) for _ in range ( n_params ) ] result = scipy_minimizer ( objective , params , ** kwargs ) return result . x return minimizer | Get minimizer which uses scipy . optimize . minimize |
25,403 | def expect ( qubits , meas ) : "For the VQE simulation without sampling." result = { } i = np . arange ( len ( qubits ) ) meas = tuple ( meas ) def to_mask ( n ) : return reduce ( lambda acc , im : acc | ( n & ( 1 << im [ 0 ] ) ) << ( im [ 1 ] - im [ 0 ] ) , enumerate ( meas ) , 0 ) def to_key ( k ) : return tuple ( 1 if k & ( 1 << i ) else 0 for i in meas ) mask = reduce ( lambda acc , v : acc | ( 1 << v ) , meas , 0 ) cnt = defaultdict ( float ) for i , v in enumerate ( qubits ) : p = v . real ** 2 + v . imag ** 2 if p != 0.0 : cnt [ i & mask ] += p return { to_key ( k ) : v for k , v in cnt . items ( ) } | For the VQE simulation without sampling . |
25,404 | def non_sampling_sampler ( circuit , meas ) : meas = tuple ( meas ) n_qubits = circuit . n_qubits return expect ( circuit . run ( returns = "statevector" ) , meas ) | Calculate the expectations without sampling . |
25,405 | def get_measurement_sampler ( n_sample , run_options = None ) : if run_options is None : run_options = { } def sampling_by_measurement ( circuit , meas ) : def reduce_bits ( bits , meas ) : bits = [ int ( x ) for x in bits [ : : - 1 ] ] return tuple ( bits [ m ] for m in meas ) meas = tuple ( meas ) circuit . measure [ meas ] counter = circuit . run ( shots = n_sample , returns = "shots" , ** run_options ) counts = Counter ( { reduce_bits ( bits , meas ) : val for bits , val in counter . items ( ) } ) return { k : v / n_sample for k , v in counts . items ( ) } return sampling_by_measurement | Returns a function which get the expectations by sampling the measured circuit |
25,406 | def get_state_vector_sampler ( n_sample ) : def sampling_by_measurement ( circuit , meas ) : val = 0.0 e = expect ( circuit . run ( returns = "statevector" ) , meas ) bits , probs = zip ( * e . items ( ) ) dists = np . random . multinomial ( n_sample , probs ) / n_sample return dict ( zip ( tuple ( bits ) , dists ) ) return sampling_by_measurement | Returns a function which get the expectations by sampling the state vector |
25,407 | def get_qiskit_sampler ( backend , ** execute_kwargs ) : try : import qiskit except ImportError : raise ImportError ( "blueqat.vqe.get_qiskit_sampler() requires qiskit. Please install before call this function." ) try : shots = execute_kwargs [ 'shots' ] except KeyError : execute_kwargs [ 'shots' ] = shots = 1024 def reduce_bits ( bits , meas ) : if bits . startswith ( "0x" ) : bits = int ( bits , base = 16 ) bits = "0" * 100 + format ( bits , "b" ) bits = [ int ( x ) for x in bits [ : : - 1 ] ] return tuple ( bits [ m ] for m in meas ) def sampling ( circuit , meas ) : meas = tuple ( meas ) if not meas : return { } circuit . measure [ meas ] qasm = circuit . to_qasm ( ) qk_circuit = qiskit . load_qasm_string ( qasm ) result = qiskit . execute ( qk_circuit , backend , ** execute_kwargs ) . result ( ) counts = Counter ( { reduce_bits ( bits , meas ) : val for bits , val in result . get_counts ( ) . items ( ) } ) return { k : v / shots for k , v in counts . items ( ) } return sampling | Returns a function which get the expectation by sampling via Qiskit . |
25,408 | def get_energy ( self , circuit , sampler ) : val = 0.0 for meas in self . hamiltonian : c = circuit . copy ( ) for op in meas . ops : if op . op == "X" : c . h [ op . n ] elif op . op == "Y" : c . rx ( - np . pi / 2 ) [ op . n ] measured = sampler ( c , meas . n_iter ( ) ) for bits , prob in measured . items ( ) : if sum ( bits ) % 2 : val -= prob * meas . coeff else : val += prob * meas . coeff return val . real | Calculate energy from circuit and sampler . |
25,409 | def get_objective ( self , sampler ) : def objective ( params ) : circuit = self . get_circuit ( params ) circuit . make_cache ( ) return self . get_energy ( circuit , sampler ) return objective | Get an objective function to be optimized . |
25,410 | def get_probs ( self , sampler = None , rerun = None , store = True ) : if rerun is None : rerun = sampler is not None if self . _probs is not None and not rerun : return self . _probs if sampler is None : sampler = self . vqe . sampler probs = sampler ( self . circuit , range ( self . circuit . n_qubits ) ) if store : self . _probs = probs return probs | Get probabilities . |
25,411 | def _run_gates ( self , gates , n_qubits , ctx ) : for gate in gates : action = self . _get_action ( gate ) if action is not None : ctx = action ( gate , ctx ) else : ctx = self . _run_gates ( gate . fallback ( n_qubits ) , n_qubits , ctx ) return ctx | Iterate gates and call backend s action for each gates |
25,412 | def _run ( self , gates , n_qubits , args , kwargs ) : gates , ctx = self . _preprocess_run ( gates , n_qubits , args , kwargs ) self . _run_gates ( gates , n_qubits , ctx ) return self . _postprocess_run ( ctx ) | Default implementation of Backend . run . Backend developer shouldn t override this function but override run instead of this . |
25,413 | def run ( self , gates , n_qubits , * args , ** kwargs ) : return self . _run ( gates , n_qubits , args , kwargs ) | Run the backend . |
25,414 | def _resolve_fallback ( self , gates , n_qubits ) : flattened = [ ] for g in gates : if self . _has_action ( g ) : flattened . append ( g ) else : flattened += self . _resolve_fallback ( g . fallback ( n_qubits ) , n_qubits ) return flattened | Resolve fallbacks and flatten gates . |
25,415 | def prepare ( self , cache ) : if cache is not None : np . copyto ( self . qubits , cache ) else : self . qubits . fill ( 0.0 ) self . qubits [ 0 ] = 1.0 self . cregs = [ 0 ] * self . n_qubits | Prepare to run next shot . |
25,416 | def store_shot ( self ) : def to_str ( cregs ) : return '' . join ( str ( b ) for b in cregs ) key = to_str ( self . cregs ) self . shots_result [ key ] = self . shots_result . get ( key , 0 ) + 1 | Store current cregs to shots_result |
25,417 | def copy ( self , copy_backends = True , copy_default_backend = True , copy_cache = None , copy_history = None ) : copied = Circuit ( self . n_qubits , self . ops . copy ( ) ) if copy_backends : copied . _backends = { k : v . copy ( ) for k , v in self . _backends . items ( ) } if copy_default_backend : copied . _default_backend = self . _default_backend if copy_cache is not None : warnings . warn ( "copy_cache is deprecated. Use copy_backends instead." , DeprecationWarning ) if copy_history is not None : warnings . warn ( "copy_history is deprecated." , DeprecationWarning ) return copied | Copy the circuit . |
25,418 | def run ( self , * args , backend = None , ** kwargs ) : if backend is None : if self . _default_backend is None : backend = self . __get_backend ( DEFAULT_BACKEND_NAME ) else : backend = self . __get_backend ( self . _default_backend ) elif isinstance ( backend , str ) : backend = self . __get_backend ( backend ) return backend . run ( self . ops , self . n_qubits , * args , ** kwargs ) | Run the circuit . |
25,419 | def make_cache ( self , backend = None ) : if backend is None : if self . _default_backend is None : backend = DEFAULT_BACKEND_NAME else : backend = self . _default_backend return self . __get_backend ( backend ) . make_cache ( self . ops , self . n_qubits ) | Make a cache to reduce the time of run . Some backends may implemented it . |
25,420 | def set_default_backend ( self , backend_name ) : if backend_name not in BACKENDS : raise ValueError ( f"Unknown backend '{backend_name}'." ) self . _default_backend = backend_name | Set the default backend of this circuit . |
25,421 | def register_macro ( name : str , func : Callable , allow_overwrite : bool = False ) -> None : if hasattr ( Circuit , name ) : if allow_overwrite : warnings . warn ( f"Circuit has attribute `{name}`." ) else : raise ValueError ( f"Circuit has attribute `{name}`." ) if name . startswith ( "run_with_" ) : if allow_overwrite : warnings . warn ( f"Gate name `{name}` may conflict with run of backend." ) else : raise ValueError ( f"Gate name `{name}` shall not start with 'run_with_'." ) if not allow_overwrite : if name in GATE_SET : raise ValueError ( f"Gate '{name}' is already exists in gate set." ) if name in GLOBAL_MACROS : raise ValueError ( f"Macro '{name}' is already exists." ) GLOBAL_MACROS [ name ] = func | Register new macro to Circuit . |
25,422 | def register_gate ( name , gateclass , allow_overwrite = False ) : if hasattr ( Circuit , name ) : if allow_overwrite : warnings . warn ( f"Circuit has attribute `{name}`." ) else : raise ValueError ( f"Circuit has attribute `{name}`." ) if name . startswith ( "run_with_" ) : if allow_overwrite : warnings . warn ( f"Gate name `{name}` may conflict with run of backend." ) else : raise ValueError ( f"Gate name `{name}` shall not start with 'run_with_'." ) if not allow_overwrite : if name in GATE_SET : raise ValueError ( f"Gate '{name}' is already exists in gate set." ) if name in GLOBAL_MACROS : raise ValueError ( f"Macro '{name}' is already exists." ) GATE_SET [ name ] = gateclass | Register new gate to gate set . |
25,423 | def register_backend ( name , backend , allow_overwrite = False ) : if hasattr ( Circuit , "run_with_" + name ) : if allow_overwrite : warnings . warn ( f"Circuit has attribute `run_with_{name}`." ) else : raise ValueError ( f"Circuit has attribute `run_with_{name}`." ) if not allow_overwrite : if name in BACKENDS : raise ValueError ( f"Backend '{name}' is already registered as backend." ) BACKENDS [ name ] = backend | Register new backend . |
25,424 | def maxcut_qaoa ( n_step , edges , minimizer = None , sampler = None , verbose = True ) : sampler = sampler or vqe . non_sampling_sampler minimizer = minimizer or vqe . get_scipy_minimizer ( method = "Powell" , options = { "ftol" : 5.0e-2 , "xtol" : 5.0e-2 , "maxiter" : 1000 , "disp" : True } ) hamiltonian = pauli . I ( ) * 0 for i , j in edges : hamiltonian += pauli . Z ( i ) * pauli . Z ( j ) return vqe . Vqe ( vqe . QaoaAnsatz ( hamiltonian , n_step ) , minimizer , sampler ) | Setup QAOA . |
25,425 | def pauli_from_char ( ch , n = 0 ) : ch = ch . upper ( ) if ch == "I" : return I if ch == "X" : return X ( n ) if ch == "Y" : return Y ( n ) if ch == "Z" : return Z ( n ) raise ValueError ( "ch shall be X, Y, Z or I" ) | Make Pauli matrix from an character . |
25,426 | def is_commutable ( expr1 , expr2 , eps = 0.00000001 ) : return sum ( ( x * x . conjugate ( ) ) . real for x in commutator ( expr1 , expr2 ) . coeffs ( ) ) < eps | Test whether expr1 and expr2 are commutable . |
25,427 | def from_pauli ( pauli , coeff = 1.0 ) : if pauli . is_identity or coeff == 0 : return Term ( ( ) , coeff ) return Term ( ( pauli , ) , coeff ) | Make new Term from an Pauli operator |
25,428 | def simplify ( self ) : def mul ( op1 , op2 ) : if op1 == "I" : return 1.0 , op2 if op2 == "I" : return 1.0 , op1 if op1 == op2 : return 1.0 , "I" if op1 == "X" : return ( - 1j , "Z" ) if op2 == "Y" else ( 1j , "Y" ) if op1 == "Y" : return ( - 1j , "X" ) if op2 == "Z" else ( 1j , "Z" ) if op1 == "Z" : return ( - 1j , "Y" ) if op2 == "X" else ( 1j , "X" ) before = defaultdict ( list ) for op in self . ops : if op . op == "I" : continue before [ op . n ] . append ( op . op ) new_coeff = self . coeff new_ops = [ ] for n in sorted ( before . keys ( ) ) : ops = before [ n ] assert ops k = 1.0 op = ops [ 0 ] for _op in ops [ 1 : ] : _k , op = mul ( op , _op ) k *= _k new_coeff *= k if new_coeff . imag == 0 : new_coeff = new_coeff . real if op != "I" : new_ops . append ( pauli_from_char ( op , n ) ) return Term ( tuple ( new_ops ) , new_coeff ) | Simplify the Term . |
25,429 | def append_to_circuit ( self , circuit , simplify = True ) : if simplify : term = self . simplify ( ) else : term = self for op in term . ops [ : : - 1 ] : gate = op . op . lower ( ) if gate != "i" : getattr ( circuit , gate ) [ op . n ] | Append Pauli gates to Circuit . |
25,430 | def get_time_evolution ( self ) : term = self . simplify ( ) coeff = term . coeff if coeff . imag : raise ValueError ( "Not a real coefficient." ) ops = term . ops def append_to_circuit ( circuit , t ) : if not ops : return for op in ops : n = op . n if op . op == "X" : circuit . h [ n ] elif op . op == "Y" : circuit . rx ( - half_pi ) [ n ] for i in range ( 1 , len ( ops ) ) : circuit . cx [ ops [ i - 1 ] . n , ops [ i ] . n ] circuit . rz ( - 2 * coeff * t ) [ ops [ - 1 ] . n ] for i in range ( len ( ops ) - 1 , 0 , - 1 ) : circuit . cx [ ops [ i - 1 ] . n , ops [ i ] . n ] for op in ops : n = op . n if op . op == "X" : circuit . h [ n ] elif op . op == "Y" : circuit . rx ( half_pi ) [ n ] return append_to_circuit | Get the function to append the time evolution of this term . |
25,431 | def is_identity ( self ) : if not self . terms : return True return len ( self . terms ) == 1 and not self . terms [ 0 ] . ops and self . terms [ 0 ] . coeff == 1.0 | If self is I returns True otherwise False . |
25,432 | def max_n ( self ) : return max ( term . max_n ( ) for term in self . terms if term . ops ) | Returns the maximum index of Pauli matrices in the Term . |
25,433 | def is_all_terms_commutable ( self ) : return all ( is_commutable ( a , b ) for a , b in combinations ( self . terms , 2 ) ) | Test whether all terms are commutable . This function may very slow . |
25,434 | def simplify ( self ) : d = defaultdict ( float ) for term in self . terms : term = term . simplify ( ) d [ term . ops ] += term . coeff return Expr . from_terms_iter ( Term . from_ops_iter ( k , d [ k ] ) for k in sorted ( d , key = repr ) if d [ k ] ) | Simplify the Expr . |
25,435 | def add_coord ( self , x , y ) : x = x * self . x_factor y = y * self . y_factor self . plotData . add_coord ( x , y ) self . circles_list . append ( gui . SvgCircle ( x , y , self . circle_radius ) ) self . append ( self . circles_list [ - 1 ] ) if len ( self . circles_list ) > self . maxlen : self . remove_child ( self . circles_list [ 0 ] ) del self . circles_list [ 0 ] | Adds a coord to the polyline and creates another circle |
25,436 | def My_TreeTable ( self , table , heads , heads2 = None ) : self . Define_TreeTable ( heads , heads2 ) self . Display_TreeTable ( table ) | Define and display a table in which the values in first column form one or more trees . |
25,437 | def Define_TreeTable ( self , heads , heads2 = None ) : display_heads = [ ] display_heads . append ( tuple ( heads [ 2 : ] ) ) self . tree_table = TreeTable ( ) self . tree_table . append_from_list ( display_heads , fill_title = True ) if heads2 is not None : heads2_color = heads2 [ 1 ] row_widget = gui . TableRow ( ) for index , field in enumerate ( heads2 [ 2 : ] ) : row_item = gui . TableItem ( text = field , style = { 'background-color' : heads2_color } ) row_widget . append ( row_item , field ) self . tree_table . append ( row_widget , heads2 [ 0 ] ) self . wid . append ( self . tree_table ) | Define a TreeTable with a heading row and optionally a second heading row . |
25,438 | def confirm_value ( self , widget , x , y ) : self . gauge . onmousedown ( self . gauge , x , y ) params = ( self . gauge . value ) return params | event called clicking on the gauge and so changing its value . propagates the new value |
25,439 | def configure_widget_for_editing ( self , widget ) : if not 'editor_varname' in widget . attributes : return widget . onclick . do ( self . on_widget_selection ) widget . __class__ . on_dropped = on_dropped widget . style [ 'overflow' ] = 'auto' widget . attributes [ 'draggable' ] = 'true' widget . attributes [ 'tabindex' ] = str ( self . tabindex ) self . tabindex += 1 | A widget have to be added to the editor it is configured here in order to be conformant to the editor |
25,440 | def on_right_click ( self , widget ) : if self . opened : return self . state = ( self . state + 1 ) % 3 self . set_icon ( ) self . game . check_if_win ( ) | Here with right click the change of cell is changed |
25,441 | def build_mine_matrix ( self , w , h , minenum ) : self . minecount = 0 matrix = [ [ Cell ( 30 , 30 , x , y , self ) for x in range ( w ) ] for y in range ( h ) ] for i in range ( 0 , minenum ) : x = random . randint ( 0 , w - 1 ) y = random . randint ( 0 , h - 1 ) if matrix [ y ] [ x ] . has_mine : continue self . minecount += 1 matrix [ y ] [ x ] . has_mine = True for coord in [ [ - 1 , - 1 ] , [ - 1 , 0 ] , [ - 1 , 1 ] , [ 0 , - 1 ] , [ 0 , 1 ] , [ 1 , - 1 ] , [ 1 , 0 ] , [ 1 , 1 ] ] : _x , _y = coord if not self . coord_in_map ( x + _x , y + _y , w , h ) : continue matrix [ y + _y ] [ x + _x ] . add_nearest_mine ( ) return matrix | random fill cells with mines and increments nearest mines num in adiacent cells |
25,442 | def check_if_win ( self ) : self . flagcount = 0 win = True for x in range ( 0 , len ( self . mine_matrix [ 0 ] ) ) : for y in range ( 0 , len ( self . mine_matrix ) ) : if self . mine_matrix [ y ] [ x ] . state == 1 : self . flagcount += 1 if not self . mine_matrix [ y ] [ x ] . has_mine : win = False elif self . mine_matrix [ y ] [ x ] . has_mine : win = False self . lblMineCount . set_text ( "%s" % self . minecount ) self . lblFlagCount . set_text ( "%s" % self . flagcount ) if win : self . dialog = gui . GenericDialog ( title = 'You Win!' , message = 'Game done in %s seconds' % self . time_count ) self . dialog . confirm_dialog . do ( self . new_game ) self . dialog . cancel_dialog . do ( self . new_game ) self . dialog . show ( self ) | Here are counted the flags . Is checked if the user win . |
25,443 | def renew_session ( self ) : if ( ( not 'user_uid' in self . cookieInterface . cookies ) or self . cookieInterface . cookies [ 'user_uid' ] != self . session_uid ) and ( not self . expired ) : self . on_session_expired ( ) if self . expired : self . session_uid = str ( random . randint ( 1 , 999999999 ) ) self . cookieInterface . set_cookie ( 'user_uid' , self . session_uid , str ( self . session_timeout_seconds ) ) if self . timeout_timer : self . timeout_timer . cancel ( ) self . timeout_timer = threading . Timer ( self . session_timeout_seconds , self . on_session_expired ) self . expired = False self . timeout_timer . start ( ) | Have to be called on user actions to check and renew session |
25,444 | def decorate_event_js ( js_code ) : def add_annotation ( method ) : setattr ( method , "__is_event" , True ) setattr ( method , "_js_code" , js_code ) return method return add_annotation | setup a method as an event adding also javascript code to generate |
25,445 | def decorate_set_on_listener ( prototype ) : def add_annotation ( method ) : method . _event_info = { } method . _event_info [ 'name' ] = method . __name__ method . _event_info [ 'prototype' ] = prototype return method return add_annotation | Private decorator for use in the editor . Allows the Editor to create listener methods . |
25,446 | def do ( self , callback , * userdata ) : if hasattr ( self . event_method_bound , '_js_code' ) : self . event_source_instance . attributes [ self . event_name ] = self . event_method_bound . _js_code % { 'emitter_identifier' : self . event_source_instance . identifier , 'event_name' : self . event_name } self . callback = callback self . userdata = userdata | The callback and userdata gets stored and if there is some javascript to add the js code is appended as attribute for the event source |
25,447 | def add_child ( self , key , value ) : if type ( value ) in ( list , tuple , dict ) : if type ( value ) == dict : for k in value . keys ( ) : self . add_child ( k , value [ k ] ) return i = 0 for child in value : self . add_child ( key [ i ] , child ) i = i + 1 return if hasattr ( value , 'attributes' ) : value . attributes [ 'data-parent-widget' ] = self . identifier value . _parent = self if key in self . children : self . _render_children_list . remove ( key ) self . _render_children_list . append ( key ) self . children [ key ] = value | Adds a child to the Tag |
25,448 | def empty ( self ) : for k in list ( self . children . keys ( ) ) : self . remove_child ( self . children [ k ] ) | remove all children from the widget |
25,449 | def remove_child ( self , child ) : if child in self . children . values ( ) and hasattr ( child , 'identifier' ) : for k in self . children . keys ( ) : if hasattr ( self . children [ k ] , 'identifier' ) : if self . children [ k ] . identifier == child . identifier : if k in self . _render_children_list : self . _render_children_list . remove ( k ) self . children . pop ( k ) break | Removes a child instance from the Tag s children . |
25,450 | def set_size ( self , width , height ) : if width is not None : try : width = to_pix ( int ( width ) ) except ValueError : pass self . style [ 'width' ] = width if height is not None : try : height = to_pix ( int ( height ) ) except ValueError : pass self . style [ 'height' ] = height | Set the widget size . |
25,451 | def repr ( self , changed_widgets = None ) : if changed_widgets is None : changed_widgets = { } return super ( Widget , self ) . repr ( changed_widgets ) | Represents the widget as HTML format packs all the attributes children and so on . |
25,452 | def set_icon_file ( self , filename , rel = "icon" ) : mimetype , encoding = mimetypes . guess_type ( filename ) self . add_child ( "favicon" , '<link rel="%s" href="%s" type="%s" />' % ( rel , filename , mimetype ) ) | Allows to define an icon for the App |
25,453 | def onerror ( self , message , source , lineno , colno ) : return ( message , source , lineno , colno ) | Called when an error occurs . |
25,454 | def set_column_sizes ( self , values ) : self . style [ 'grid-template-columns' ] = ' ' . join ( map ( lambda value : ( str ( value ) if str ( value ) . endswith ( '%' ) else str ( value ) + '%' ) , values ) ) | Sets the size value for each column |
25,455 | def set_column_gap ( self , value ) : value = str ( value ) + 'px' value = value . replace ( 'pxpx' , 'px' ) self . style [ 'grid-column-gap' ] = value | Sets the gap value between columns |
25,456 | def set_row_gap ( self , value ) : value = str ( value ) + 'px' value = value . replace ( 'pxpx' , 'px' ) self . style [ 'grid-row-gap' ] = value | Sets the gap value between rows |
25,457 | def select_by_widget ( self , widget ) : for a , li , holder in self . _tabs . values ( ) : if holder . children [ 'content' ] == widget : self . _on_tab_pressed ( a , li , holder ) return | shows a tab identified by the contained widget |
25,458 | def select_by_name ( self , name ) : for a , li , holder in self . _tabs . values ( ) : if a . children [ 'text' ] == name : self . _on_tab_pressed ( a , li , holder ) return | shows a tab identified by the name |
25,459 | def set_value ( self , text ) : if self . single_line : text = text . replace ( '\n' , '' ) self . set_text ( text ) | Sets the text content . |
25,460 | def onchange ( self , new_value ) : self . disable_refresh ( ) self . set_value ( new_value ) self . enable_refresh ( ) return ( new_value , ) | Called when the user changes the TextInput content . With single_line = True it fires in case of focus lost and Enter key pressed . With single_line = False it fires at each key released . |
25,461 | def add_field_with_label ( self , key , label_description , field ) : self . inputs [ key ] = field label = Label ( label_description ) label . style [ 'margin' ] = '0px 5px' label . style [ 'min-width' ] = '30%' container = HBox ( ) container . style . update ( { 'justify-content' : 'space-between' , 'overflow' : 'auto' , 'padding' : '3px' } ) container . append ( label , key = 'lbl' + key ) container . append ( self . inputs [ key ] , key = key ) self . container . append ( container , key = key ) | Adds a field to the dialog together with a descriptive label and a unique identifier . |
25,462 | def add_field ( self , key , field ) : self . inputs [ key ] = field container = HBox ( ) container . style . update ( { 'justify-content' : 'space-between' , 'overflow' : 'auto' , 'padding' : '3px' } ) container . append ( self . inputs [ key ] , key = key ) self . container . append ( container , key = key ) | Adds a field to the dialog with a unique identifier . |
25,463 | def on_keydown_listener ( self , widget , value , keycode ) : if keycode == "13" : self . hide ( ) self . inputText . set_text ( value ) self . confirm_value ( self ) | event called pressing on ENTER key . |
25,464 | def new_from_list ( cls , items , ** kwargs ) : obj = cls ( ** kwargs ) for item in items : obj . append ( ListItem ( item ) ) return obj | Populates the ListView with a string list . |
25,465 | def empty ( self ) : self . _selected_item = None self . _selected_key = None super ( ListView , self ) . empty ( ) | Removes all children from the list |
25,466 | def onselection ( self , widget ) : self . _selected_key = None for k in self . children : if self . children [ k ] == widget : self . _selected_key = k if ( self . _selected_item is not None ) and self . _selectable : self . _selected_item . attributes [ 'selected' ] = False self . _selected_item = self . children [ self . _selected_key ] if self . _selectable : self . _selected_item . attributes [ 'selected' ] = True break return ( self . _selected_key , ) | Called when a new item gets selected in the list . |
25,467 | def select_by_key ( self , key ) : self . _selected_key = None self . _selected_item = None for item in self . children . values ( ) : item . attributes [ 'selected' ] = False if key in self . children : self . children [ key ] . attributes [ 'selected' ] = True self . _selected_key = key self . _selected_item = self . children [ key ] | Selects an item by its key . |
25,468 | def select_by_value ( self , value ) : self . _selected_key = None self . _selected_item = None for k in self . children : item = self . children [ k ] item . attributes [ 'selected' ] = False if value == item . get_value ( ) : self . _selected_key = k self . _selected_item = item self . _selected_item . attributes [ 'selected' ] = True | Selects an item by the text content of the child . |
25,469 | def select_by_key ( self , key ) : for item in self . children . values ( ) : if 'selected' in item . attributes : del item . attributes [ 'selected' ] self . children [ key ] . attributes [ 'selected' ] = 'selected' self . _selected_key = key self . _selected_item = self . children [ key ] | Selects an item by its unique string identifier . |
25,470 | def select_by_value ( self , value ) : self . _selected_key = None self . _selected_item = None for k in self . children : item = self . children [ k ] if item . get_text ( ) == value : item . attributes [ 'selected' ] = 'selected' self . _selected_key = k self . _selected_item = item else : if 'selected' in item . attributes : del item . attributes [ 'selected' ] | Selects a DropDownItem by means of the contained text - |
25,471 | def onchange ( self , value ) : log . debug ( 'combo box. selected %s' % value ) self . select_by_value ( value ) return ( value , ) | Called when a new DropDownItem gets selected . |
25,472 | def append_from_list ( self , content , fill_title = False ) : row_index = 0 for row in content : tr = TableRow ( ) column_index = 0 for item in row : if row_index == 0 and fill_title : ti = TableTitle ( item ) else : ti = TableItem ( item ) tr . append ( ti , str ( column_index ) ) column_index = column_index + 1 self . append ( tr , str ( row_index ) ) row_index = row_index + 1 | Appends rows created from the data contained in the provided list of tuples of strings . The first tuple of the list can be set as table title . |
25,473 | def item_at ( self , row , column ) : return self . children [ str ( row ) ] . children [ str ( column ) ] | Returns the TableItem instance at row column cordinates |
25,474 | def set_row_count ( self , count ) : current_row_count = self . row_count ( ) current_column_count = self . column_count ( ) if count > current_row_count : cl = TableEditableItem if self . _editable else TableItem for i in range ( current_row_count , count ) : tr = TableRow ( ) for c in range ( 0 , current_column_count ) : tr . append ( cl ( ) , str ( c ) ) if self . _editable : tr . children [ str ( c ) ] . onchange . connect ( self . on_item_changed , int ( i ) , int ( c ) ) self . append ( tr , str ( i ) ) self . _update_first_row ( ) elif count < current_row_count : for i in range ( count , current_row_count ) : self . remove_child ( self . children [ str ( i ) ] ) | Sets the table row count . |
25,475 | def set_column_count ( self , count ) : current_row_count = self . row_count ( ) current_column_count = self . column_count ( ) if count > current_column_count : cl = TableEditableItem if self . _editable else TableItem for r_key in self . children . keys ( ) : row = self . children [ r_key ] for i in range ( current_column_count , count ) : row . append ( cl ( ) , str ( i ) ) if self . _editable : row . children [ str ( i ) ] . onchange . connect ( self . on_item_changed , int ( r_key ) , int ( i ) ) self . _update_first_row ( ) elif count < current_column_count : for row in self . children . values ( ) : for i in range ( count , current_column_count ) : row . remove_child ( row . children [ str ( i ) ] ) self . _column_count = count | Sets the table column count . |
25,476 | def on_item_changed ( self , item , new_value , row , column ) : return ( item , new_value , row , column ) | Event for the item change . |
25,477 | def set_viewbox ( self , x , y , w , h ) : self . attributes [ 'viewBox' ] = "%s %s %s %s" % ( x , y , w , h ) self . attributes [ 'preserveAspectRatio' ] = 'none' | Sets the origin and size of the viewbox describing a virtual view area . |
25,478 | def set_position ( self , x , y ) : self . attributes [ 'x' ] = str ( x ) self . attributes [ 'y' ] = str ( y ) | Sets the shape position . |
25,479 | def set_size ( self , w , h ) : self . attributes [ 'width' ] = str ( w ) self . attributes [ 'height' ] = str ( h ) | Sets the rectangle size . |
25,480 | def start ( main_gui_class , ** kwargs ) : debug = kwargs . pop ( 'debug' , False ) standalone = kwargs . pop ( 'standalone' , False ) logging . basicConfig ( level = logging . DEBUG if debug else logging . INFO , format = '%(name)-16s %(levelname)-8s %(message)s' ) logging . getLogger ( 'remi' ) . setLevel ( level = logging . DEBUG if debug else logging . INFO ) if standalone : s = StandaloneServer ( main_gui_class , start = True , ** kwargs ) else : s = Server ( main_gui_class , start = True , ** kwargs ) | This method starts the webserver with a specific App subclass . |
25,481 | def _instance ( self ) : global clients global runtimeInstances self . session = 0 if 'cookie' in self . headers : self . session = parse_session_cookie ( self . headers [ 'cookie' ] ) if self . session == None : self . session = 0 if not self . session in clients . keys ( ) : self . session = 0 if self . session == 0 : if self . server . multiple_instance : self . session = int ( time . time ( ) * 1000 ) del self . headers [ 'cookie' ] if not ( self . session in clients ) : self . update_interval = self . server . update_interval from remi import gui head = gui . HEAD ( self . server . title ) head . add_child ( 'internal_css' , "<link href='/res:style.css' rel='stylesheet' />\n" ) body = gui . BODY ( ) body . onload . connect ( self . onload ) body . onerror . connect ( self . onerror ) body . ononline . connect ( self . ononline ) body . onpagehide . connect ( self . onpagehide ) body . onpageshow . connect ( self . onpageshow ) body . onresize . connect ( self . onresize ) self . page = gui . HTML ( ) self . page . add_child ( 'head' , head ) self . page . add_child ( 'body' , body ) if not hasattr ( self , 'websockets' ) : self . websockets = [ ] self . update_lock = threading . RLock ( ) if not hasattr ( self , '_need_update_flag' ) : self . _need_update_flag = False self . _stop_update_flag = False if self . update_interval > 0 : self . _update_thread = threading . Thread ( target = self . _idle_loop ) self . _update_thread . setDaemon ( True ) self . _update_thread . start ( ) runtimeInstances [ str ( id ( self ) ) ] = self clients [ self . session ] = self else : client = clients [ self . session ] self . websockets = client . websockets self . page = client . page self . update_lock = client . update_lock self . update_interval = client . update_interval self . _need_update_flag = client . _need_update_flag if hasattr ( client , '_update_thread' ) : self . _update_thread = client . _update_thread net_interface_ip = self . headers . get ( 'Host' , "%s:%s" % ( self . connection . getsockname ( ) [ 0 ] , self . server . server_address [ 1 ] ) ) websocket_timeout_timer_ms = str ( self . server . websocket_timeout_timer_ms ) pending_messages_queue_length = str ( self . server . pending_messages_queue_length ) self . page . children [ 'head' ] . set_internal_js ( net_interface_ip , pending_messages_queue_length , websocket_timeout_timer_ms ) | This method is used to get the Application instance previously created managing on this it is possible to switch to single instance for multiple clients or multiple instance for multiple clients execution way |
25,482 | def do_gui_update ( self ) : with self . update_lock : changed_widget_dict = { } self . root . repr ( changed_widget_dict ) for widget in changed_widget_dict . keys ( ) : html = changed_widget_dict [ widget ] __id = str ( widget . identifier ) self . _send_spontaneous_websocket_message ( _MSG_UPDATE + __id + ',' + to_websocket ( html ) ) self . _need_update_flag = False | This method gets called also by Timer a new thread and so needs to lock the update |
25,483 | def do_GET ( self ) : if "Upgrade" in self . headers : if self . headers [ 'Upgrade' ] == 'websocket' : ws = WebSocketsHandler ( self . headers , self . request , self . client_address , self . server ) return do_process = False if self . server . auth is None : do_process = True else : if not ( 'Authorization' in self . headers ) or self . headers [ 'Authorization' ] is None : self . _log . info ( "Authenticating" ) self . do_AUTHHEAD ( ) self . wfile . write ( encode_text ( 'no auth header received' ) ) elif self . headers [ 'Authorization' ] == 'Basic ' + self . server . auth . decode ( ) : do_process = True else : self . do_AUTHHEAD ( ) self . wfile . write ( encode_text ( self . headers [ 'Authorization' ] ) ) self . wfile . write ( encode_text ( 'not authenticated' ) ) if do_process : path = str ( unquote ( self . path ) ) try : self . _instance ( ) with self . update_lock : if not 'root' in self . page . children [ 'body' ] . children . keys ( ) : self . _log . info ( 'built UI (path=%s)' % path ) self . set_root_widget ( self . main ( * self . server . userdata ) ) self . _process_all ( path ) except : self . _log . error ( 'error processing GET request' , exc_info = True ) | Handler for the GET requests . |
25,484 | def on_close ( self ) : self . _stop_update_flag = True for ws in self . websockets : ws . close ( ) | Called by the server when the App have to be terminated |
25,485 | def update ( self , widget , widget_tree ) : self . listeners_list = [ ] self . build_widget_list_from_tree ( widget_tree ) self . label . set_text ( 'Signal connections: ' + widget . attributes [ 'editor_varname' ] ) self . container = gui . VBox ( width = '100%' , height = '90%' ) self . container . style [ 'justify-content' ] = 'flex-start' self . container . style [ 'overflow-y' ] = 'scroll' self . append ( self . container , 'container' ) for ( setOnEventListenerFuncname , setOnEventListenerFunc ) in inspect . getmembers ( widget ) : if hasattr ( setOnEventListenerFunc , '_event_info' ) : self . container . append ( SignalConnection ( widget , self . listeners_list , setOnEventListenerFuncname , setOnEventListenerFunc , width = '100%' ) ) | for the selected widget are listed the relative signals for each signal there is a dropdown containing all the widgets the user will select the widget that have to listen a specific event |
25,486 | def confirm_dialog ( self , emitter ) : self . from_fields_to_dict ( ) return super ( ProjectConfigurationDialog , self ) . confirm_dialog ( self ) | event called pressing on OK button . |
25,487 | def show ( self , baseAppInstance ) : self . from_dict_to_fields ( self . configDict ) super ( ProjectConfigurationDialog , self ) . show ( baseAppInstance ) | Allows to show the widget as root window |
25,488 | def set_value ( self , value ) : v = 0 measure_unit = 'px' try : v = int ( float ( value . replace ( 'px' , '' ) ) ) except ValueError : try : v = int ( float ( value . replace ( '%' , '' ) ) ) measure_unit = '%' except ValueError : pass self . numInput . set_value ( v ) self . dropMeasureUnit . set_value ( measure_unit ) | The value have to be in the form 10px or 10% so numeric value plus measure unit |
25,489 | def on_table_row_click ( self , row , item ) : if hasattr ( self , "last_clicked_row" ) : del self . last_clicked_row . style [ 'outline' ] self . last_clicked_row = row self . last_clicked_row . style [ 'outline' ] = "2px dotted blue" return ( row , item ) | Highlight selected row . |
25,490 | def extract_kwargs ( docstring ) : lines = inspect . cleandoc ( docstring ) . split ( '\n' ) retval = [ ] while lines [ 0 ] != 'Parameters' : lines . pop ( 0 ) lines . pop ( 0 ) lines . pop ( 0 ) while lines and lines [ 0 ] : name , type_ = lines . pop ( 0 ) . split ( ':' , 1 ) description = [ ] while lines and lines [ 0 ] . startswith ( ' ' ) : description . append ( lines . pop ( 0 ) . strip ( ) ) if 'optional' in type_ : retval . append ( ( name . strip ( ) , type_ . strip ( ) , description ) ) return retval | Extract keyword argument documentation from a function s docstring . |
25,491 | def to_docstring ( kwargs , lpad = '' ) : buf = io . StringIO ( ) for name , type_ , description in kwargs : buf . write ( '%s%s: %s\n' % ( lpad , name , type_ ) ) for line in description : buf . write ( '%s %s\n' % ( lpad , line ) ) return buf . getvalue ( ) | Reconstruct a docstring from keyword argument info . |
25,492 | def extract_examples_from_readme_rst ( indent = ' ' ) : curr_dir = os . path . dirname ( os . path . abspath ( __file__ ) ) readme_path = os . path . join ( curr_dir , '..' , 'README.rst' ) try : with open ( readme_path ) as fin : lines = list ( fin ) start = lines . index ( '.. _doctools_before_examples:\n' ) end = lines . index ( ".. _doctools_after_examples:\n" ) lines = lines [ start + 4 : end - 2 ] return '' . join ( [ indent + re . sub ( '^ ' , '' , l ) for l in lines ] ) except Exception : return indent + 'See README.rst' | Extract examples from this project s README . rst file . |
25,493 | def open ( bucket_id , key_id , mode , buffer_size = DEFAULT_BUFFER_SIZE , min_part_size = DEFAULT_MIN_PART_SIZE , session = None , resource_kwargs = None , multipart_upload_kwargs = None , ) : logger . debug ( '%r' , locals ( ) ) if mode not in MODES : raise NotImplementedError ( 'bad mode: %r expected one of %r' % ( mode , MODES ) ) if resource_kwargs is None : resource_kwargs = { } if multipart_upload_kwargs is None : multipart_upload_kwargs = { } if mode == READ_BINARY : fileobj = SeekableBufferedInputBase ( bucket_id , key_id , buffer_size = buffer_size , session = session , resource_kwargs = resource_kwargs , ) elif mode == WRITE_BINARY : fileobj = BufferedOutputBase ( bucket_id , key_id , min_part_size = min_part_size , session = session , multipart_upload_kwargs = multipart_upload_kwargs , resource_kwargs = resource_kwargs , ) else : assert False , 'unexpected mode: %r' % mode return fileobj | Open an S3 object for reading or writing . |
25,494 | def read ( self , size = - 1 ) : if size == 0 : return b'' elif size < 0 : from_buf = self . _read_from_buffer ( ) self . _current_pos = self . _content_length return from_buf + self . _raw_reader . read ( ) if len ( self . _buffer ) >= size : return self . _read_from_buffer ( size ) if self . _eof : return self . _read_from_buffer ( ) self . _fill_buffer ( size ) return self . _read_from_buffer ( size ) | Read up to size bytes from the object and return them . |
25,495 | def readline ( self , limit = - 1 ) : if limit != - 1 : raise NotImplementedError ( 'limits other than -1 not implemented yet' ) the_line = io . BytesIO ( ) while not ( self . _eof and len ( self . _buffer ) == 0 ) : remaining_buffer = self . _buffer . peek ( ) if self . _line_terminator in remaining_buffer : next_newline = remaining_buffer . index ( self . _line_terminator ) the_line . write ( self . _read_from_buffer ( next_newline + 1 ) ) break else : the_line . write ( self . _read_from_buffer ( ) ) self . _fill_buffer ( ) return the_line . getvalue ( ) | Read up to and including the next newline . Returns the bytes read . |
25,496 | def _read_from_buffer ( self , size = - 1 ) : size = size if size >= 0 else len ( self . _buffer ) part = self . _buffer . read ( size ) self . _current_pos += len ( part ) return part | Remove at most size bytes from our buffer and return them . |
25,497 | def open ( path , mode = 'r' , host = None , user = None , port = DEFAULT_PORT ) : if not host : raise ValueError ( 'you must specify the host to connect to' ) if not user : user = getpass . getuser ( ) conn = _connect ( host , user , port ) sftp_client = conn . get_transport ( ) . open_sftp_client ( ) return sftp_client . open ( path , mode ) | Open a file on a remote machine over SSH . |
25,498 | def open ( uri , mode , kerberos = False , user = None , password = None ) : if mode == 'rb' : return BufferedInputBase ( uri , mode , kerberos = kerberos , user = user , password = password ) else : raise NotImplementedError ( 'http support for mode %r not implemented' % mode ) | Implement streamed reader from a web site . |
25,499 | def read ( self , size = - 1 ) : logger . debug ( "reading with size: %d" , size ) if self . response is None : return b'' if size == 0 : return b'' elif size < 0 and len ( self . _read_buffer ) == 0 : retval = self . response . raw . read ( ) elif size < 0 : retval = self . _read_buffer . read ( ) + self . response . raw . read ( ) else : while len ( self . _read_buffer ) < size : logger . debug ( "http reading more content at current_pos: %d with size: %d" , self . _current_pos , size ) bytes_read = self . _read_buffer . fill ( self . _read_iter ) if bytes_read == 0 : retval = self . _read_buffer . read ( ) self . _current_pos += len ( retval ) return retval retval = self . _read_buffer . read ( size ) self . _current_pos += len ( retval ) return retval | Mimics the read call to a filehandle object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.