idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
229,700
def mutual_info ( rho : Density , qubits0 : Qubits , qubits1 : Qubits = None , base : float = None ) -> float : if qubits1 is None : qubits1 = tuple ( set ( rho . qubits ) - set ( qubits0 ) ) rho0 = rho . partial_trace ( qubits1 ) rho1 = rho . partial_trace ( qubits0 ) ent = entropy ( rho , base ) ent0 = entropy ( rho0...
Compute the bipartite von - Neumann mutual information of a mixed quantum state .
229,701
def gate_angle ( gate0 : Gate , gate1 : Gate ) -> bk . BKTensor : return fubini_study_angle ( gate0 . vec , gate1 . vec )
The Fubini - Study angle between gates
229,702
def channel_angle ( chan0 : Channel , chan1 : Channel ) -> bk . BKTensor : return fubini_study_angle ( chan0 . vec , chan1 . vec )
The Fubini - Study angle between channels
229,703
def inner_product ( vec0 : QubitVector , vec1 : QubitVector ) -> bk . BKTensor : if vec0 . rank != vec1 . rank or vec0 . qubit_nb != vec1 . qubit_nb : raise ValueError ( 'Incompatibly vectors. Qubits and rank must match' ) vec1 = vec1 . permute ( vec0 . qubits ) return bk . inner ( vec0 . tensor , vec1 . tensor )
Hilbert - Schmidt inner product between qubit vectors
229,704
def outer_product ( vec0 : QubitVector , vec1 : QubitVector ) -> QubitVector : R = vec0 . rank R1 = vec1 . rank N0 = vec0 . qubit_nb N1 = vec1 . qubit_nb if R != R1 : raise ValueError ( 'Incompatibly vectors. Rank must match' ) if not set ( vec0 . qubits ) . isdisjoint ( vec1 . qubits ) : raise ValueError ( 'Overlappin...
Direct product of qubit vectors
229,705
def vectors_close ( vec0 : QubitVector , vec1 : QubitVector , tolerance : float = TOLERANCE ) -> bool : if vec0 . rank != vec1 . rank : return False if vec0 . qubit_nb != vec1 . qubit_nb : return False if set ( vec0 . qubits ) ^ set ( vec1 . qubits ) : return False return bk . evaluate ( fubini_study_angle ( vec0 , vec...
Return True if vectors in close in the projective Hilbert space .
229,706
def flatten ( self ) -> bk . BKTensor : N = self . qubit_nb R = self . rank return bk . reshape ( self . tensor , [ 2 ** N ] * R )
Return tensor with with qubit indices flattened
229,707
def relabel ( self , qubits : Qubits ) -> 'QubitVector' : qubits = tuple ( qubits ) assert len ( qubits ) == self . qubit_nb vec = copy ( self ) vec . qubits = qubits return vec
Return a copy of this vector with new qubits
229,708
def H ( self ) -> 'QubitVector' : N = self . qubit_nb R = self . rank tensor = self . tensor tensor = bk . reshape ( tensor , [ 2 ** ( N * R // 2 ) ] * 2 ) tensor = bk . transpose ( tensor ) tensor = bk . reshape ( tensor , [ 2 ] * R * N ) tensor = bk . conj ( tensor ) return QubitVector ( tensor , self . qubits )
Return the conjugate transpose of this tensor .
229,709
def norm ( self ) -> bk . BKTensor : return bk . absolute ( bk . inner ( self . tensor , self . tensor ) )
Return the norm of this vector
229,710
def partial_trace ( self , qubits : Qubits ) -> 'QubitVector' : N = self . qubit_nb R = self . rank if R == 1 : raise ValueError ( 'Cannot take trace of vector' ) new_qubits : List [ Qubit ] = list ( self . qubits ) for q in qubits : new_qubits . remove ( q ) if not new_qubits : raise ValueError ( 'Cannot remove all qu...
Return the partial trace over some subset of qubits
229,711
def fit_zyz ( target_gate ) : steps = 1000 dev = '/gpu:0' if bk . DEVICE == 'gpu' else '/cpu:0' with tf . device ( dev ) : t = tf . Variable ( tf . random . normal ( [ 3 ] ) ) def loss_fn ( ) : gate = qf . ZYZ ( t [ 0 ] , t [ 1 ] , t [ 2 ] ) ang = qf . fubini_study_angle ( target_gate . vec , gate . vec ) return ang op...
Tensorflow 2 . 0 example . Given an arbitrary one - qubit gate use gradient descent to find corresponding parameters of a universal ZYZ gate .
229,712
def run ( self , ket : State = None ) -> State : if ket is None : qubits = self . qubits ket = zero_state ( qubits ) ket = self . _initilize ( ket ) pc = 0 while pc >= 0 and pc < len ( self ) : instr = self . instructions [ pc ] ket = ket . update ( { PC : pc + 1 } ) ket = instr . run ( ket ) pc = ket . memory [ PC ] r...
Compiles and runs a program . The optional program argument supplies the initial state and memory . Else qubits and classical bits start from zero states .
229,713
def relabel ( self , qubits : Qubits ) -> 'Gate' : gate = copy ( self ) gate . vec = gate . vec . relabel ( qubits ) return gate
Return a copy of this Gate with new qubits
229,714
def run ( self , ket : State ) -> State : qubits = self . qubits indices = [ ket . qubits . index ( q ) for q in qubits ] tensor = bk . tensormul ( self . tensor , ket . tensor , indices ) return State ( tensor , ket . qubits , ket . memory )
Apply the action of this gate upon a state
229,715
def evolve ( self , rho : Density ) -> Density : chan = self . aschannel ( ) return chan . evolve ( rho )
Apply the action of this gate upon a density
229,716
def aschannel ( self ) -> 'Channel' : N = self . qubit_nb R = 4 tensor = bk . outer ( self . tensor , self . H . tensor ) tensor = bk . reshape ( tensor , [ 2 ** N ] * R ) tensor = bk . transpose ( tensor , [ 0 , 3 , 1 , 2 ] ) return Channel ( tensor , self . qubits )
Converts a Gate into a Channel
229,717
def su ( self ) -> 'Gate' : rank = 2 ** self . qubit_nb U = asarray ( self . asoperator ( ) ) U /= np . linalg . det ( U ) ** ( 1 / rank ) return Gate ( tensor = U , qubits = self . qubits )
Convert gate tensor to the special unitary group .
229,718
def relabel ( self , qubits : Qubits ) -> 'Channel' : chan = copy ( self ) chan . vec = chan . vec . relabel ( qubits ) return chan
Return a copy of this channel with new qubits
229,719
def permute ( self , qubits : Qubits ) -> 'Channel' : vec = self . vec . permute ( qubits ) return Channel ( vec . tensor , qubits = vec . qubits )
Return a copy of this channel with qubits in new order
229,720
def sharp ( self ) -> 'Channel' : r N = self . qubit_nb tensor = self . tensor tensor = bk . reshape ( tensor , [ 2 ** N ] * 4 ) tensor = bk . transpose ( tensor , ( 0 , 2 , 1 , 3 ) ) tensor = bk . reshape ( tensor , [ 2 ] * 4 * N ) return Channel ( tensor , self . qubits )
r Return the sharp transpose of the superoperator .
229,721
def choi ( self ) -> bk . BKTensor : N = self . qubit_nb return bk . reshape ( self . sharp . tensor , [ 2 ** ( N * 2 ) ] * 2 )
Return the Choi matrix representation of this super operator
229,722
def evolve ( self , rho : Density ) -> Density : N = rho . qubit_nb qubits = rho . qubits indices = list ( [ qubits . index ( q ) for q in self . qubits ] ) + list ( [ qubits . index ( q ) + N for q in self . qubits ] ) tensor = bk . tensormul ( self . tensor , rho . tensor , indices ) return Density ( tensor , qubits ...
Apply the action of this channel upon a density
229,723
def fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) return newvalue
Cast to float tensor
229,724
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( array , dtype = CTYPE ) if DEVICE == 'gpu' : tensor = tensor . gpu ( ) N = int ( math . log2 ( size ( tensor ) ) ) tensor = tf . reshape ( tensor , ( [ 2 ] * N ) ) return tensor
Convert to product tensor
229,725
def count_operations ( elements : Iterable [ Operation ] ) -> Dict [ Type [ Operation ] , int ] : op_count : Dict [ Type [ Operation ] , int ] = defaultdict ( int ) for elem in elements : op_count [ type ( elem ) ] += 1 return dict ( op_count )
Return a count of different operation types given a colelction of operations such as a Circuit or DAGCircuit
229,726
def map_gate ( gate : Gate , args : Sequence [ Qubits ] ) -> Circuit : circ = Circuit ( ) for qubits in args : circ += gate . relabel ( qubits ) return circ
Applies the same gate all input qubits in the argument list .
229,727
def qft_circuit ( qubits : Qubits ) -> Circuit : N = len ( qubits ) circ = Circuit ( ) for n0 in range ( N ) : q0 = qubits [ n0 ] circ += H ( q0 ) for n1 in range ( n0 + 1 , N ) : q1 = qubits [ n1 ] angle = pi / 2 ** ( n1 - n0 ) circ += CPHASE ( angle , q1 , q0 ) circ . extend ( reversal_circuit ( qubits ) ) return cir...
Returns the Quantum Fourier Transform circuit
229,728
def reversal_circuit ( qubits : Qubits ) -> Circuit : N = len ( qubits ) circ = Circuit ( ) for n in range ( N // 2 ) : circ += SWAP ( qubits [ n ] , qubits [ N - 1 - n ] ) return circ
Returns a circuit to reverse qubits
229,729
def zyz_circuit ( t0 : float , t1 : float , t2 : float , q0 : Qubit ) -> Circuit : circ = Circuit ( ) circ += TZ ( t0 , q0 ) circ += TY ( t1 , q0 ) circ += TZ ( t2 , q0 ) return circ
Circuit equivalent of 1 - qubit ZYZ gate
229,730
def phase_estimation_circuit ( gate : Gate , outputs : Qubits ) -> Circuit : circ = Circuit ( ) circ += map_gate ( H ( ) , list ( zip ( outputs ) ) ) for cq in reversed ( outputs ) : cgate = control_gate ( cq , gate ) circ += cgate gate = gate @ gate circ += qft_circuit ( outputs ) . H return circ
Returns a circuit for quantum phase estimation .
229,731
def ghz_circuit ( qubits : Qubits ) -> Circuit : circ = Circuit ( ) circ += H ( qubits [ 0 ] ) for q0 in range ( 0 , len ( qubits ) - 1 ) : circ += CNOT ( qubits [ q0 ] , qubits [ q0 + 1 ] ) return circ
Returns a circuit that prepares a multi - qubit Bell state from the zero state .
229,732
def extend ( self , other : Operation ) -> None : if isinstance ( other , Circuit ) : self . elements . extend ( other . elements ) else : self . elements . extend ( [ other ] )
Append gates from circuit to the end of this circuit
229,733
def run ( self , ket : State = None ) -> State : if ket is None : qubits = self . qubits ket = zero_state ( qubits = qubits ) for elem in self . elements : ket = elem . run ( ket ) return ket
Apply the action of this circuit upon a state .
229,734
def asgate ( self ) -> Gate : gate = identity_gate ( self . qubits ) for elem in self . elements : gate = elem . asgate ( ) @ gate return gate
Return the action of this circuit as a gate
229,735
def join_channels ( * channels : Channel ) -> Channel : vectors = [ chan . vec for chan in channels ] vec = reduce ( outer_product , vectors ) return Channel ( vec . tensor , vec . qubits )
Join two channels acting on different qubits into a single channel acting on all qubits
229,736
def channel_to_kraus ( chan : Channel ) -> 'Kraus' : qubits = chan . qubits N = chan . qubit_nb choi = asarray ( chan . choi ( ) ) evals , evecs = np . linalg . eig ( choi ) evecs = np . transpose ( evecs ) assert np . allclose ( evals . imag , 0.0 ) assert np . all ( evals . real >= 0.0 ) values = np . sqrt ( evals . ...
Convert a channel superoperator into a Kraus operator representation of the same channel .
229,737
def run ( self , ket : State ) -> State : res = [ op . run ( ket ) for op in self . operators ] probs = [ asarray ( ket . norm ( ) ) * w for ket , w in zip ( res , self . weights ) ] probs = np . asarray ( probs ) probs /= np . sum ( probs ) newket = np . random . choice ( res , p = probs ) return newket . normalize ( ...
Apply the action of this Kraus quantum operation upon a state
229,738
def evolve ( self , rho : Density ) -> Density : qubits = rho . qubits results = [ op . evolve ( rho ) for op in self . operators ] tensors = [ rho . tensor * w for rho , w in zip ( results , self . weights ) ] tensor = reduce ( add , tensors ) return Density ( tensor , qubits )
Apply the action of this Kraus quantum operation upon a density
229,739
def H ( self ) -> 'Kraus' : operators = [ op . H for op in self . operators ] return Kraus ( operators , self . weights )
Return the complex conjugate of this Kraus operation
229,740
def asgate ( self ) -> Gate : return np . random . choice ( self . operators , p = self . weights )
Return one of the composite Kraus operators at random with the appropriate weights
229,741
def _display_layers ( circ : Circuit , qubits : Qubits ) -> Circuit : N = len ( qubits ) qubit_idx = dict ( zip ( qubits , range ( N ) ) ) gate_layers = DAGCircuit ( circ ) . layers ( ) layers = [ ] lcirc = Circuit ( ) layers . append ( lcirc ) unused = [ True ] * N for gl in gate_layers : assert isinstance ( gl , Circ...
Separate a circuit into groups of gates that do not visually overlap
229,742
def render_latex ( latex : str ) -> PIL . Image : tmpfilename = 'circ' with tempfile . TemporaryDirectory ( ) as tmpdirname : tmppath = os . path . join ( tmpdirname , tmpfilename ) with open ( tmppath + '.tex' , 'w' ) as latex_file : latex_file . write ( latex ) subprocess . run ( [ "pdflatex" , "-halt-on-error" , "-o...
Convert a single page LaTeX document into an image .
229,743
def circuit_to_image ( circ : Circuit , qubits : Qubits = None ) -> PIL . Image : latex = circuit_to_latex ( circ , qubits ) img = render_latex ( latex ) return img
Create an image of a quantum circuit .
229,744
def _latex_format ( obj : Any ) -> str : if isinstance ( obj , float ) : try : return sympy . latex ( symbolize ( obj ) ) except ValueError : return "{0:.4g}" . format ( obj ) return str ( obj )
Format an object as a latex string .
229,745
def fit_zyz ( target_gate ) : assert bk . BACKEND == 'eager' tf = bk . TL tfe = bk . tfe steps = 4000 dev = '/gpu:0' if bk . DEVICE == 'gpu' else '/cpu:0' with tf . device ( dev ) : t = tfe . Variable ( np . random . normal ( size = [ 3 ] ) , name = 't' ) def loss_fn ( ) : gate = qf . ZYZ ( t [ 0 ] , t [ 1 ] , t [ 2 ] ...
Tensorflow eager mode example . Given an arbitrary one - qubit gate use gradient descent to find corresponding parameters of a universal ZYZ gate .
229,746
def print_versions ( file : typing . TextIO = None ) -> None : print ( '** QuantumFlow dependencies (> python -m quantumflow.meta) **' ) print ( 'quantumflow \t' , qf . __version__ , file = file ) print ( 'python \t' , sys . version [ 0 : 5 ] , file = file ) print ( 'numpy \t' , np . __version__ , file = fil...
Print version strings of currently installed dependencies
229,747
def fit_zyz ( target_gate ) : assert bk . BACKEND == 'tensorflow' tf = bk . TL steps = 4000 t = tf . get_variable ( 't' , [ 3 ] ) gate = qf . ZYZ ( t [ 0 ] , t [ 1 ] , t [ 2 ] ) ang = qf . fubini_study_angle ( target_gate . vec , gate . vec ) opt = tf . train . AdamOptimizer ( learning_rate = 0.001 ) train = opt . mini...
Tensorflow example . Given an arbitrary one - qubit gate use gradient descent to find corresponding parameters of a universal ZYZ gate .
229,748
def zyz_decomposition ( gate : Gate ) -> Circuit : if gate . qubit_nb != 1 : raise ValueError ( 'Expected 1-qubit gate' ) q , = gate . qubits U = asarray ( gate . asoperator ( ) ) U /= np . linalg . det ( U ) ** ( 1 / 2 ) if abs ( U [ 0 , 0 ] ) > abs ( U [ 1 , 0 ] ) : theta1 = 2 * np . arccos ( min ( abs ( U [ 0 , 0 ] ...
Returns the Euler Z - Y - Z decomposition of a local 1 - qubit gate .
229,749
def kronecker_decomposition ( gate : Gate ) -> Circuit : if gate . qubit_nb != 2 : raise ValueError ( 'Expected 2-qubit gate' ) U = asarray ( gate . asoperator ( ) ) rank = 2 ** gate . qubit_nb U /= np . linalg . det ( U ) ** ( 1 / rank ) R = np . stack ( [ U [ 0 : 2 , 0 : 2 ] . reshape ( 4 ) , U [ 0 : 2 , 2 : 4 ] . re...
Decompose a 2 - qubit unitary composed of two 1 - qubit local gates .
229,750
def canonical_coords ( gate : Gate ) -> Sequence [ float ] : circ = canonical_decomposition ( gate ) gate = circ . elements [ 6 ] params = [ gate . params [ key ] for key in ( 'tx' , 'ty' , 'tz' ) ] return params
Returns the canonical coordinates of a 2 - qubit gate
229,751
def _eig_complex_symmetric ( M : np . ndarray ) -> Tuple [ np . ndarray , np . ndarray ] : if not np . allclose ( M , M . transpose ( ) ) : raise np . linalg . LinAlgError ( 'Not a symmetric matrix' ) max_attempts = 16 for _ in range ( max_attempts ) : c = np . random . uniform ( 0 , 1 ) matrix = c * M . real + ( 1 - c...
Diagonalize a complex symmetric matrix . The eigenvalues are complex and the eigenvectors form an orthogonal matrix .
229,752
def maxcut_qaoa ( graph , steps = DEFAULT_STEPS , learning_rate = LEARNING_RATE , verbose = False ) : if not isinstance ( graph , nx . Graph ) : graph = nx . from_edgelist ( graph ) init_scale = 0.01 init_bias = 0.5 init_beta = normal ( loc = init_bias , scale = init_scale , size = [ steps ] ) init_gamma = normal ( loc...
QAOA Maxcut using tensorflow
229,753
def identity_gate ( qubits : Union [ int , Qubits ] ) -> Gate : _ , qubits = qubits_count_tuple ( qubits ) return I ( * qubits )
Returns the K - qubit identity gate
229,754
def join_gates ( * gates : Gate ) -> Gate : vectors = [ gate . vec for gate in gates ] vec = reduce ( outer_product , vectors ) return Gate ( vec . tensor , vec . qubits )
Direct product of two gates . Qubit count is the sum of each gate s bit count .
229,755
def control_gate ( control : Qubit , gate : Gate ) -> Gate : if control in gate . qubits : raise ValueError ( 'Gate and control qubits overlap' ) qubits = [ control , * gate . qubits ] gate_tensor = join_gates ( P0 ( control ) , identity_gate ( gate . qubits ) ) . tensor + join_gates ( P1 ( control ) , gate ) . tensor ...
Return a controlled unitary gate . Given a gate acting on K qubits return a new gate on K + 1 qubits prepended with a control bit .
229,756
def conditional_gate ( control : Qubit , gate0 : Gate , gate1 : Gate ) -> Gate : assert gate0 . qubits == gate1 . qubits tensor = join_gates ( P0 ( control ) , gate0 ) . tensor tensor += join_gates ( P1 ( control ) , gate1 ) . tensor gate = Gate ( tensor = tensor , qubits = [ control , * gate0 . qubits ] ) return gate
Return a conditional unitary gate . Do gate0 on bit 1 if bit 0 is zero else do gate1 on 1
229,757
def print_gate ( gate : Gate , ndigits : int = 2 , file : TextIO = None ) -> None : N = gate . qubit_nb gate_tensor = gate . vec . asarray ( ) lines = [ ] for index , amplitude in np . ndenumerate ( gate_tensor ) : ket = "" . join ( [ str ( n ) for n in index [ 0 : N ] ] ) bra = "" . join ( [ str ( index [ n ] ) for n ...
Pretty print a gate tensor
229,758
def random_gate ( qubits : Union [ int , Qubits ] ) -> Gate : r N , qubits = qubits_count_tuple ( qubits ) unitary = scipy . stats . unitary_group . rvs ( 2 ** N ) return Gate ( unitary , qubits = qubits , name = 'RAND{}' . format ( N ) )
r Returns a random unitary gate on K qubits .
229,759
def has_function ( function_name , libraries = None ) : compiler = distutils . ccompiler . new_compiler ( ) with muted ( sys . stdout , sys . stderr ) : result = compiler . has_function ( function_name , libraries = libraries ) if os . path . exists ( 'a.out' ) : os . remove ( 'a.out' ) return result
Checks if a given functions exists in the current platform .
229,760
async def handle_agent_message ( self , agent_addr , message ) : message_handlers = { AgentHello : self . handle_agent_hello , AgentJobStarted : self . handle_agent_job_started , AgentJobDone : self . handle_agent_job_done , AgentJobSSHDebug : self . handle_agent_job_ssh_debug , Pong : self . _handle_pong } try : func ...
Dispatch messages received from agents to the right handlers
229,761
async def handle_client_hello ( self , client_addr , _ : ClientHello ) : self . _logger . info ( "New client connected %s" , client_addr ) self . _registered_clients . add ( client_addr ) await self . send_container_update_to_client ( [ client_addr ] )
Handle an ClientHello message . Send available containers to the client
229,762
async def handle_client_ping ( self , client_addr , _ : Ping ) : await ZMQUtils . send_with_addr ( self . _client_socket , client_addr , Pong ( ) )
Handle an Ping message . Pong the client
229,763
async def handle_client_new_job ( self , client_addr , message : ClientNewJob ) : self . _logger . info ( "Adding a new job %s %s to the queue" , client_addr , message . job_id ) self . _waiting_jobs [ ( client_addr , message . job_id ) ] = message await self . update_queue ( )
Handle an ClientNewJob message . Add a job to the queue and triggers an update
229,764
async def handle_client_kill_job ( self , client_addr , message : ClientKillJob ) : if ( client_addr , message . job_id ) in self . _waiting_jobs : del self . _waiting_jobs [ ( client_addr , message . job_id ) ] await ZMQUtils . send_with_addr ( self . _client_socket , client_addr , BackendJobDone ( message . job_id , ...
Handle an ClientKillJob message . Remove a job from the waiting list or send the kill message to the right agent .
229,765
async def handle_client_get_queue ( self , client_addr , _ : ClientGetQueue ) : jobs_running = list ( ) for backend_job_id , content in self . _job_running . items ( ) : jobs_running . append ( ( content [ 1 ] . job_id , backend_job_id [ 0 ] == client_addr , self . _registered_agents [ content [ 0 ] ] , content [ 1 ] ....
Handles a ClientGetQueue message . Send back info about the job queue
229,766
async def update_queue ( self ) : not_found_for_agent = [ ] while len ( self . _available_agents ) > 0 and len ( self . _waiting_jobs ) > 0 : agent_addr = self . _available_agents . pop ( 0 ) found = False client_addr , job_id , job_msg = None , None , None for ( client_addr , job_id ) , job_msg in self . _waiting_jobs...
Send waiting jobs to available agents
229,767
async def handle_agent_hello ( self , agent_addr , message : AgentHello ) : self . _logger . info ( "Agent %s (%s) said hello" , agent_addr , message . friendly_name ) if agent_addr in self . _registered_agents : await self . _delete_agent ( agent_addr ) self . _registered_agents [ agent_addr ] = message . friendly_nam...
Handle an AgentAvailable message . Add agent_addr to the list of available agents
229,768
async def handle_agent_job_started ( self , agent_addr , message : AgentJobStarted ) : self . _logger . debug ( "Job %s %s started on agent %s" , message . job_id [ 0 ] , message . job_id [ 1 ] , agent_addr ) await ZMQUtils . send_with_addr ( self . _client_socket , message . job_id [ 0 ] , BackendJobStarted ( message ...
Handle an AgentJobStarted message . Send the data back to the client
229,769
async def handle_agent_job_done ( self , agent_addr , message : AgentJobDone ) : if agent_addr in self . _registered_agents : self . _logger . info ( "Job %s %s finished on agent %s" , message . job_id [ 0 ] , message . job_id [ 1 ] , agent_addr ) del self . _job_running [ message . job_id ] await ZMQUtils . send_with_...
Handle an AgentJobDone message . Send the data back to the client and start new job if needed
229,770
async def handle_agent_job_ssh_debug ( self , _ , message : AgentJobSSHDebug ) : await ZMQUtils . send_with_addr ( self . _client_socket , message . job_id [ 0 ] , BackendJobSSHDebug ( message . job_id [ 1 ] , message . host , message . port , message . password ) )
Handle an AgentJobSSHDebug message . Send the data back to the client
229,771
async def _do_ping ( self ) : for agent_addr , friendly_name in list ( self . _registered_agents . items ( ) ) : try : ping_count = self . _ping_count . get ( agent_addr , 0 ) if ping_count > 5 : self . _logger . warning ( "Agent %s (%s) does not respond: removing from list." , agent_addr , friendly_name ) delete_agent...
Ping the agents
229,772
async def _delete_agent ( self , agent_addr ) : self . _available_agents = [ agent for agent in self . _available_agents if agent != agent_addr ] del self . _registered_agents [ agent_addr ] await self . _recover_jobs ( agent_addr )
Deletes an agent
229,773
async def _recover_jobs ( self , agent_addr ) : for ( client_addr , job_id ) , ( agent , job_msg , _ ) in reversed ( list ( self . _job_running . items ( ) ) ) : if agent == agent_addr : await ZMQUtils . send_with_addr ( self . _client_socket , client_addr , BackendJobDone ( job_id , ( "crash" , "Agent restarted" ) , 0...
Recover the jobs sent to a crashed agent
229,774
def parse_date ( date , default = None ) : if date == "" : if default is not None : return default else : raise Exception ( "Unknown format for " + date ) for format_type in [ "%Y-%m-%d %H:%M:%S" , "%Y-%m-%d %H:%M" , "%Y-%m-%d %H" , "%Y-%m-%d" , "%d/%m/%Y %H:%M:%S" , "%d/%m/%Y %H:%M" , "%d/%m/%Y %H" , "%d/%m/%Y" ] : tr...
Parse a valid date
229,775
def GET ( self ) : if self . user_manager . session_logged_in ( ) or not self . app . allow_registration : raise web . notfound ( ) error = False reset = None msg = "" data = web . input ( ) if "activate" in data : msg , error = self . activate_user ( data ) elif "reset" in data : msg , error , reset = self . get_reset...
Handles GET request
229,776
def get_reset_data ( self , data ) : error = False reset = None msg = "" user = self . database . users . find_one ( { "reset" : data [ "reset" ] } ) if user is None : error = True msg = "Invalid reset hash." else : reset = { "hash" : data [ "reset" ] , "username" : user [ "username" ] , "realname" : user [ "realname" ...
Returns the user info to reset
229,777
def register_user ( self , data ) : error = False msg = "" email_re = re . compile ( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$' , re . IGNORECASE ) if r...
Parses input and register user
229,778
def lost_passwd ( self , data ) : error = False msg = "" email_re = re . compile ( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$' , re . IGNORECASE ) if ema...
Send a reset link to user to recover its password
229,779
def reset_passwd ( self , data ) : error = False msg = "" if len ( data [ "passwd" ] ) < 6 : error = True msg = _ ( "Password too short." ) elif data [ "passwd" ] != data [ "passwd2" ] : error = True msg = _ ( "Passwords don't match !" ) if not error : passwd_hash = hashlib . sha512 ( data [ "passwd" ] . encode ( "utf-...
Reset the user password
229,780
def POST ( self ) : if self . user_manager . session_logged_in ( ) or not self . app . allow_registration : raise web . notfound ( ) reset = None msg = "" error = False data = web . input ( ) if "register" in data : msg , error = self . register_user ( data ) elif "lostpasswd" in data : msg , error = self . lost_passwd...
Handles POST request
229,781
def get_readable_tasks ( self , course ) : course_fs = self . _filesystem . from_subfolder ( course . get_id ( ) ) tasks = [ task [ 0 : len ( task ) - 1 ] for task in course_fs . list ( folders = True , files = False , recursive = False ) if self . _task_file_exists ( course_fs . from_subfolder ( task ) ) ] return task...
Returns the list of all available tasks in a course
229,782
def _task_file_exists ( self , task_fs ) : for filename in [ "task.{}" . format ( ext ) for ext in self . get_available_task_file_extensions ( ) ] : if task_fs . exists ( filename ) : return True return False
Returns true if a task file exists in this directory
229,783
def delete_all_possible_task_files ( self , courseid , taskid ) : if not id_checker ( courseid ) : raise InvalidNameException ( "Course with invalid name: " + courseid ) if not id_checker ( taskid ) : raise InvalidNameException ( "Task with invalid name: " + taskid ) task_fs = self . get_task_fs ( courseid , taskid ) f...
Deletes all possibles task files in directory to allow to change the format
229,784
def prepare_request ( settings ) : settings [ "sp" ] [ "assertionConsumerService" ] = { "url" : web . ctx . homedomain + web . ctx . homepath + "/auth/callback/" + settings [ "id" ] , "binding" : "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" } data = web . input ( ) return { 'https' : 'on' if web . ctx . protocol ==...
Prepare SAML request
229,785
def _checkpath ( self , path ) : if path . startswith ( "/" ) or ".." in path or path . strip ( ) != path : raise NotFoundException ( )
Checks that a given path is valid . If it s not raises NotFoundException
229,786
def API_GET ( self , courseid = None ) : output = [ ] if courseid is None : courses = self . course_factory . get_all_courses ( ) else : try : courses = { courseid : self . course_factory . get_course ( courseid ) } except : raise APINotFound ( "Course not found" ) username = self . user_manager . session_username ( ) ...
List courses available to the connected client . Returns a dict in the form
229,787
def _api_convert_output ( return_value ) : content_type = web . ctx . environ . get ( 'CONTENT_TYPE' , 'text/json' ) if "text/json" in content_type : web . header ( 'Content-Type' , 'text/json; charset=utf-8' ) return json . dumps ( return_value ) if "text/html" in content_type : web . header ( 'Content-Type' , 'text/h...
Convert the output to what the client asks
229,788
def _handle_api ( self , handler , handler_args , handler_kwargs ) : try : status_code , return_value = handler ( * handler_args , ** handler_kwargs ) except APIError as error : return error . send ( ) web . ctx . status = _convert_http_status ( status_code ) return _api_convert_output ( return_value )
Handle call to subclasses and convert the output to an appropriate value
229,789
def _guess_available_methods ( self ) : available_methods = [ ] for m in [ "GET" , "POST" , "PUT" , "DELETE" , "PATCH" , "HEAD" , "OPTIONS" ] : self_method = getattr ( type ( self ) , "API_{}" . format ( m ) ) super_method = getattr ( APIPage , "API_{}" . format ( m ) ) if self_method != super_method : available_method...
Guess the method implemented by the subclass
229,790
def _verify_authentication ( self , handler , args , kwargs ) : if not self . user_manager . session_logged_in ( ) : raise APIForbidden ( ) return handler ( * args , ** kwargs )
Verify that the user is authenticated
229,791
def send ( self ) : web . ctx . status = _convert_http_status ( self . status_code ) return _api_convert_output ( self . return_value )
Send the API Exception to the client
229,792
def _job_done_callback ( self , submissionid , task , result , grade , problems , tests , custom , state , archive , stdout , stderr , newsub = True ) : submission = self . get_submission ( submissionid , False ) submission = self . get_input_from_submission ( submission ) data = { "status" : ( "done" if result [ 0 ] =...
Callback called by Client when a job is done . Updates the submission in the database with the data returned after the completion of the job
229,793
def _before_submission_insertion ( self , task , inputdata , debug , obj ) : username = self . _user_manager . session_username ( ) if task . is_group_task ( ) and not self . _user_manager . has_staff_rights_on_course ( task . get_course ( ) , username ) : group = self . _database . aggregations . find_one ( { "coursei...
Called before any new submission is inserted into the database . Allows you to modify obj the new document that will be inserted into the database . Should be overridden in subclasses .
229,794
def get_submission ( self , submissionid , user_check = True ) : sub = self . _database . submissions . find_one ( { '_id' : ObjectId ( submissionid ) } ) if user_check and not self . user_is_submission_owner ( sub ) : return None return sub
Get a submission from the database
229,795
def _delete_exceeding_submissions ( self , username , task , max_submissions_bound = - 1 ) : if max_submissions_bound <= 0 : max_submissions = task . get_stored_submissions ( ) elif task . get_stored_submissions ( ) <= 0 : max_submissions = max_submissions_bound else : max_submissions = min ( max_submissions_bound , ta...
Deletes exceeding submissions from the database to keep the database relatively small
229,796
def is_done ( self , submissionid_or_submission , user_check = True ) : if isinstance ( submissionid_or_submission , dict ) : submission = submissionid_or_submission else : submission = self . get_submission ( submissionid_or_submission , False ) if user_check and not self . user_is_submission_owner ( submission ) : re...
Tells if a submission is done and its result is available
229,797
def user_is_submission_owner ( self , submission ) : if not self . _user_manager . session_logged_in ( ) : raise Exception ( "A user must be logged in to verify if he owns a jobid" ) return self . _user_manager . session_username ( ) in submission [ "username" ]
Returns true if the current user is the owner of this jobid false else
229,798
def get_user_submissions ( self , task ) : if not self . _user_manager . session_logged_in ( ) : raise Exception ( "A user must be logged in to get his submissions" ) cursor = self . _database . submissions . find ( { "username" : self . _user_manager . session_username ( ) , "taskid" : task . get_id ( ) , "courseid" :...
Get all the user s submissions for a given task
229,799
def get_user_last_submissions ( self , limit = 5 , request = None ) : if request is None : request = { } request . update ( { "username" : self . _user_manager . session_username ( ) } ) data = self . _database . submissions . aggregate ( [ { "$match" : request } , { "$group" : { "_id" : { "courseid" : "$courseid" , "t...
Get last submissions of a user