_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q268500
QasmLexer.input
test
def input(self, data): """Set the input text data.""" self.data = data self.lexer.input(data)
python
{ "resource": "" }
q268501
QasmLexer.pop
test
def pop(self): """Pop a PLY lexer off the stack.""" self.lexer = self.stack.pop() self.filename = self.lexer.qasm_file self.lineno = self.lexer.qasm_line
python
{ "resource": "" }
q268502
QasmLexer.push
test
def push(self, filename): """Push a PLY lexer on the stack to parse filename.""" self.lexer.qasm_file = self.filename self.lexer.qasm_line = self.lineno self.stack.append(self.lexer) self.__mklexer__(filename)
python
{ "resource": "" }
q268503
ConsolidateBlocks.run
test
def run(self, dag): """iterate over each block and replace it with an equivalent Unitary on the same wires. """ new_dag = DAGCircuit() for qreg in dag.qregs.values(): new_dag.add_qreg(qreg) for creg in dag.cregs.values(): new_dag.add_creg(creg) ...
python
{ "resource": "" }
q268504
ConversionMethodBinder.get_bound_method
test
def get_bound_method(self, instruction): """Get conversion method for instruction.""" try: return self._bound_instructions[type(instruction)] except KeyError: raise PulseError('Qobj conversion method for %s is not found.' % instruction)
python
{ "resource": "" }
q268505
PulseQobjConverter.convert_acquire
test
def convert_acquire(self, shift, instruction): """Return converted `AcquireInstruction`. Args: shift(int): Offset time. instruction (AcquireInstruction): acquire instruction. Returns: dict: Dictionary of required parameters. """ meas_level = s...
python
{ "resource": "" }
q268506
PulseQobjConverter.convert_frame_change
test
def convert_frame_change(self, shift, instruction): """Return converted `FrameChangeInstruction`. Args: shift(int): Offset time. instruction (FrameChangeInstruction): frame change instruction. Returns: dict: Dictionary of required parameters. """ ...
python
{ "resource": "" }
q268507
PulseQobjConverter.convert_persistent_value
test
def convert_persistent_value(self, shift, instruction): """Return converted `PersistentValueInstruction`. Args: shift(int): Offset time. instruction (PersistentValueInstruction): persistent value instruction. Returns: dict: Dictionary of required parameters. ...
python
{ "resource": "" }
q268508
PulseQobjConverter.convert_drive
test
def convert_drive(self, shift, instruction): """Return converted `PulseInstruction`. Args: shift(int): Offset time. instruction (PulseInstruction): drive instruction. Returns: dict: Dictionary of required parameters. """ command_dict = { ...
python
{ "resource": "" }
q268509
PulseQobjConverter.convert_snapshot
test
def convert_snapshot(self, shift, instruction): """Return converted `Snapshot`. Args: shift(int): Offset time. instruction (Snapshot): snapshot instruction. Returns: dict: Dictionary of required parameters. """ command_dict = { 'na...
python
{ "resource": "" }
q268510
_update_annotations
test
def _update_annotations(discretized_pulse: Callable) -> Callable: """Update annotations of discretized continuous pulse function with duration. Args: discretized_pulse: Discretized decorated continuous pulse. """ undecorated_annotations = list(discretized_pulse.__annotations__.items()) deco...
python
{ "resource": "" }
q268511
sampler
test
def sampler(sample_function: Callable) -> Callable: """Sampler decorator base method. Samplers are used for converting an continuous function to a discretized pulse. They operate on a function with the signature: `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray` Where `times` is a nump...
python
{ "resource": "" }
q268512
filter_backends
test
def filter_backends(backends, filters=None, **kwargs): """Return the backends matching the specified filtering. Filter the `backends` list by their `configuration` or `status` attributes, or from a boolean callable. The criteria for filtering can be specified via `**kwargs` or as a callable via `filter...
python
{ "resource": "" }
q268513
resolve_backend_name
test
def resolve_backend_name(name, backends, deprecated, aliased): """Resolve backend name from a deprecated name or an alias. A group will be resolved in order of member priorities, depending on availability. Args: name (str): name of backend to resolve backends (list[BaseBackend]): list ...
python
{ "resource": "" }
q268514
dag_to_circuit
test
def dag_to_circuit(dag): """Build a ``QuantumCircuit`` object from a ``DAGCircuit``. Args: dag (DAGCircuit): the input dag. Return: QuantumCircuit: the circuit representing the input dag. """ qregs = collections.OrderedDict() for qreg in dag.qregs.values(): qreg_tmp = Q...
python
{ "resource": "" }
q268515
make_dict_observable
test
def make_dict_observable(matrix_observable): """Convert an observable in matrix form to dictionary form. Takes in a diagonal observable as a matrix and converts it to a dictionary form. Can also handle a list sorted of the diagonal elements. Args: matrix_observable (list): The observable to be...
python
{ "resource": "" }
q268516
QasmParser.update_symtab
test
def update_symtab(self, obj): """Update a node in the symbol table. Everything in the symtab must be a node with these attributes: name - the string name of the object type - the string type of the object line - the source line where the type was first found file - the s...
python
{ "resource": "" }
q268517
QasmParser.verify_declared_bit
test
def verify_declared_bit(self, obj): """Verify a qubit id against the gate prototype.""" # We are verifying gate args against the formal parameters of a # gate prototype. if obj.name not in self.current_symtab: raise QasmError("Cannot find symbol '" + obj.name ...
python
{ "resource": "" }
q268518
QasmParser.verify_exp_list
test
def verify_exp_list(self, obj): """Verify each expression in a list.""" # A tad harder. This is a list of expressions each of which could be # the head of a tree. We need to recursively walk each of these and # ensure that any Id elements resolve to the current stack. # ...
python
{ "resource": "" }
q268519
QasmParser.verify_as_gate
test
def verify_as_gate(self, obj, bitlist, arglist=None): """Verify a user defined gate call.""" if obj.name not in self.global_symtab: raise QasmError("Cannot find gate definition for '" + obj.name + "', line", str(obj.line), 'file', obj.file) g_sym = self.gl...
python
{ "resource": "" }
q268520
QasmParser.verify_reg
test
def verify_reg(self, obj, object_type): """Verify a register.""" # How to verify: # types must match # indexes must be checked if obj.name not in self.global_symtab: raise QasmError('Cannot find definition for', object_type, "'" + obj...
python
{ "resource": "" }
q268521
QasmParser.verify_reg_list
test
def verify_reg_list(self, obj, object_type): """Verify a list of registers.""" # We expect the object to be a bitlist or an idlist, we don't care. # We will iterate it and ensure everything in it is declared as a bit, # and throw if not. for children in obj.children: ...
python
{ "resource": "" }
q268522
QasmParser.find_column
test
def find_column(self, input_, token): """Compute the column. Input is the input text string. token is a token instance. """ if token is None: return 0 last_cr = input_.rfind('\n', 0, token.lexpos) if last_cr < 0: last_cr = 0 column...
python
{ "resource": "" }
q268523
QasmParser.parse_debug
test
def parse_debug(self, val): """Set the parse_deb field.""" if val is True: self.parse_deb = True elif val is False: self.parse_deb = False else: raise QasmError("Illegal debug value '" + str(val) + "' must be True or False."...
python
{ "resource": "" }
q268524
QasmParser.parse
test
def parse(self, data): """Parse some data.""" self.parser.parse(data, lexer=self.lexer, debug=self.parse_deb) if self.qasm is None: raise QasmError("Uncaught exception in parser; " + "see previous messages for details.") return self.qasm
python
{ "resource": "" }
q268525
QasmParser.run
test
def run(self, data): """Parser runner. To use this module stand-alone. """ ast = self.parser.parse(data, debug=True) self.parser.parse(data, debug=True) ast.to_string(0)
python
{ "resource": "" }
q268526
Qasm.parse
test
def parse(self): """Parse the data.""" if self._filename: with open(self._filename) as ifile: self._data = ifile.read() with QasmParser(self._filename) as qasm_p: qasm_p.parse_debug(False) return qasm_p.parse(self._data)
python
{ "resource": "" }
q268527
crz
test
def crz(self, theta, ctl, tgt): """Apply crz from ctl to tgt with angle theta.""" return self.append(CrzGate(theta), [ctl, tgt], [])
python
{ "resource": "" }
q268528
basis_state
test
def basis_state(str_state, num): """ Return a basis state ndarray. Args: str_state (string): a string representing the state. num (int): the number of qubits Returns: ndarray: state(2**num) a quantum state with basis basis state. Raises: QiskitError: if the dimensi...
python
{ "resource": "" }
q268529
projector
test
def projector(state, flatten=False): """ maps a pure state to a state matrix Args: state (ndarray): the number of qubits flatten (bool): determine if state matrix of column work Returns: ndarray: state_mat(2**num, 2**num) if flatten is false ndarray: state_mat(4**num) ...
python
{ "resource": "" }
q268530
purity
test
def purity(state): """Calculate the purity of a quantum state. Args: state (ndarray): a quantum state Returns: float: purity. """ rho = np.array(state) if rho.ndim == 1: return 1.0 return np.real(np.trace(rho.dot(rho)))
python
{ "resource": "" }
q268531
CommutationAnalysis.run
test
def run(self, dag): """ Run the pass on the DAG, and write the discovered commutation relations into the property_set. """ # Initiate the commutation set self.property_set['commutation_set'] = defaultdict(list) # Build a dictionary to keep track of the gates on e...
python
{ "resource": "" }
q268532
backend_widget
test
def backend_widget(backend): """Creates a backend widget. """ config = backend.configuration().to_dict() props = backend.properties().to_dict() name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()), layout=widgets.Layout()) n_qubits = config['n_qubits'...
python
{ "resource": "" }
q268533
update_backend_info
test
def update_backend_info(self, interval=60): """Updates the monitor info Called from another thread. """ my_thread = threading.currentThread() current_interval = 0 started = False all_dead = False stati = [None]*len(self._backends) while getattr(my_thread, "do_run", True) and not all_...
python
{ "resource": "" }
q268534
generate_jobs_pending_widget
test
def generate_jobs_pending_widget(): """Generates a jobs_pending progress bar widget. """ pbar = widgets.IntProgress( value=0, min=0, max=50, description='', orientation='horizontal', layout=widgets.Layout(max_width='180px')) pbar.style.bar_color = '#71cddd' p...
python
{ "resource": "" }
q268535
CXCancellation.run
test
def run(self, dag): """ Run one pass of cx cancellation on the circuit Args: dag (DAGCircuit): the directed acyclic graph to run on. Returns: DAGCircuit: Transformed DAG. """ cx_runs = dag.collect_runs(["cx"]) for cx_run in cx_runs: ...
python
{ "resource": "" }
q268536
BaseProvider.get_backend
test
def get_backend(self, name=None, **kwargs): """Return a single backend matching the specified filtering. Args: name (str): name of the backend. **kwargs (dict): dict used for filtering. Returns: BaseBackend: a backend matching the filtering. Raises:...
python
{ "resource": "" }
q268537
Choi._bipartite_shape
test
def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim)
python
{ "resource": "" }
q268538
_get_register_specs
test
def _get_register_specs(bit_labels): """Get the number and size of unique registers from bit_labels list. Args: bit_labels (list): this list is of the form:: [['reg1', 0], ['reg1', 1], ['reg2', 0]] which indicates a register named "reg1" of size 2 and a register na...
python
{ "resource": "" }
q268539
_truncate_float
test
def _truncate_float(matchobj, format_str='0.2g'): """Truncate long floats Args: matchobj (re.Match): contains original float format_str (str): format specifier Returns: str: returns truncated float """ if matchobj.group(0): return format(float(matchobj.group(0)), form...
python
{ "resource": "" }
q268540
QCircuitImage.latex
test
def latex(self, aliases=None): """Return LaTeX string representation of circuit. This method uses the LaTeX Qconfig package to create a graphical representation of the circuit. Returns: string: for writing to a LaTeX file. """ self._initialize_latex_array(al...
python
{ "resource": "" }
q268541
QCircuitImage._get_image_depth
test
def _get_image_depth(self): """Get depth information for the circuit. Returns: int: number of columns in the circuit int: total size of columns in the circuit """ max_column_widths = [] for layer in self.ops: # store the max width for the l...
python
{ "resource": "" }
q268542
QCircuitImage._get_beamer_page
test
def _get_beamer_page(self): """Get height, width & scale attributes for the beamer page. Returns: tuple: (height, width, scale) desirable page attributes """ # PIL python package limits image size to around a quarter gigabyte # this means the beamer image should be l...
python
{ "resource": "" }
q268543
_load_schema
test
def _load_schema(file_path, name=None): """Loads the QObj schema for use in future validations. Caches schema in _SCHEMAS module attribute. Args: file_path(str): Path to schema. name(str): Given name for schema. Defaults to file_path filename without schema. Return: sc...
python
{ "resource": "" }
q268544
_get_validator
test
def _get_validator(name, schema=None, check_schema=True, validator_class=None, **validator_kwargs): """Generate validator for JSON schema. Args: name (str): Name for validator. Will be validator key in `_VALIDATORS` dict. schema (dict): JSON schema `dict`. If not ...
python
{ "resource": "" }
q268545
_load_schemas_and_validators
test
def _load_schemas_and_validators(): """Load all default schemas into `_SCHEMAS`.""" schema_base_path = os.path.join(os.path.dirname(__file__), '../..') for name, path in _DEFAULT_SCHEMA_PATHS.items(): _load_schema(os.path.join(schema_base_path, path), name) _get_validator(name)
python
{ "resource": "" }
q268546
validate_json_against_schema
test
def validate_json_against_schema(json_dict, schema, err_msg=None): """Validates JSON dict against a schema. Args: json_dict (dict): JSON to be validated. schema (dict or str): JSON schema dictionary or the name of one of the standards schemas in Qisk...
python
{ "resource": "" }
q268547
_format_causes
test
def _format_causes(err, level=0): """Return a cascading explanation of the validation error. Returns a cascading explanation of the validation error in the form of:: <validator> failed @ <subfield_path> because of: <validator> failed @ <subfield_path> because of: ... ...
python
{ "resource": "" }
q268548
majority
test
def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c)
python
{ "resource": "" }
q268549
unmajority
test
def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b)
python
{ "resource": "" }
q268550
_generate_latex_source
test
def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image sc...
python
{ "resource": "" }
q268551
_matplotlib_circuit_drawer
test
def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): ...
python
{ "resource": "" }
q268552
random_unitary
test
def random_unitary(dim, seed=None): """ Return a random dim x dim unitary Operator from the Haar measure. Args: dim (int): the dim of the state space. seed (int): Optional. To set a random seed. Returns: Operator: (dim, dim) unitary operator. Raises: QiskitError: i...
python
{ "resource": "" }
q268553
random_density_matrix
test
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None): """ Generate a random density matrix rho. Args: length (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. method (...
python
{ "resource": "" }
q268554
__ginibre_matrix
test
def __ginibre_matrix(nrow, ncol=None, seed=None): """ Return a normally distributed complex random matrix. Args: nrow (int): number of rows in output matrix. ncol (int): number of columns in output matrix. seed (int): Optional. To set a random seed. Returns: ndarray: A c...
python
{ "resource": "" }
q268555
__random_density_hs
test
def __random_density_hs(N, rank=None, seed=None): """ Generate a random density matrix from the Hilbert-Schmidt metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Option...
python
{ "resource": "" }
q268556
__random_density_bures
test
def __random_density_bures(N, rank=None, seed=None): """ Generate a random density matrix from the Bures metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To ...
python
{ "resource": "" }
q268557
GateBody.calls
test
def calls(self): """Return a list of custom gate names in this gate body.""" lst = [] for children in self.children: if children.type == "custom_unitary": lst.append(children.name) return lst
python
{ "resource": "" }
q268558
SuperOp.power
test
def power(self, n): """Return the compose of a QuantumChannel with itself n times. Args: n (int): compute the matrix power of the superoperator matrix. Returns: SuperOp: the n-times composition channel as a SuperOp object. Raises: QiskitError: if th...
python
{ "resource": "" }
q268559
SuperOp._compose_subsystem
test
def _compose_subsystem(self, other, qargs, front=False): """Return the composition channel.""" # Compute tensor contraction indices from qargs input_dims = list(self.input_dims()) output_dims = list(self.output_dims()) if front: num_indices = len(self.input_dims()) ...
python
{ "resource": "" }
q268560
SuperOp._instruction_to_superop
test
def _instruction_to_superop(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the ...
python
{ "resource": "" }
q268561
BarrierBeforeFinalMeasurements.run
test
def run(self, dag): """Return a circuit with a barrier before last measurements.""" # Collect DAG nodes which are followed only by barriers or other measures. final_op_types = ['measure', 'barrier'] final_ops = [] for candidate_node in dag.named_nodes(*final_op_types): ...
python
{ "resource": "" }
q268562
circuits_to_qobj
test
def circuits_to_qobj(circuits, qobj_header=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, coupling_map=None, seed=None, memory=None): """Convert a list of circuits into a qobj. ...
python
{ "resource": "" }
q268563
Unroll3qOrMore.run
test
def run(self, dag): """Expand 3+ qubit gates using their decomposition rules. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag with maximum node degrees of 2 Raises: QiskitError: if a 3q+ gate is not decomposable """ fo...
python
{ "resource": "" }
q268564
Decompose.run
test
def run(self, dag): """Expand a given gate into its decomposition. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag where gate was expanded. """ # Walk through the DAG and expand each non-basis node for node in dag.op_nodes(self.ga...
python
{ "resource": "" }
q268565
UnitaryGate._define
test
def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") angles = euler_angles_1q(self.to_matrix()) self.definition = [(U3Gate(*angles), [q[0]], [])] if self.num_qubits == 2: ...
python
{ "resource": "" }
q268566
Nested.check_type
test
def check_type(self, value, attr, data): """Validate if the value is of the type of the schema's model. Assumes the nested schema is a ``BaseSchema``. """ if self.many and not is_collection(value): raise self._not_expected_type( value, Iterable, fields=[self]...
python
{ "resource": "" }
q268567
List.check_type
test
def check_type(self, value, attr, data): """Validate if it's a list of valid item-field values. Check if each element in the list can be validated by the item-field passed during construction. """ super().check_type(value, attr, data) errors = [] for idx, v in e...
python
{ "resource": "" }
q268568
BaseOperator._atol
test
def _atol(self, atol): """Set the absolute tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if atol < 0: raise QiskitError("Invalid atol: must be non-...
python
{ "resource": "" }
q268569
BaseOperator._rtol
test
def _rtol(self, rtol): """Set the relative tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if rtol < 0: raise QiskitError("Invalid rtol: must be non-...
python
{ "resource": "" }
q268570
BaseOperator._reshape
test
def _reshape(self, input_dims=None, output_dims=None): """Reshape input and output dimensions of operator. Arg: input_dims (tuple): new subsystem input dimensions. output_dims (tuple): new subsystem output dimensions. Returns: Operator: returns self with res...
python
{ "resource": "" }
q268571
BaseOperator.input_dims
test
def input_dims(self, qargs=None): """Return tuple of input dimension for specified subsystems.""" if qargs is None: return self._input_dims return tuple(self._input_dims[i] for i in qargs)
python
{ "resource": "" }
q268572
BaseOperator.output_dims
test
def output_dims(self, qargs=None): """Return tuple of output dimension for specified subsystems.""" if qargs is None: return self._output_dims return tuple(self._output_dims[i] for i in qargs)
python
{ "resource": "" }
q268573
BaseOperator.copy
test
def copy(self): """Make a copy of current operator.""" # pylint: disable=no-value-for-parameter # The constructor of subclasses from raw data should be a copy return self.__class__(self.data, self.input_dims(), self.output_dims())
python
{ "resource": "" }
q268574
BaseOperator.power
test
def power(self, n): """Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions...
python
{ "resource": "" }
q268575
BaseOperator._automatic_dims
test
def _automatic_dims(cls, dims, size): """Check if input dimension corresponds to qubit subsystems.""" if dims is None: dims = size elif np.product(dims) != size: raise QiskitError("dimensions do not match size.") if isinstance(dims, (int, np.integer)): ...
python
{ "resource": "" }
q268576
BaseOperator._einsum_matmul
test
def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False): """Perform a contraction using Numpy.einsum Args: tensor (np.array): a vector or matrix reshaped to a rank-N tensor. mat (np.array): a matrix reshaped to a rank-2M tensor. indices (list): tensor...
python
{ "resource": "" }
q268577
BasePolyField._deserialize
test
def _deserialize(self, value, attr, data): """Override ``_deserialize`` for customizing the exception raised.""" try: return super()._deserialize(value, attr, data) except ValidationError as ex: if 'deserialization_schema_selector' in ex.messages[0]: ex.me...
python
{ "resource": "" }
q268578
BasePolyField._serialize
test
def _serialize(self, value, key, obj): """Override ``_serialize`` for customizing the exception raised.""" try: return super()._serialize(value, key, obj) except TypeError as ex: if 'serialization_schema_selector' in str(ex): raise ValidationError('Data fr...
python
{ "resource": "" }
q268579
ByType.check_type
test
def check_type(self, value, attr, data): """Check if at least one of the possible choices validates the value. Possible choices are assumed to be ``ModelTypeValidator`` fields. """ for field in self.choices: if isinstance(field, ModelTypeValidator): try: ...
python
{ "resource": "" }
q268580
state_fidelity
test
def state_fidelity(state1, state2): """Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. The state fidelity (F) for two density matrices is defined as:: F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2 For a pure state and m...
python
{ "resource": "" }
q268581
_funm_svd
test
def _funm_svd(a, func): """Apply real scalar function to singular values of a matrix. Args: a (array_like): (N, N) Matrix at which to evaluate the function. func (callable): Callable object that evaluates a scalar function f. Returns: ndarray: funm (N, N) Value of the matrix functi...
python
{ "resource": "" }
q268582
Snapshot.inverse
test
def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1])
python
{ "resource": "" }
q268583
Snapshot.label
test
def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('...
python
{ "resource": "" }
q268584
QuantumChannel.is_unitary
test
def is_unitary(self, atol=None, rtol=None): """Return True if QuantumChannel is a unitary channel.""" try: op = self.to_operator() return op.is_unitary(atol=atol, rtol=rtol) except QiskitError: return False
python
{ "resource": "" }
q268585
QuantumChannel.to_operator
test
def to_operator(self): """Try to convert channel to a unitary representation Operator.""" mat = _to_operator(self.rep, self._data, *self.dim) return Operator(mat, self.input_dims(), self.output_dims())
python
{ "resource": "" }
q268586
QuantumChannel.to_instruction
test
def to_instruction(self): """Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. Returns: Instruction: A kraus instruction for the channel. ...
python
{ "resource": "" }
q268587
QuantumChannel._init_transformer
test
def _init_transformer(cls, data): """Convert input into a QuantumChannel subclass object or Operator object""" # This handles common conversion for all QuantumChannel subclasses. # If the input is already a QuantumChannel subclass it will return # the original object if isinstanc...
python
{ "resource": "" }
q268588
sort_enum_for_model
test
def sort_enum_for_model(cls, name=None, symbol_name=_symbol_name): """Create Graphene Enum for sorting a SQLAlchemy class query Parameters - cls : Sqlalchemy model class Model used to create the sort enumerator - name : str, optional, default None Name to use for the enumerator. If not ...
python
{ "resource": "" }
q268589
patch_strptime
test
def patch_strptime(): """Monkey patching _strptime to avoid problems related with non-english locale changes on the system. For example, if system's locale is set to fr_FR. Parser won't recognize any date since all languages are translated to english dates. """ _strptime = imp.load_module( ...
python
{ "resource": "" }
q268590
LocaleDataLoader.get_locale_map
test
def get_locale_map(self, languages=None, locales=None, region=None, use_given_order=False, allow_conflicting_locales=False): """ Get an ordered mapping with locale codes as keys and corresponding locale instances as values. :param languages: A list of ...
python
{ "resource": "" }
q268591
LocaleDataLoader.get_locales
test
def get_locales(self, languages=None, locales=None, region=None, use_given_order=False, allow_conflicting_locales=False): """ Yield locale instances. :param languages: A list of language codes, e.g. ['en', 'es', 'zh-Hant']. If locales are not given, l...
python
{ "resource": "" }
q268592
Dictionary.are_tokens_valid
test
def are_tokens_valid(self, tokens): """ Check if tokens are valid tokens for the locale. :param tokens: a list of string or unicode tokens. :type tokens: list :return: True if tokens are valid, False otherwise. """ match_relative_regex = self._get_ma...
python
{ "resource": "" }
q268593
Dictionary.split
test
def split(self, string, keep_formatting=False): """ Split the date string using translations in locale info. :param string: Date string to be splitted. :type string: str|unicode :param keep_formatting: If True, retain formatting of the date s...
python
{ "resource": "" }
q268594
parse
test
def parse(date_string, date_formats=None, languages=None, locales=None, region=None, settings=None): """Parse date and time from given date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :param date_formats: ...
python
{ "resource": "" }
q268595
FreshnessDateDataParser._parse_time
test
def _parse_time(self, date_string, settings): """Attemps to parse time part of date strings like '1 day ago, 2 PM' """ date_string = PATTERN.sub('', date_string) date_string = re.sub(r'\b(?:ago|in)\b', '', date_string) try: return time_parser(date_string) except: ...
python
{ "resource": "" }
q268596
Locale.is_applicable
test
def is_applicable(self, date_string, strip_timezone=False, settings=None): """ Check if the locale is applicable to translate date string. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :para...
python
{ "resource": "" }
q268597
Locale.translate
test
def translate(self, date_string, keep_formatting=False, settings=None): """ Translate the date string to its English equivalent. :param date_string: A string representing date and/or time in a recognizably valid format. :type date_string: str|unicode :param keep_for...
python
{ "resource": "" }
q268598
parse_with_formats
test
def parse_with_formats(date_string, date_formats, settings): """ Parse with formats and return a dictionary with 'period' and 'obj_date'. :returns: :class:`datetime.datetime`, dict or None """ period = 'day' for date_format in date_formats: try: date_obj = datetime.strptime(dat...
python
{ "resource": "" }
q268599
ComponentFactory.get_ammo_generator
test
def get_ammo_generator(self): """ return ammo generator """ af_readers = { 'phantom': missile.AmmoFileReader, 'slowlog': missile.SlowLogReader, 'line': missile.LineReader, 'uri': missile.UriReader, 'uripost': missile.UriPostRead...
python
{ "resource": "" }