id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
248,700
rigetti/quantumflow
quantumflow/channels.py
Kraus.evolve
def evolve(self, rho: Density) -> Density: """Apply the action of this Kraus quantum operation upon a 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, tensor...
python
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)
[ "def", "evolve", "(", "self", ",", "rho", ":", "Density", ")", "->", "Density", ":", "qubits", "=", "rho", ".", "qubits", "results", "=", "[", "op", ".", "evolve", "(", "rho", ")", "for", "op", "in", "self", ".", "operators", "]", "tensors", "=", ...
Apply the action of this Kraus quantum operation upon a density
[ "Apply", "the", "action", "of", "this", "Kraus", "quantum", "operation", "upon", "a", "density" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L79-L85
248,701
rigetti/quantumflow
quantumflow/channels.py
Kraus.H
def H(self) -> 'Kraus': """Return the complex conjugate of this Kraus operation""" operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
python
def H(self) -> 'Kraus': operators = [op.H for op in self.operators] return Kraus(operators, self.weights)
[ "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
[ "Return", "the", "complex", "conjugate", "of", "this", "Kraus", "operation" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L103-L106
248,702
rigetti/quantumflow
quantumflow/channels.py
UnitaryMixture.asgate
def asgate(self) -> Gate: """Return one of the composite Kraus operators at random with the appropriate weights""" return np.random.choice(self.operators, p=self.weights)
python
def asgate(self) -> Gate: return np.random.choice(self.operators, p=self.weights)
[ "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
[ "Return", "one", "of", "the", "composite", "Kraus", "operators", "at", "random", "with", "the", "appropriate", "weights" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L119-L122
248,703
rigetti/quantumflow
quantumflow/visualization.py
_display_layers
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
python
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, Cir...
[ "def", "_display_layers", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "qubit_idx", "=", "dict", "(", "zip", "(", "qubits", ",", "range", "(", "N", ")", ")", ")", "gate_l...
Separate a circuit into groups of gates that do not visually overlap
[ "Separate", "a", "circuit", "into", "groups", "of", "gates", "that", "do", "not", "visually", "overlap" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L235-L261
248,704
rigetti/quantumflow
quantumflow/visualization.py
render_latex
def render_latex(latex: str) -> PIL.Image: # pragma: no cover """ Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX...
python
def render_latex(latex: str) -> PIL.Image: # pragma: no cover 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(["...
[ "def", "render_latex", "(", "latex", ":", "str", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "tmpfilename", "=", "'circ'", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdirname", ":", "tmppath", "=", "os", ".", "path", "...
Convert a single page LaTeX document into an image. To display the returned image, `img.show()` Required external dependencies: `pdflatex` (with `qcircuit` package), and `poppler` (for `pdftocairo`). Args: A LaTeX document as a string. Returns: A PIL Image Raises: O...
[ "Convert", "a", "single", "page", "LaTeX", "document", "into", "an", "image", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L264-L305
248,705
rigetti/quantumflow
quantumflow/visualization.py
circuit_to_image
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
python
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover latex = circuit_to_latex(circ, qubits) img = render_latex(latex) return img
[ "def", "circuit_to_image", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "latex", "=", "circuit_to_latex", "(", "circ", ",", "qubits", ")", "img", "=", "render_latex", "("...
Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubit list to specify qubit order Returns: Returns: A PIL Image (Use img.show() to display) Raises: ...
[ "Create", "an", "image", "of", "a", "quantum", "circuit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L308-L327
248,706
rigetti/quantumflow
quantumflow/visualization.py
_latex_format
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
python
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)
[ "def", "_latex_format", "(", "obj", ":", "Any", ")", "->", "str", ":", "if", "isinstance", "(", "obj", ",", "float", ")", ":", "try", ":", "return", "sympy", ".", "latex", "(", "symbolize", "(", "obj", ")", ")", "except", "ValueError", ":", "return",...
Format an object as a latex string.
[ "Format", "an", "object", "as", "a", "latex", "string", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/visualization.py#L332-L340
248,707
rigetti/quantumflow
examples/eager_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'eager' tf = bk.TL tfe = bk.tfe steps = 4000 dev = '/gpu:0' if bk.DEVICE == '...
python
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(): """Loss""" gate =...
[ "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...
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "eager", "mode", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/eager_fit_gate.py#L21-L60
248,708
rigetti/quantumflow
quantumflow/meta.py
print_versions
def print_versions(file: typing.TextIO = None) -> None: """ Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout. """ print('** QuantumFlow dependencies (> python -m quantumflow.meta) **') print(...
python
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=file) print('networkx ...
[ "def", "print_versions", "(", "file", ":", "typing", ".", "TextIO", "=", "None", ")", "->", "None", ":", "print", "(", "'** QuantumFlow dependencies (> python -m quantumflow.meta) **'", ")", "print", "(", "'quantumflow \\t'", ",", "qf", ".", "__version__", ",", "f...
Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout.
[ "Print", "version", "strings", "of", "currently", "installed", "dependencies" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/meta.py#L21-L40
248,709
rigetti/quantumflow
examples/tensorflow_fit_gate.py
fit_zyz
def fit_zyz(target_gate): """ Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate. """ assert bk.BACKEND == 'tensorflow' tf = bk.TL steps = 4000 t = tf.get_variable('t', [3]) gate = qf.ZYZ(t[0], t[1],...
python
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.minimize(ang, var_list...
[ "def", "fit_zyz", "(", "target_gate", ")", ":", "assert", "bk", ".", "BACKEND", "==", "'tensorflow'", "tf", "=", "bk", ".", "TL", "steps", "=", "4000", "t", "=", "tf", ".", "get_variable", "(", "'t'", ",", "[", "3", "]", ")", "gate", "=", "qf", "...
Tensorflow example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
[ "Tensorflow", "example", ".", "Given", "an", "arbitrary", "one", "-", "qubit", "gate", "use", "gradient", "descent", "to", "find", "corresponding", "parameters", "of", "a", "universal", "ZYZ", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/tensorflow_fit_gate.py#L20-L50
248,710
rigetti/quantumflow
quantumflow/decompositions.py
zyz_decomposition
def zyz_decomposition(gate: Gate) -> Circuit: """ Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate. """ 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) # SU(2) if ab...
python
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) # SU(2) if abs(U[0, 0]) > abs(U[1, 0]): theta1 = 2 * np.arccos(min(abs(U[0, 0]), 1)) ...
[ "def", "zyz_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "if", "gate", ".", "qubit_nb", "!=", "1", ":", "raise", "ValueError", "(", "'Expected 1-qubit gate'", ")", "q", ",", "=", "gate", ".", "qubits", "U", "=", "asarray", "(", ...
Returns the Euler Z-Y-Z decomposition of a local 1-qubit gate.
[ "Returns", "the", "Euler", "Z", "-", "Y", "-", "Z", "decomposition", "of", "a", "local", "1", "-", "qubit", "gate", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L65-L108
248,711
rigetti/quantumflow
quantumflow/decompositions.py
kronecker_decomposition
def kronecker_decomposition(gate: Gate) -> Circuit: """ Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates. """ # An alternative approach would be t...
python
def kronecker_decomposition(gate: Gate) -> Circuit: # An alternative approach would be to take partial traces, but # this approach appears to be more robust. if gate.qubit_nb != 2: raise ValueError('Expected 2-qubit gate') U = asarray(gate.asoperator()) rank = 2**gate.qubit_nb U /= np....
[ "def", "kronecker_decomposition", "(", "gate", ":", "Gate", ")", "->", "Circuit", ":", "# An alternative approach would be to take partial traces, but", "# this approach appears to be more robust.", "if", "gate", ".", "qubit_nb", "!=", "2", ":", "raise", "ValueError", "(", ...
Decompose a 2-qubit unitary composed of two 1-qubit local gates. Uses the "Nearest Kronecker Product" algorithm. Will give erratic results if the gate is not the direct product of two 1-qubit gates.
[ "Decompose", "a", "2", "-", "qubit", "unitary", "composed", "of", "two", "1", "-", "qubit", "local", "gates", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L111-L150
248,712
rigetti/quantumflow
quantumflow/decompositions.py
canonical_coords
def canonical_coords(gate: Gate) -> Sequence[float]: """Returns the canonical coordinates of a 2-qubit gate""" circ = canonical_decomposition(gate) gate = circ.elements[6] # type: ignore params = [gate.params[key] for key in ('tx', 'ty', 'tz')] return params
python
def canonical_coords(gate: Gate) -> Sequence[float]: circ = canonical_decomposition(gate) gate = circ.elements[6] # type: ignore params = [gate.params[key] for key in ('tx', 'ty', 'tz')] return params
[ "def", "canonical_coords", "(", "gate", ":", "Gate", ")", "->", "Sequence", "[", "float", "]", ":", "circ", "=", "canonical_decomposition", "(", "gate", ")", "gate", "=", "circ", ".", "elements", "[", "6", "]", "# type: ignore", "params", "=", "[", "gate...
Returns the canonical coordinates of a 2-qubit gate
[ "Returns", "the", "canonical", "coordinates", "of", "a", "2", "-", "qubit", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L153-L158
248,713
rigetti/quantumflow
quantumflow/decompositions.py
_eig_complex_symmetric
def _eig_complex_symmetric(M: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors """ if not np.allclose(M, M.transpose()): raise np....
python
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') # The matrix of eigenvectors should be orthogonal. # But the standard 'eig' method will fail to return an orthogonal # eigenvec...
[ "def", "_eig_complex_symmetric", "(", "M", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "if", "not", "np", ".", "allclose", "(", "M", ",", "M", ".", "transpose", "(", ")", ")", ":"...
Diagonalize a complex symmetric matrix. The eigenvalues are complex, and the eigenvectors form an orthogonal matrix. Returns: eigenvalues, eigenvectors
[ "Diagonalize", "a", "complex", "symmetric", "matrix", ".", "The", "eigenvalues", "are", "complex", "and", "the", "eigenvectors", "form", "an", "orthogonal", "matrix", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L262-L309
248,714
rigetti/quantumflow
examples/qaoa_maxcut.py
maxcut_qaoa
def maxcut_qaoa( graph, steps=DEFAULT_STEPS, learning_rate=LEARNING_RATE, verbose=False): """QAOA Maxcut using tensorflow""" if not isinstance(graph, nx.Graph): graph = nx.from_edgelist(graph) init_scale = 0.01 init_bias = 0.5 init_beta = normal(loc=init_bi...
python
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]) ...
[ "def", "maxcut_qaoa", "(", "graph", ",", "steps", "=", "DEFAULT_STEPS", ",", "learning_rate", "=", "LEARNING_RATE", ",", "verbose", "=", "False", ")", ":", "if", "not", "isinstance", "(", "graph", ",", "nx", ".", "Graph", ")", ":", "graph", "=", "nx", ...
QAOA Maxcut using tensorflow
[ "QAOA", "Maxcut", "using", "tensorflow" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/qaoa_maxcut.py#L37-L87
248,715
rigetti/quantumflow
quantumflow/gates.py
identity_gate
def identity_gate(qubits: Union[int, Qubits]) -> Gate: """Returns the K-qubit identity gate""" _, qubits = qubits_count_tuple(qubits) return I(*qubits)
python
def identity_gate(qubits: Union[int, Qubits]) -> Gate: _, qubits = qubits_count_tuple(qubits) return I(*qubits)
[ "def", "identity_gate", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Gate", ":", "_", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "return", "I", "(", "*", "qubits", ")" ]
Returns the K-qubit identity gate
[ "Returns", "the", "K", "-", "qubit", "identity", "gate" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L57-L60
248,716
rigetti/quantumflow
quantumflow/gates.py
join_gates
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
python
def join_gates(*gates: Gate) -> Gate: vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
[ "def", "join_gates", "(", "*", "gates", ":", "Gate", ")", "->", "Gate", ":", "vectors", "=", "[", "gate", ".", "vec", "for", "gate", "in", "gates", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Gate", "(", "vec", ...
Direct product of two gates. Qubit count is the sum of each gate's bit count.
[ "Direct", "product", "of", "two", "gates", ".", "Qubit", "count", "is", "the", "sum", "of", "each", "gate", "s", "bit", "count", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L63-L68
248,717
rigetti/quantumflow
quantumflow/gates.py
control_gate
def control_gate(control: Qubit, gate: Gate) -> Gate: """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. """ if control in gate.qubits: raise ValueError('Gate and control qubits overlap') qubits = [control, *gate....
python
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 control...
[ "def", "control_gate", "(", "control", ":", "Qubit", ",", "gate", ":", "Gate", ")", "->", "Gate", ":", "if", "control", "in", "gate", ".", "qubits", ":", "raise", "ValueError", "(", "'Gate and control qubits overlap'", ")", "qubits", "=", "[", "control", "...
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.
[ "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", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L71-L83
248,718
rigetti/quantumflow
quantumflow/gates.py
conditional_gate
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: """Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1""" assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1...
python
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1).tensor gate = Gate(tensor=tensor, qubits=[control, *gate0.qubits]) return gate
[ "def", "conditional_gate", "(", "control", ":", "Qubit", ",", "gate0", ":", "Gate", ",", "gate1", ":", "Gate", ")", "->", "Gate", ":", "assert", "gate0", ".", "qubits", "==", "gate1", ".", "qubits", "# FIXME", "tensor", "=", "join_gates", "(", "P0", "(...
Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1
[ "Return", "a", "conditional", "unitary", "gate", ".", "Do", "gate0", "on", "bit", "1", "if", "bit", "0", "is", "zero", "else", "do", "gate1", "on", "1" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L86-L94
248,719
rigetti/quantumflow
quantumflow/gates.py
print_gate
def print_gate(gate: Gate, ndigits: int = 2, file: TextIO = None) -> None: """Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout """ N = gate.qubit_nb gate_tensor = gate.vec.asarray() lines = [] for index...
python
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 in r...
[ "def", "print_gate", "(", "gate", ":", "Gate", ",", "ndigits", ":", "int", "=", "2", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "N", "=", "gate", ".", "qubit_nb", "gate_tensor", "=", "gate", ".", "vec", ".", "asarray", "(", ...
Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout
[ "Pretty", "print", "a", "gate", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L116-L134
248,720
rigetti/quantumflow
quantumflow/gates.py
random_gate
def random_gate(qubits: Union[int, Qubits]) -> Gate: r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050 """ N, qubits = qubits_count_tuple(qubits) unitary = scipy.stats.unitary_g...
python
def random_gate(qubits: Union[int, Qubits]) -> Gate: r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050 """ N, qubits = qubits_count_tuple(qubits) unitary = scipy.stats.unitary_g...
[ "def", "random_gate", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Gate", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "unitary", "=", "scipy", ".", "stats", ".", "unitary_group", ".", "rvs", "(", ...
r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050
[ "r", "Returns", "a", "random", "unitary", "gate", "on", "K", "qubits", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L159-L168
248,721
VirusTotal/yara-python
setup.py
has_function
def has_function(function_name, libraries=None): """Checks if a given functions exists in the current platform.""" 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....
python
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
[ "def", "has_function", "(", "function_name", ",", "libraries", "=", "None", ")", ":", "compiler", "=", "distutils", ".", "ccompiler", ".", "new_compiler", "(", ")", "with", "muted", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ")", ":", "result"...
Checks if a given functions exists in the current platform.
[ "Checks", "if", "a", "given", "functions", "exists", "in", "the", "current", "platform", "." ]
c3992bdc3a95d42e9df249ae92e726b74737e859
https://github.com/VirusTotal/yara-python/blob/c3992bdc3a95d42e9df249ae92e726b74737e859/setup.py#L80-L88
248,722
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_message
async def handle_agent_message(self, agent_addr, message): """Dispatch messages received from agents to the right handlers""" message_handlers = { AgentHello: self.handle_agent_hello, AgentJobStarted: self.handle_agent_job_started, AgentJobDone: self.handle_agent_job_...
python
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, ...
[ "async", "def", "handle_agent_message", "(", "self", ",", "agent_addr", ",", "message", ")", ":", "message_handlers", "=", "{", "AgentHello", ":", "self", ".", "handle_agent_hello", ",", "AgentJobStarted", ":", "self", ".", "handle_agent_job_started", ",", "AgentJ...
Dispatch messages received from agents to the right handlers
[ "Dispatch", "messages", "received", "from", "agents", "to", "the", "right", "handlers" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L59-L72
248,723
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_hello
async def handle_client_hello(self, client_addr, _: ClientHello): """ Handle an ClientHello message. Send available containers to the client """ self._logger.info("New client connected %s", client_addr) self._registered_clients.add(client_addr) await self.send_container_update_to_client(...
python
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])
[ "async", "def", "handle_client_hello", "(", "self", ",", "client_addr", ",", "_", ":", "ClientHello", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"New client connected %s\"", ",", "client_addr", ")", "self", ".", "_registered_clients", ".", "add", "(...
Handle an ClientHello message. Send available containers to the client
[ "Handle", "an", "ClientHello", "message", ".", "Send", "available", "containers", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L103-L107
248,724
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_ping
async def handle_client_ping(self, client_addr, _: Ping): """ Handle an Ping message. Pong the client """ await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
python
async def handle_client_ping(self, client_addr, _: Ping): await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
[ "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
[ "Handle", "an", "Ping", "message", ".", "Pong", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L109-L111
248,725
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_new_job
async def handle_client_new_job(self, client_addr, message: ClientNewJob): """ Handle an ClientNewJob message. Add a job to the queue and triggers an update """ 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)]...
python
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()
[ "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", ")", ...
Handle an ClientNewJob message. Add a job to the queue and triggers an update
[ "Handle", "an", "ClientNewJob", "message", ".", "Add", "a", "job", "to", "the", "queue", "and", "triggers", "an", "update" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L113-L117
248,726
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_kill_job
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): """ Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """ # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: ...
python
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: del self._waiting_jobs[(client_addr, message.job_id)] # Do not forget to send a JobDone await ZM...
[ "async", "def", "handle_client_kill_job", "(", "self", ",", "client_addr", ",", "message", ":", "ClientKillJob", ")", ":", "# Check if the job is not in the queue", "if", "(", "client_addr", ",", "message", ".", "job_id", ")", "in", "self", ".", "_waiting_jobs", "...
Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent.
[ "Handle", "an", "ClientKillJob", "message", ".", "Remove", "a", "job", "from", "the", "waiting", "list", "or", "send", "the", "kill", "message", "to", "the", "right", "agent", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L119-L132
248,727
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_get_queue
async def handle_client_get_queue(self, client_addr, _: ClientGetQueue): """ Handles a ClientGetQueue message. Send back info about the job queue""" #jobs_running: a list of tuples in the form #(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end) jobs_running ...
python
async def handle_client_get_queue(self, client_addr, _: ClientGetQueue): #jobs_running: a list of tuples in the form #(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end) jobs_running = list() for backend_job_id, content in self._job_running.items(): ...
[ "async", "def", "handle_client_get_queue", "(", "self", ",", "client_addr", ",", "_", ":", "ClientGetQueue", ")", ":", "#jobs_running: a list of tuples in the form", "#(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end)", "jobs_running", "=", "list", ...
Handles a ClientGetQueue message. Send back info about the job queue
[ "Handles", "a", "ClientGetQueue", "message", ".", "Send", "back", "info", "about", "the", "job", "queue" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L134-L154
248,728
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.update_queue
async def update_queue(self): """ Send waiting jobs to available agents """ # For now, round-robin not_found_for_agent = [] while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0: agent_addr = self._available_agents.pop(0) # Find ...
python
async def update_queue(self): # For now, round-robin not_found_for_agent = [] while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0: agent_addr = self._available_agents.pop(0) # Find first job that can be run on this agent found = False ...
[ "async", "def", "update_queue", "(", "self", ")", ":", "# For now, round-robin", "not_found_for_agent", "=", "[", "]", "while", "len", "(", "self", ".", "_available_agents", ")", ">", "0", "and", "len", "(", "self", ".", "_waiting_jobs", ")", ">", "0", ":"...
Send waiting jobs to available agents
[ "Send", "waiting", "jobs", "to", "available", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L156-L193
248,729
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_hello
async def handle_agent_hello(self, agent_addr, message: AgentHello): """ Handle an AgentAvailable message. Add agent_addr to the list of available agents """ self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name) if agent_addr in self._registered_agents...
python
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: # Delete previous instance of this agent, if any await self._delete_agent(agent_addr) ...
[ "async", "def", "handle_agent_hello", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentHello", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Agent %s (%s) said hello\"", ",", "agent_addr", ",", "message", ".", "friendly_name", ")", "if", "ag...
Handle an AgentAvailable message. Add agent_addr to the list of available agents
[ "Handle", "an", "AgentAvailable", "message", ".", "Add", "agent_addr", "to", "the", "list", "of", "available", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L195-L248
248,730
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_started
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted): """Handle an AgentJobStarted message. Send the data back to the client""" 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._clie...
python
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.job_id[1]))
[ "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", "]", ",", "me...
Handle an AgentJobStarted message. Send the data back to the client
[ "Handle", "an", "AgentJobStarted", "message", ".", "Send", "the", "data", "back", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L250-L253
248,731
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_done
async def handle_agent_job_done(self, agent_addr, message: AgentJobDone): """Handle an AgentJobDone message. Send the data back to the client, and start new job if needed""" if agent_addr in self._registered_agents: self._logger.info("Job %s %s finished on agent %s", message.job_id[0], mess...
python
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) # Remove the job from the list of running jobs del self._...
[ "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\""...
Handle an AgentJobDone message. Send the data back to the client, and start new job if needed
[ "Handle", "an", "AgentJobDone", "message", ".", "Send", "the", "data", "back", "to", "the", "client", "and", "start", "new", "job", "if", "needed" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L255-L277
248,732
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_ssh_debug
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): """Handle an AgentJobSSHDebug message. Send the data back to the client""" await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, ...
python
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, messa...
[ "async", "def", "handle_agent_job_ssh_debug", "(", "self", ",", "_", ",", "message", ":", "AgentJobSSHDebug", ")", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "message", ".", "job_id", "[", "0", "]", ",", "Backen...
Handle an AgentJobSSHDebug message. Send the data back to the client
[ "Handle", "an", "AgentJobSSHDebug", "message", ".", "Send", "the", "data", "back", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L279-L282
248,733
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._do_ping
async def _do_ping(self): """ Ping the agents """ # the list() call here is needed, as we remove entries from _registered_agents! for agent_addr, friendly_name in list(self._registered_agents.items()): try: ping_count = self._ping_count.get(agent_addr, 0) ...
python
async def _do_ping(self): # the list() call here is needed, as we remove entries from _registered_agents! 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: ...
[ "async", "def", "_do_ping", "(", "self", ")", ":", "# the list() call here is needed, as we remove entries from _registered_agents!", "for", "agent_addr", ",", "friendly_name", "in", "list", "(", "self", ".", "_registered_agents", ".", "items", "(", ")", ")", ":", "tr...
Ping the agents
[ "Ping", "the", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L314-L339
248,734
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._delete_agent
async def _delete_agent(self, agent_addr): """ Deletes an agent """ 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)
python
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)
[ "async", "def", "_delete_agent", "(", "self", ",", "agent_addr", ")", ":", "self", ".", "_available_agents", "=", "[", "agent", "for", "agent", "in", "self", ".", "_available_agents", "if", "agent", "!=", "agent_addr", "]", "del", "self", ".", "_registered_a...
Deletes an agent
[ "Deletes", "an", "agent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L341-L345
248,735
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._recover_jobs
async def _recover_jobs(self, agent_addr): """ Recover the jobs sent to a crashed agent """ 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, ...
python
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...
[ "async", "def", "_recover_jobs", "(", "self", ",", "agent_addr", ")", ":", "for", "(", "client_addr", ",", "job_id", ")", ",", "(", "agent", ",", "job_msg", ",", "_", ")", "in", "reversed", "(", "list", "(", "self", ".", "_job_running", ".", "items", ...
Recover the jobs sent to a crashed agent
[ "Recover", "the", "jobs", "sent", "to", "a", "crashed", "agent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L347-L356
248,736
UCL-INGI/INGInious
inginious/frontend/accessible_time.py
parse_date
def parse_date(date, default=None): """ Parse a valid date """ 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...
python
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/...
[ "def", "parse_date", "(", "date", ",", "default", "=", "None", ")", ":", "if", "date", "==", "\"\"", ":", "if", "default", "is", "not", "None", ":", "return", "default", "else", ":", "raise", "Exception", "(", "\"Unknown format for \"", "+", "date", ")",...
Parse a valid date
[ "Parse", "a", "valid", "date" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/accessible_time.py#L11-L25
248,737
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.GET
def GET(self): """ Handles GET request """ 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.a...
python
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 "res...
[ "def", "GET", "(", "self", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", "or", "not", "self", ".", "app", ".", "allow_registration", ":", "raise", "web", ".", "notfound", "(", ")", "error", "=", "False", "reset", "=",...
Handles GET request
[ "Handles", "GET", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L20-L35
248,738
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.get_reset_data
def get_reset_data(self, data): """ Returns the user info to reset """ 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: ...
python
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"...
[ "def", "get_reset_data", "(", "self", ",", "data", ")", ":", "error", "=", "False", "reset", "=", "None", "msg", "=", "\"\"", "user", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"reset\"", ":", "data", "[", "\"reset\"", "...
Returns the user info to reset
[ "Returns", "the", "user", "info", "to", "reset" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L37-L49
248,739
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.register_user
def register_user(self, data): """ Parses input and register user """ error = False msg = "" email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\0...
python
def register_user(self, data): error = False msg = "" email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(...
[ "def", "register_user", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "email_re", "=", "re", ".", "compile", "(", "r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"", "# dot-atom", "r'|^\"([\\001-\\010\\013\\014\\016-\\...
Parses input and register user
[ "Parses", "input", "and", "register", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L63-L117
248,740
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.lost_passwd
def lost_passwd(self, data): """ Send a reset link to user to recover its password """ error = False msg = "" # Check input format email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\0...
python
def lost_passwd(self, data): error = False msg = "" # Check input format email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quot...
[ "def", "lost_passwd", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "# Check input format", "email_re", "=", "re", ".", "compile", "(", "r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"", "# dot-atom", "r'|^\"([\\001...
Send a reset link to user to recover its password
[ "Send", "a", "reset", "link", "to", "user", "to", "recover", "its", "password" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L119-L151
248,741
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.reset_passwd
def reset_passwd(self, data): """ Reset the user password """ error = False msg = "" # Check input format if len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True ...
python
def reset_passwd(self, data): error = False msg = "" # Check input format if len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True msg = _("Passwords don't match !...
[ "def", "reset_passwd", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "# Check input format", "if", "len", "(", "data", "[", "\"passwd\"", "]", ")", "<", "6", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Passwor...
Reset the user password
[ "Reset", "the", "user", "password" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L153-L177
248,742
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.POST
def POST(self): """ Handles POST request """ 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....
python
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 "los...
[ "def", "POST", "(", "self", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", "or", "not", "self", ".", "app", ".", "allow_registration", ":", "raise", "web", ".", "notfound", "(", ")", "reset", "=", "None", "msg", "=", ...
Handles POST request
[ "Handles", "POST", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L179-L199
248,743
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory.get_readable_tasks
def get_readable_tasks(self, course): """ Returns the list of all available tasks in a course """ course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursiv...
python
def get_readable_tasks(self, course): course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursive=False) if self._task_file_exists(course_fs.from_subfol...
[ "def", "get_readable_tasks", "(", "self", ",", "course", ")", ":", "course_fs", "=", "self", ".", "_filesystem", ".", "from_subfolder", "(", "course", ".", "get_id", "(", ")", ")", "tasks", "=", "[", "task", "[", "0", ":", "len", "(", "task", ")", "-...
Returns the list of all available tasks in a course
[ "Returns", "the", "list", "of", "all", "available", "tasks", "in", "a", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L122-L129
248,744
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory._task_file_exists
def _task_file_exists(self, task_fs): """ Returns true if a task file exists in this directory """ for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]: if task_fs.exists(filename): return True return False
python
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
[ "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", ".",...
Returns true if a task file exists in this directory
[ "Returns", "true", "if", "a", "task", "file", "exists", "in", "this", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L131-L136
248,745
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory.delete_all_possible_task_files
def delete_all_possible_task_files(self, courseid, taskid): """ Deletes all possibles task files in directory, to allow to change the format """ if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) if not id_checker(taskid): rai...
python
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_...
[ "def", "delete_all_possible_task_files", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "if", "not", "id_checker", "(", "courseid", ")", ":", "raise", "InvalidNameException", "(", "\"Course with invalid name: \"", "+", "courseid", ")", "if", "not", "id_che...
Deletes all possibles task files in directory, to allow to change the format
[ "Deletes", "all", "possibles", "task", "files", "in", "directory", "to", "allow", "to", "change", "the", "format" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L138-L149
248,746
UCL-INGI/INGInious
inginious/frontend/plugins/auth/saml2_auth.py
prepare_request
def prepare_request(settings): """ Prepare SAML request """ # Set the ACS url and binding method 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" ...
python
def prepare_request(settings): # Set the ACS url and binding method 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" } # If server is behind proxy...
[ "def", "prepare_request", "(", "settings", ")", ":", "# Set the ACS url and binding method", "settings", "[", "\"sp\"", "]", "[", "\"assertionConsumerService\"", "]", "=", "{", "\"url\"", ":", "web", ".", "ctx", ".", "homedomain", "+", "web", ".", "ctx", ".", ...
Prepare SAML request
[ "Prepare", "SAML", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/saml2_auth.py#L98-L119
248,747
UCL-INGI/INGInious
inginious/common/filesystems/provider.py
FileSystemProvider._checkpath
def _checkpath(self, path): """ Checks that a given path is valid. If it's not, raises NotFoundException """ if path.startswith("/") or ".." in path or path.strip() != path: raise NotFoundException()
python
def _checkpath(self, path): if path.startswith("/") or ".." in path or path.strip() != path: raise NotFoundException()
[ "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
[ "Checks", "that", "a", "given", "path", "is", "valid", ".", "If", "it", "s", "not", "raises", "NotFoundException" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/provider.py#L41-L44
248,748
UCL-INGI/INGInious
inginious/frontend/pages/api/courses.py
APICourses.API_GET
def API_GET(self, courseid=None): # pylint: disable=arguments-differ """ List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #th...
python
def API_GET(self, courseid=None): # pylint: disable=arguments-differ output = [] if courseid is None: courses = self.course_factory.get_all_courses() else: try: courses = {courseid: self.course_factory.get_course(courseid)} except: ...
[ "def", "API_GET", "(", "self", ",", "courseid", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "output", "=", "[", "]", "if", "courseid", "is", "None", ":", "courses", "=", "self", ".", "course_factory", ".", "get_all_courses", "(", ")", "else"...
List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if t...
[ "List", "courses", "available", "to", "the", "connected", "client", ".", "Returns", "a", "dict", "in", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/courses.py#L16-L67
248,749
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
_api_convert_output
def _api_convert_output(return_value): """ Convert the output to what the client asks """ 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"...
python
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', 't...
[ "def", "_api_convert_output", "(", "return_value", ")", ":", "content_type", "=", "web", ".", "ctx", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "'text/json'", ")", "if", "\"text/json\"", "in", "content_type", ":", "web", ".", "header", "(", "'Co...
Convert the output to what the client asks
[ "Convert", "the", "output", "to", "what", "the", "client", "asks" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L163-L182
248,750
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIPage._handle_api
def _handle_api(self, handler, handler_args, handler_kwargs): """ Handle call to subclasses and convert the output to an appropriate value """ try: status_code, return_value = handler(*handler_args, **handler_kwargs) except APIError as error: return error.send() ...
python
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(ret...
[ "def", "_handle_api", "(", "self", ",", "handler", ",", "handler_args", ",", "handler_kwargs", ")", ":", "try", ":", "status_code", ",", "return_value", "=", "handler", "(", "*", "handler_args", ",", "*", "*", "handler_kwargs", ")", "except", "APIError", "as...
Handle call to subclasses and convert the output to an appropriate value
[ "Handle", "call", "to", "subclasses", "and", "convert", "the", "output", "to", "an", "appropriate", "value" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L47-L55
248,751
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIPage._guess_available_methods
def _guess_available_methods(self): """ Guess the method implemented by the subclass""" 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...
python
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: ...
[ "def", "_guess_available_methods", "(", "self", ")", ":", "available_methods", "=", "[", "]", "for", "m", "in", "[", "\"GET\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ",", "\"PATCH\"", ",", "\"HEAD\"", ",", "\"OPTIONS\"", "]", ":", "self_method"...
Guess the method implemented by the subclass
[ "Guess", "the", "method", "implemented", "by", "the", "subclass" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L57-L65
248,752
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIAuthenticatedPage._verify_authentication
def _verify_authentication(self, handler, args, kwargs): """ Verify that the user is authenticated """ if not self.user_manager.session_logged_in(): raise APIForbidden() return handler(*args, **kwargs)
python
def _verify_authentication(self, handler, args, kwargs): if not self.user_manager.session_logged_in(): raise APIForbidden() return handler(*args, **kwargs)
[ "def", "_verify_authentication", "(", "self", ",", "handler", ",", "args", ",", "kwargs", ")", ":", "if", "not", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "APIForbidden", "(", ")", "return", "handler", "(", "*", "args",...
Verify that the user is authenticated
[ "Verify", "that", "the", "user", "is", "authenticated" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L109-L113
248,753
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIError.send
def send(self): """ Send the API Exception to the client """ web.ctx.status = _convert_http_status(self.status_code) return _api_convert_output(self.return_value)
python
def send(self): web.ctx.status = _convert_http_status(self.status_code) return _api_convert_output(self.return_value)
[ "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
[ "Send", "the", "API", "Exception", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L124-L127
248,754
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._job_done_callback
def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True): """ 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 """ submission = ...
python
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...
[ "def", "_job_done_callback", "(", "self", ",", "submissionid", ",", "task", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "state", ",", "archive", ",", "stdout", ",", "stderr", ",", "newsub", "=", "True", ")", ":", "su...
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
[ "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" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L46-L93
248,755
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._before_submission_insertion
def _before_submission_insertion(self, task, inputdata, debug, obj): """ 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. :param task: Task related to t...
python
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( {"c...
[ "def", "_before_submission_insertion", "(", "self", ",", "task", ",", "inputdata", ",", "debug", ",", "obj", ")", ":", "username", "=", "self", ".", "_user_manager", ".", "session_username", "(", ")", "if", "task", ".", "is_group_task", "(", ")", "and", "n...
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. :param task: Task related to the submission :param inputdata: input of the student :param debug: True, ...
[ "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"...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L95-L129
248,756
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_submission
def get_submission(self, submissionid, user_check=True): """ Get a submission from the database """ sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)}) if user_check and not self.user_is_submission_owner(sub): return None return sub
python
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
[ "def", "get_submission", "(", "self", ",", "submissionid", ",", "user_check", "=", "True", ")", ":", "sub", "=", "self", ".", "_database", ".", "submissions", ".", "find_one", "(", "{", "'_id'", ":", "ObjectId", "(", "submissionid", ")", "}", ")", "if", ...
Get a submission from the database
[ "Get", "a", "submission", "from", "the", "database" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L208-L213
248,757
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._delete_exceeding_submissions
def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1): """ Deletes exceeding submissions from the database, to keep the database relatively small """ if max_submissions_bound <= 0: max_submissions = task.get_stored_submissions() elif task.get_stored_submi...
python
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_submiss...
[ "def", "_delete_exceeding_submissions", "(", "self", ",", "username", ",", "task", ",", "max_submissions_bound", "=", "-", "1", ")", ":", "if", "max_submissions_bound", "<=", "0", ":", "max_submissions", "=", "task", ".", "get_stored_submissions", "(", ")", "eli...
Deletes exceeding submissions from the database, to keep the database relatively small
[ "Deletes", "exceeding", "submissions", "from", "the", "database", "to", "keep", "the", "database", "relatively", "small" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L284-L337
248,758
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.is_done
def is_done(self, submissionid_or_submission, user_check=True): """ Tells if a submission is done and its result is available """ # TODO: not a very nice way to avoid too many database call. Should be refactored. if isinstance(submissionid_or_submission, dict): submission = submissio...
python
def is_done(self, submissionid_or_submission, user_check=True): # TODO: not a very nice way to avoid too many database call. Should be refactored. if isinstance(submissionid_or_submission, dict): submission = submissionid_or_submission else: submission = self.get_submissi...
[ "def", "is_done", "(", "self", ",", "submissionid_or_submission", ",", "user_check", "=", "True", ")", ":", "# TODO: not a very nice way to avoid too many database call. Should be refactored.", "if", "isinstance", "(", "submissionid_or_submission", ",", "dict", ")", ":", "s...
Tells if a submission is done and its result is available
[ "Tells", "if", "a", "submission", "is", "done", "and", "its", "result", "is", "available" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L379-L388
248,759
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.user_is_submission_owner
def user_is_submission_owner(self, submission): """ Returns true if the current user is the owner of this jobid, false else """ 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_u...
python
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"]
[ "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", "sel...
Returns true if the current user is the owner of this jobid, false else
[ "Returns", "true", "if", "the", "current", "user", "is", "the", "owner", "of", "this", "jobid", "false", "else" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L404-L409
248,760
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_user_submissions
def get_user_submissions(self, task): """ Get all the user's submissions for a given 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.se...
python
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(), ...
[ "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", "."...
Get all the user's submissions for a given task
[ "Get", "all", "the", "user", "s", "submissions", "for", "a", "given", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L411-L419
248,761
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_user_last_submissions
def get_user_last_submissions(self, limit=5, request=None): """ Get last submissions of a user """ if request is None: request = {} request.update({"username": self._user_manager.session_username()}) # Before, submissions were first sorted by submission date, then grouped ...
python
def get_user_last_submissions(self, limit=5, request=None): if request is None: request = {} request.update({"username": self._user_manager.session_username()}) # Before, submissions were first sorted by submission date, then grouped # and then resorted by submission date b...
[ "def", "get_user_last_submissions", "(", "self", ",", "limit", "=", "5", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "{", "}", "request", ".", "update", "(", "{", "\"username\"", ":", "self", ".", "_user_m...
Get last submissions of a user
[ "Get", "last", "submissions", "of", "a", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L421-L465
248,762
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._handle_ssh_callback
def _handle_ssh_callback(self, submission_id, host, port, password): """ Handles the creation of a remote ssh server """ if host is not None: # ignore late calls (a bit hacky, but...) obj = { "ssh_host": host, "ssh_port": port, "ssh_password":...
python
def _handle_ssh_callback(self, submission_id, host, port, password): if host is not None: # ignore late calls (a bit hacky, but...) obj = { "ssh_host": host, "ssh_port": port, "ssh_password": password } self._database.submissio...
[ "def", "_handle_ssh_callback", "(", "self", ",", "submission_id", ",", "host", ",", "port", ",", "password", ")", ":", "if", "host", "is", "not", "None", ":", "# ignore late calls (a bit hacky, but...)", "obj", "=", "{", "\"ssh_host\"", ":", "host", ",", "\"ss...
Handles the creation of a remote ssh server
[ "Handles", "the", "creation", "of", "a", "remote", "ssh", "server" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L569-L577
248,763
UCL-INGI/INGInious
inginious/common/entrypoints.py
filesystem_from_config_dict
def filesystem_from_config_dict(config_fs): """ Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error. """ if "module" not in config_fs: print("Key 'module' should be defined for the fil...
python
def filesystem_from_config_dict(config_fs): if "module" not in config_fs: print("Key 'module' should be defined for the filesystem provider ('fs' configuration option)", file=sys.stderr) exit(1) filesystem_providers = get_filesystems_providers() if config_fs["module"] not in filesystem_prov...
[ "def", "filesystem_from_config_dict", "(", "config_fs", ")", ":", "if", "\"module\"", "not", "in", "config_fs", ":", "print", "(", "\"Key 'module' should be defined for the filesystem provider ('fs' configuration option)\"", ",", "file", "=", "sys", ".", "stderr", ")", "e...
Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error.
[ "Given", "a", "dict", "containing", "an", "entry", "module", "which", "contains", "a", "FSProvider", "identifier", "parse", "the", "configuration", "and", "returns", "a", "fs_provider", ".", "Exits", "if", "there", "is", "an", "error", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/entrypoints.py#L20-L48
248,764
UCL-INGI/INGInious
inginious/agent/docker_agent/_timeout_watcher.py
TimeoutWatcher._kill_it_with_fire
async def _kill_it_with_fire(self, container_id): """ Kill a container, with fire. """ if container_id in self._watching: self._watching.remove(container_id) self._container_had_error.add(container_id) try: await self._docker_interface....
python
async def _kill_it_with_fire(self, container_id): if container_id in self._watching: self._watching.remove(container_id) self._container_had_error.add(container_id) try: await self._docker_interface.kill_container(container_id) except: ...
[ "async", "def", "_kill_it_with_fire", "(", "self", ",", "container_id", ")", ":", "if", "container_id", "in", "self", ".", "_watching", ":", "self", ".", "_watching", ".", "remove", "(", "container_id", ")", "self", ".", "_container_had_error", ".", "add", "...
Kill a container, with fire.
[ "Kill", "a", "container", "with", "fire", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/_timeout_watcher.py#L95-L105
248,765
UCL-INGI/INGInious
inginious/frontend/cookieless_app.py
CookieLessCompatibleSession._cleanup
def _cleanup(self): """Cleanup the stored sessions""" current_time = time.time() timeout = self._config.timeout if current_time - self._last_cleanup_time > timeout: self.store.cleanup(timeout) self._last_cleanup_time = current_time
python
def _cleanup(self): current_time = time.time() timeout = self._config.timeout if current_time - self._last_cleanup_time > timeout: self.store.cleanup(timeout) self._last_cleanup_time = current_time
[ "def", "_cleanup", "(", "self", ")", ":", "current_time", "=", "time", ".", "time", "(", ")", "timeout", "=", "self", ".", "_config", ".", "timeout", "if", "current_time", "-", "self", ".", "_last_cleanup_time", ">", "timeout", ":", "self", ".", "store",...
Cleanup the stored sessions
[ "Cleanup", "the", "stored", "sessions" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/cookieless_app.py#L255-L261
248,766
UCL-INGI/INGInious
inginious/frontend/cookieless_app.py
CookieLessCompatibleSession.expired
def expired(self): """Called when an expired session is atime""" self._data["_killed"] = True self.save() raise SessionExpired(self._config.expired_message)
python
def expired(self): self._data["_killed"] = True self.save() raise SessionExpired(self._config.expired_message)
[ "def", "expired", "(", "self", ")", ":", "self", ".", "_data", "[", "\"_killed\"", "]", "=", "True", "self", ".", "save", "(", ")", "raise", "SessionExpired", "(", "self", ".", "_config", ".", "expired_message", ")" ]
Called when an expired session is atime
[ "Called", "when", "an", "expired", "session", "is", "atime" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/cookieless_app.py#L263-L267
248,767
UCL-INGI/INGInious
inginious/frontend/pages/preferences/delete.py
DeletePage.delete_account
def delete_account(self, data): """ Delete account from DB """ error = False msg = "" username = self.user_manager.session_username() # Check input format result = self.database.users.find_one_and_delete({"username": username, ...
python
def delete_account(self, data): error = False msg = "" username = self.user_manager.session_username() # Check input format result = self.database.users.find_one_and_delete({"username": username, "email": data.get("delet...
[ "def", "delete_account", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "# Check input format", "result", "=", "self", ".", "database", ".", "u...
Delete account from DB
[ "Delete", "account", "from", "DB" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/preferences/delete.py#L15-L41
248,768
UCL-INGI/INGInious
inginious/common/custom_yaml.py
dump
def dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. Dict keys are produced in the order in which they appear in OrderedDicts. Safe version. If objects are not "conventional" objects, t...
python
def dump(data, stream=None, **kwds): # Display OrderedDicts correctly class OrderedDumper(SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, list(data.items())) # Displ...
[ "def", "dump", "(", "data", ",", "stream", "=", "None", ",", "*", "*", "kwds", ")", ":", "# Display OrderedDicts correctly", "class", "OrderedDumper", "(", "SafeDumper", ")", ":", "pass", "def", "_dict_representer", "(", "dumper", ",", "data", ")", ":", "r...
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. Dict keys are produced in the order in which they appear in OrderedDicts. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str()...
[ "Serialize", "a", "Python", "object", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", ".", "Dict", "keys", "are", "produced", "in", "the", "order", "in", "which", "they", "appear", "in", ...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/custom_yaml.py#L40-L87
248,769
UCL-INGI/INGInious
inginious/frontend/pages/api/tasks.py
APITasks._check_for_parsable_text
def _check_for_parsable_text(self, val): """ Util to remove parsable text from a dict, recursively """ if isinstance(val, ParsableText): return val.original_content() if isinstance(val, list): for key, val2 in enumerate(val): val[key] = self._check_for_par...
python
def _check_for_parsable_text(self, val): if isinstance(val, ParsableText): return val.original_content() if isinstance(val, list): for key, val2 in enumerate(val): val[key] = self._check_for_parsable_text(val2) return val if isinstance(val, dic...
[ "def", "_check_for_parsable_text", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "ParsableText", ")", ":", "return", "val", ".", "original_content", "(", ")", "if", "isinstance", "(", "val", ",", "list", ")", ":", "for", "key", ...
Util to remove parsable text from a dict, recursively
[ "Util", "to", "remove", "parsable", "text", "from", "a", "dict", "recursively" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L17-L28
248,770
UCL-INGI/INGInious
inginious/frontend/pages/api/tasks.py
APITasks.API_GET
def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ """ List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", ...
python
def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ try: course = self.course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not self.user_manager.course_is_open_to_user(course, lti=False): raise APIFor...
[ "def", "API_GET", "(", "self", ",", "courseid", ",", "taskid", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "except", ":", "raise", "APINotFound"...
List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": ""...
[ "List", "tasks", "available", "to", "the", "connected", "client", ".", "Returns", "a", "dict", "in", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L30-L103
248,771
UCL-INGI/INGInious
base-containers/base/inginious/input.py
load_input
def load_input(): """ Open existing input file """ file = open(_input_file, 'r') result = json.loads(file.read().strip('\0').strip()) file.close() return result
python
def load_input(): file = open(_input_file, 'r') result = json.loads(file.read().strip('\0').strip()) file.close() return result
[ "def", "load_input", "(", ")", ":", "file", "=", "open", "(", "_input_file", ",", "'r'", ")", "result", "=", "json", ".", "loads", "(", "file", ".", "read", "(", ")", ".", "strip", "(", "'\\0'", ")", ".", "strip", "(", ")", ")", "file", ".", "c...
Open existing input file
[ "Open", "existing", "input", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/input.py#L14-L19
248,772
UCL-INGI/INGInious
base-containers/base/inginious/input.py
parse_template
def parse_template(input_filename, output_filename=''): """ Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file """ ...
python
def parse_template(input_filename, output_filename=''): data = load_input() with open(input_filename, 'rb') as file: template = file.read().decode("utf-8") # Check if 'input' in data if not 'input' in data: raise ValueError("Could not find 'input' in data") # Parse template...
[ "def", "parse_template", "(", "input_filename", ",", "output_filename", "=", "''", ")", ":", "data", "=", "load_input", "(", ")", "with", "open", "(", "input_filename", ",", "'rb'", ")", "as", "file", ":", "template", "=", "file", ".", "read", "(", ")", ...
Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file
[ "Parses", "a", "template", "file", "Replaces", "all", "occurences", "of" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/input.py#L49-L92
248,773
UCL-INGI/INGInious
inginious/client/client.py
_callable_once
def _callable_once(func): """ Returns a function that is only callable once; any other call will do nothing """ def once(*args, **kwargs): if not once.called: once.called = True return func(*args, **kwargs) once.called = False return once
python
def _callable_once(func): def once(*args, **kwargs): if not once.called: once.called = True return func(*args, **kwargs) once.called = False return once
[ "def", "_callable_once", "(", "func", ")", ":", "def", "once", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "once", ".", "called", ":", "once", ".", "called", "=", "True", "return", "func", "(", "*", "args", ",", "*", "*", ...
Returns a function that is only callable once; any other call will do nothing
[ "Returns", "a", "function", "that", "is", "only", "callable", "once", ";", "any", "other", "call", "will", "do", "nothing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L17-L26
248,774
UCL-INGI/INGInious
inginious/client/client.py
Client._ask_queue_update
async def _ask_queue_update(self): """ Send a ClientGetQueue message to the backend, if one is not already sent """ try: while True: await asyncio.sleep(self._queue_update_timer) if self._queue_update_last_attempt == 0 or self._queue_update_last_attempt > self...
python
async def _ask_queue_update(self): try: while True: await asyncio.sleep(self._queue_update_timer) if self._queue_update_last_attempt == 0 or self._queue_update_last_attempt > self._queue_update_last_attempt_max: if self._queue_update_last_attempt: ...
[ "async", "def", "_ask_queue_update", "(", "self", ")", ":", "try", ":", "while", "True", ":", "await", "asyncio", ".", "sleep", "(", "self", ".", "_queue_update_timer", ")", "if", "self", ".", "_queue_update_last_attempt", "==", "0", "or", "self", ".", "_q...
Send a ClientGetQueue message to the backend, if one is not already sent
[ "Send", "a", "ClientGetQueue", "message", "to", "the", "backend", "if", "one", "is", "not", "already", "sent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L144-L162
248,775
UCL-INGI/INGInious
inginious/client/client.py
Client._handle_job_queue_update
async def _handle_job_queue_update(self, message: BackendGetQueue): """ Handles a BackendGetQueue containing a snapshot of the job queue """ self._logger.debug("Received job queue update") self._queue_update_last_attempt = 0 self._queue_cache = message # Do some precomputation ...
python
async def _handle_job_queue_update(self, message: BackendGetQueue): self._logger.debug("Received job queue update") self._queue_update_last_attempt = 0 self._queue_cache = message # Do some precomputation new_job_queue_cache = {} # format is job_id: (nb_jobs_before, max_...
[ "async", "def", "_handle_job_queue_update", "(", "self", ",", "message", ":", "BackendGetQueue", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Received job queue update\"", ")", "self", ".", "_queue_update_last_attempt", "=", "0", "self", ".", "_queue_ca...
Handles a BackendGetQueue containing a snapshot of the job queue
[ "Handles", "a", "BackendGetQueue", "containing", "a", "snapshot", "of", "the", "job", "queue" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L164-L185
248,776
UCL-INGI/INGInious
inginious/client/client.py
Client.new_job
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): """ Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback:...
python
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): job_id = str(uuid.uuid4()) if debug == "ssh" and ssh_callback is None: self._logger.error("SSH callback not set in %s/%s", task.get_course_id(), task.get_id()) callback(("crash...
[ "def", "new_job", "(", "self", ",", "task", ",", "inputdata", ",", "callback", ",", "launcher_name", "=", "\"Unknown\"", ",", "debug", "=", "False", ",", "ssh_callback", "=", "None", ")", ":", "job_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ...
Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signatur...
[ "Add", "a", "new", "job", ".", "Every", "callback", "will", "be", "called", "once", "and", "only", "once", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L253-L311
248,777
UCL-INGI/INGInious
inginious/client/client.py
Client.kill_job
def kill_job(self, job_id): """ Kills a running job """ self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id)))
python
def kill_job(self, job_id): self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id)))
[ "def", "kill_job", "(", "self", ",", "job_id", ")", ":", "self", ".", "_loop", ".", "call_soon_threadsafe", "(", "asyncio", ".", "ensure_future", ",", "self", ".", "_simple_send", "(", "ClientKillJob", "(", "job_id", ")", ")", ")" ]
Kills a running job
[ "Kills", "a", "running", "job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L313-L317
248,778
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_codeblock
def get_codeblock(language, text): """ Generates rst codeblock for given text and language """ rst = "\n\n.. code-block:: " + language + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
python
def get_codeblock(language, text): rst = "\n\n.. code-block:: " + language + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
[ "def", "get_codeblock", "(", "language", ",", "text", ")", ":", "rst", "=", "\"\\n\\n.. code-block:: \"", "+", "language", "+", "\"\\n\\n\"", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "rst", "+=", "\"\\t\"", "+", "line", "+", "\"\\n\""...
Generates rst codeblock for given text and language
[ "Generates", "rst", "codeblock", "for", "given", "text", "and", "language" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L9-L16
248,779
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_imageblock
def get_imageblock(filename, format=''): """ Generates rst raw block for given image filename and format""" _, extension = os.path.splitext(filename) with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') return '\n\n.. raw:: html\n\n\t<im...
python
def get_imageblock(filename, format=''): _, extension = os.path.splitext(filename) with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') return '\n\n.. raw:: html\n\n\t<img src="data:image/' + (format if format else extension[1:]) + ';base64,...
[ "def", "get_imageblock", "(", "filename", ",", "format", "=", "''", ")", ":", "_", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "image_file", ":", "encoded_s...
Generates rst raw block for given image filename and format
[ "Generates", "rst", "raw", "block", "for", "given", "image", "filename", "and", "format" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L18-L25
248,780
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_admonition
def get_admonition(cssclass, title, text): """ Generates rst admonition block given a bootstrap alert css class, title, and text""" rst = ("\n\n.. admonition:: " + title + "\n") if title else "\n\n.. note:: \n" rst += "\t:class: alert alert-" + cssclass + "\n\n" for line in text.splitlines(): rs...
python
def get_admonition(cssclass, title, text): rst = ("\n\n.. admonition:: " + title + "\n") if title else "\n\n.. note:: \n" rst += "\t:class: alert alert-" + cssclass + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
[ "def", "get_admonition", "(", "cssclass", ",", "title", ",", "text", ")", ":", "rst", "=", "(", "\"\\n\\n.. admonition:: \"", "+", "title", "+", "\"\\n\"", ")", "if", "title", "else", "\"\\n\\n.. note:: \\n\"", "rst", "+=", "\"\\t:class: alert alert-\"", "+", "c...
Generates rst admonition block given a bootstrap alert css class, title, and text
[ "Generates", "rst", "admonition", "block", "given", "a", "bootstrap", "alert", "css", "class", "title", "and", "text" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L27-L35
248,781
UCL-INGI/INGInious
base-containers/base/inginious/lang.py
init
def init(): """ Install gettext with the default parameters """ if "_" not in builtins.__dict__: # avoid installing lang two times os.environ["LANGUAGE"] = inginious.input.get_lang() if inginious.DEBUG: gettext.install("messages", get_lang_dir_path()) else: gette...
python
def init(): if "_" not in builtins.__dict__: # avoid installing lang two times os.environ["LANGUAGE"] = inginious.input.get_lang() if inginious.DEBUG: gettext.install("messages", get_lang_dir_path()) else: gettext.install("messages", get_lang_dir_path())
[ "def", "init", "(", ")", ":", "if", "\"_\"", "not", "in", "builtins", ".", "__dict__", ":", "# avoid installing lang two times", "os", ".", "environ", "[", "\"LANGUAGE\"", "]", "=", "inginious", ".", "input", ".", "get_lang", "(", ")", "if", "inginious", "...
Install gettext with the default parameters
[ "Install", "gettext", "with", "the", "default", "parameters" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/lang.py#L22-L29
248,782
UCL-INGI/INGInious
inginious/common/filesystems/local.py
LocalFSProvider._recursive_overwrite
def _recursive_overwrite(self, src, dest): """ Copy src to dest, recursively and with file overwrite. """ if os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) for f in files: self....
python
def _recursive_overwrite(self, src, dest): if os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) for f in files: self._recursive_overwrite(os.path.join(src, f), os...
[ "def", "_recursive_overwrite", "(", "self", ",", "src", ",", "dest", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest", ")", ":", "os", ".", "makedirs", "(", "dest", ...
Copy src to dest, recursively and with file overwrite.
[ "Copy", "src", "to", "dest", "recursively", "and", "with", "file", "overwrite", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/local.py#L134-L146
248,783
UCL-INGI/INGInious
inginious/frontend/plugins/git_repo/__init__.py
init
def init(plugin_manager, _, _2, config): """ Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions" """ submission_git_saver = SubmissionGitSaver(p...
python
def init(plugin_manager, _, _2, config): submission_git_saver = SubmissionGitSaver(plugin_manager, config) submission_git_saver.daemon = True submission_git_saver.start()
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "config", ")", ":", "submission_git_saver", "=", "SubmissionGitSaver", "(", "plugin_manager", ",", "config", ")", "submission_git_saver", ".", "daemon", "=", "True", "submission_git_saver", ".", "st...
Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions"
[ "Init", "the", "plugin" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/git_repo/__init__.py#L97-L111
248,784
UCL-INGI/INGInious
inginious/common/tags.py
Tag.get_type_as_str
def get_type_as_str(self): """ Return a textual description of the type """ if self.get_type() == 0: return _("Skill") elif self.get_type() == 1: return _("Misconception") elif self.get_type() == 2: return _("Category") else: return...
python
def get_type_as_str(self): if self.get_type() == 0: return _("Skill") elif self.get_type() == 1: return _("Misconception") elif self.get_type() == 2: return _("Category") else: return _("Unknown type")
[ "def", "get_type_as_str", "(", "self", ")", ":", "if", "self", ".", "get_type", "(", ")", "==", "0", ":", "return", "_", "(", "\"Skill\"", ")", "elif", "self", ".", "get_type", "(", ")", "==", "1", ":", "return", "_", "(", "\"Misconception\"", ")", ...
Return a textual description of the type
[ "Return", "a", "textual", "description", "of", "the", "type" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tags.py#L58-L67
248,785
UCL-INGI/INGInious
inginious/common/tags.py
Tag.create_tags_from_dict
def create_tags_from_dict(cls, tag_dict): """ Build a tuple of list of Tag objects based on the tag_dict. The tuple contains 3 lists. - The first list contains skill tags - The second list contains misconception tags - The third list contains category...
python
def create_tags_from_dict(cls, tag_dict): tag_list_common = [] tag_list_misconception = [] tag_list_organisational = [] for tag in tag_dict: try: id = tag_dict[tag]["id"] name = tag_dict[tag]["name"] visible = tag_dict[tag]["vis...
[ "def", "create_tags_from_dict", "(", "cls", ",", "tag_dict", ")", ":", "tag_list_common", "=", "[", "]", "tag_list_misconception", "=", "[", "]", "tag_list_organisational", "=", "[", "]", "for", "tag", "in", "tag_dict", ":", "try", ":", "id", "=", "tag_dict"...
Build a tuple of list of Tag objects based on the tag_dict. The tuple contains 3 lists. - The first list contains skill tags - The second list contains misconception tags - The third list contains category tags
[ "Build", "a", "tuple", "of", "list", "of", "Tag", "objects", "based", "on", "the", "tag_dict", ".", "The", "tuple", "contains", "3", "lists", ".", "-", "The", "first", "list", "contains", "skill", "tags", "-", "The", "second", "list", "contains", "miscon...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tags.py#L73-L100
248,786
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.run
async def run(self): """ Runs the agent. Answer to the requests made by the Backend. May raise an asyncio.CancelledError, in which case the agent should clean itself and restart completely. """ self._logger.info("Agent started") self.__backend_socket.connect(self.__backen...
python
async def run(self): self._logger.info("Agent started") self.__backend_socket.connect(self.__backend_addr) # Tell the backend we are up and have `concurrency` threads available self._logger.info("Saying hello to the backend") await ZMQUtils.send(self.__backend_socket, AgentHello...
[ "async", "def", "run", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Agent started\"", ")", "self", ".", "__backend_socket", ".", "connect", "(", "self", ".", "__backend_addr", ")", "# Tell the backend we are up and have `concurrency` threads a...
Runs the agent. Answer to the requests made by the Backend. May raise an asyncio.CancelledError, in which case the agent should clean itself and restart completely.
[ "Runs", "the", "agent", ".", "Answer", "to", "the", "requests", "made", "by", "the", "Backend", ".", "May", "raise", "an", "asyncio", ".", "CancelledError", "in", "which", "case", "the", "agent", "should", "clean", "itself", "and", "restart", "completely", ...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L100-L117
248,787
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__check_last_ping
async def __check_last_ping(self, run_listen): """ Check if the last timeout is too old. If it is, kills the run_listen task """ if self.__last_ping < time.time()-10: self._logger.warning("Last ping too old. Restarting the agent.") run_listen.cancel() self.__cancel_re...
python
async def __check_last_ping(self, run_listen): if self.__last_ping < time.time()-10: self._logger.warning("Last ping too old. Restarting the agent.") run_listen.cancel() self.__cancel_remaining_safe_tasks() else: self._loop.call_later(1, self._create_safe_...
[ "async", "def", "__check_last_ping", "(", "self", ",", "run_listen", ")", ":", "if", "self", ".", "__last_ping", "<", "time", ".", "time", "(", ")", "-", "10", ":", "self", ".", "_logger", ".", "warning", "(", "\"Last ping too old. Restarting the agent.\"", ...
Check if the last timeout is too old. If it is, kills the run_listen task
[ "Check", "if", "the", "last", "timeout", "is", "too", "old", ".", "If", "it", "is", "kills", "the", "run_listen", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L119-L126
248,788
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__run_listen
async def __run_listen(self): """ Listen to the backend """ while True: message = await ZMQUtils.recv(self.__backend_socket) await self.__handle_backend_message(message)
python
async def __run_listen(self): while True: message = await ZMQUtils.recv(self.__backend_socket) await self.__handle_backend_message(message)
[ "async", "def", "__run_listen", "(", "self", ")", ":", "while", "True", ":", "message", "=", "await", "ZMQUtils", ".", "recv", "(", "self", ".", "__backend_socket", ")", "await", "self", ".", "__handle_backend_message", "(", "message", ")" ]
Listen to the backend
[ "Listen", "to", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L128-L132
248,789
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__handle_ping
async def __handle_ping(self, _ : Ping): """ Handle a Ping message. Pong the backend """ self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
python
async def __handle_ping(self, _ : Ping): self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
[ "async", "def", "__handle_ping", "(", "self", ",", "_", ":", "Ping", ")", ":", "self", ".", "__last_ping", "=", "time", ".", "time", "(", ")", "await", "ZMQUtils", ".", "send", "(", "self", ".", "__backend_socket", ",", "Pong", "(", ")", ")" ]
Handle a Ping message. Pong the backend
[ "Handle", "a", "Ping", "message", ".", "Pong", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L147-L150
248,790
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/utils.py
get_menu
def get_menu(course, current, renderer, plugin_manager, user_manager): """ Returns the HTML of the menu used in the administration. ```current``` is the current page of section """ default_entries = [] if user_manager.has_admin_rights_on_course(course): default_entries += [("settings", "<i class='fa...
python
def get_menu(course, current, renderer, plugin_manager, user_manager): default_entries = [] if user_manager.has_admin_rights_on_course(course): default_entries += [("settings", "<i class='fa fa-cog fa-fw'></i>&nbsp; " + _("Course settings"))] default_entries += [("stats", "<i class='fa fa-area-char...
[ "def", "get_menu", "(", "course", ",", "current", ",", "renderer", ",", "plugin_manager", ",", "user_manager", ")", ":", "default_entries", "=", "[", "]", "if", "user_manager", ".", "has_admin_rights_on_course", "(", "course", ")", ":", "default_entries", "+=", ...
Returns the HTML of the menu used in the administration. ```current``` is the current page of section
[ "Returns", "the", "HTML", "of", "the", "menu", "used", "in", "the", "administration", ".", "current", "is", "the", "current", "page", "of", "section" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/utils.py#L252-L278
248,791
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/utils.py
UnicodeWriter.writerow
def writerow(self, row): """ Writes a row to the CSV file """ self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) s...
python
def writerow(self, row): self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) self.queue.seek(0)
[ "def", "writerow", "(", "self", ",", "row", ")", ":", "self", ".", "writer", ".", "writerow", "(", "row", ")", "# Fetch UTF-8 output from the queue ...", "data", "=", "self", ".", "queue", ".", "getvalue", "(", ")", "# write to the target stream", "self", ".",...
Writes a row to the CSV file
[ "Writes", "a", "row", "to", "the", "CSV", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/utils.py#L175-L184
248,792
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper.get_renderer
def get_renderer(self, with_layout=True): """ Get the default renderer """ if with_layout and self.is_lti(): return self._default_renderer_lti elif with_layout: return self._default_renderer else: return self._default_renderer_nolayout
python
def get_renderer(self, with_layout=True): if with_layout and self.is_lti(): return self._default_renderer_lti elif with_layout: return self._default_renderer else: return self._default_renderer_nolayout
[ "def", "get_renderer", "(", "self", ",", "with_layout", "=", "True", ")", ":", "if", "with_layout", "and", "self", ".", "is_lti", "(", ")", ":", "return", "self", ".", "_default_renderer_lti", "elif", "with_layout", ":", "return", "self", ".", "_default_rend...
Get the default renderer
[ "Get", "the", "default", "renderer" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L63-L70
248,793
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._javascript_helper
def _javascript_helper(self, position): """ Add javascript links for the current page and for the plugins """ if position not in ["header", "footer"]: position = "footer" # Load javascript files from plugins if position == "header": entries = [entry for entry in ...
python
def _javascript_helper(self, position): if position not in ["header", "footer"]: position = "footer" # Load javascript files from plugins if position == "header": entries = [entry for entry in self._plugin_manager.call_hook("javascript_header") if entry is not None] ...
[ "def", "_javascript_helper", "(", "self", ",", "position", ")", ":", "if", "position", "not", "in", "[", "\"header\"", ",", "\"footer\"", "]", ":", "position", "=", "\"footer\"", "# Load javascript files from plugins", "if", "position", "==", "\"header\"", ":", ...
Add javascript links for the current page and for the plugins
[ "Add", "javascript", "links", "for", "the", "current", "page", "and", "for", "the", "plugins" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L117-L130
248,794
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._css_helper
def _css_helper(self): """ Add CSS links for the current page and for the plugins """ entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + ent...
python
def _css_helper(self): entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + entry + "' rel='stylesheet'>" for entry in entries] return "\n".jo...
[ "def", "_css_helper", "(", "self", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "\"css\"", ")", "if", "entry", "is", "not", "None", "]", "# Load javascript for the current page", "entries"...
Add CSS links for the current page and for the plugins
[ "Add", "CSS", "links", "for", "the", "current", "page", "and", "for", "the", "plugins" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L132-L138
248,795
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._get_ctx
def _get_ctx(self): """ Get web.ctx object for the Template helper """ if self._WEB_CTX_KEY not in web.ctx: web.ctx[self._WEB_CTX_KEY] = { "javascript": {"footer": [], "header": []}, "css": []} return web.ctx.get(self._WEB_CTX_KEY)
python
def _get_ctx(self): if self._WEB_CTX_KEY not in web.ctx: web.ctx[self._WEB_CTX_KEY] = { "javascript": {"footer": [], "header": []}, "css": []} return web.ctx.get(self._WEB_CTX_KEY)
[ "def", "_get_ctx", "(", "self", ")", ":", "if", "self", ".", "_WEB_CTX_KEY", "not", "in", "web", ".", "ctx", ":", "web", ".", "ctx", "[", "self", ".", "_WEB_CTX_KEY", "]", "=", "{", "\"javascript\"", ":", "{", "\"footer\"", ":", "[", "]", ",", "\"h...
Get web.ctx object for the Template helper
[ "Get", "web", ".", "ctx", "object", "for", "the", "Template", "helper" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L140-L146
248,796
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._generic_hook
def _generic_hook(self, name, **kwargs): """ A generic hook that links the TemplateHelper with PluginManager """ entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
python
def _generic_hook(self, name, **kwargs): entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
[ "def", "_generic_hook", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "name", ",", "*", "*", "kwargs", ")", "if", "entry", "is",...
A generic hook that links the TemplateHelper with PluginManager
[ "A", "generic", "hook", "that", "links", "the", "TemplateHelper", "with", "PluginManager" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L148-L151
248,797
UCL-INGI/INGInious
inginious/client/client_buffer.py
ClientBuffer.new_job
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): """ Runs a new job. It works exactly like the Client class, instead that there is no callback """ bjobid = uuid.uuid4() self._waiting_jobs.append(str(bjobid)) self._client.new_job(task, inputdata, ...
python
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): bjobid = uuid.uuid4() self._waiting_jobs.append(str(bjobid)) self._client.new_job(task, inputdata, (lambda result, grade, problems, tests, custom, archive, stdout, stderr: ...
[ "def", "new_job", "(", "self", ",", "task", ",", "inputdata", ",", "launcher_name", "=", "\"Unknown\"", ",", "debug", "=", "False", ")", ":", "bjobid", "=", "uuid", ".", "uuid4", "(", ")", "self", ".", "_waiting_jobs", ".", "append", "(", "str", "(", ...
Runs a new job. It works exactly like the Client class, instead that there is no callback
[ "Runs", "a", "new", "job", ".", "It", "works", "exactly", "like", "the", "Client", "class", "instead", "that", "there", "is", "no", "callback" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_buffer.py#L19-L27
248,798
UCL-INGI/INGInious
inginious/client/client_buffer.py
ClientBuffer._callback
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): """ Callback for self._client.new_job """ self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
python
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
[ "def", "_callback", "(", "self", ",", "bjobid", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "archive", ",", "stdout", ",", "stderr", ")", ":", "self", ".", "_jobs_done", "[", "str", "(", "bjobid", ")", "]", "=", ...
Callback for self._client.new_job
[ "Callback", "for", "self", ".", "_client", ".", "new_job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_buffer.py#L29-L32
248,799
UCL-INGI/INGInious
inginious/frontend/plugins/auth/ldap_auth.py
init
def init(plugin_manager, _, _2, conf): """ Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, ...
python
def init(plugin_manager, _, _2, conf): encryption = conf.get("encryption", "none") if encryption not in ["none", "ssl", "tls"]: raise Exception("Unknown encryption method {}".format(encryption)) if encryption == "none": conf["encryption"] = None if conf.get("port", 0) == 0: conf...
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "conf", ")", ":", "encryption", "=", "conf", ".", "get", "(", "\"encryption\"", ",", "\"none\"", ")", "if", "encryption", "not", "in", "[", "\"none\"", ",", "\"ssl\"", ",", "\"tls\"", "]",...
Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o...
[ "Allow", "to", "connect", "through", "a", "LDAP", "service" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/ldap_auth.py#L127-L165