self._initialize_latex_array(aliases)<EOL>self._build_latex_array(aliases)<EOL>header_1 = r"""<STR_LIT>"""% instead and customize the height and width (in cm) to fit.<EOL>images may run out of memory quickly.<EOL><INDENT>this use the LuaLaTeX compiler, which dynamically<EOL><DEDENT>tes memory.<EOL>age[braket, qm]{qcircuit}<EOL>age{amsmath}<EOL>ile{+sansmathaccent.map}<EOL>ckage[landscape]{geometry}<EOL>t out the above line if using the beamer documentclass.<EOL>ocument}<EOL>quation*}"""<STR_LIT>"""<EOL>rcuit @C=%<NUM_LIT>fem @R=%<NUM_LIT>fem @!R {<EOL>output = io.StringIO()<EOL>output.write(header_1)<EOL>output.write('<STR_LIT>' % (self.img_width, self.img_depth))<EOL>output.write(beamer_line % self._get_beamer_page())<EOL>output.write(header_2)<EOL>output.write(qcircuit_line %<EOL><INDENT>(self.column_separation, self.row_separation))<EOL>for i in range(self.img_width):<EOL>output.write("<STR_LIT>")<EOL>for j in range(self.img_depth + <NUM_LIT:1>):<EOL>cell_str = self._latex[i][j]<EOL>if '<STR_LIT>' in cell_str:<EOL>output.write(cell_str)<EOL>else:<EOL>cell_str = re.sub(r'<STR_LIT>',<EOL><INDENT>_truncate_float,<EOL>cell_str)<EOL>output.write(cell_str)<EOL>if j != self.img_depth:<EOL>output.write("<STR_LIT>")<EOL>else:<EOL>output.write(r'<STR_LIT:\\>' + '<STR_LIT:\n>')<EOL>output.write('<STR_LIT>')<EOL>output.write('<STR_LIT>')<EOL>output.write('<STR_LIT>')<EOL>contents = output.getvalue()<EOL>output.close()<EOL>return contents<EOL>

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.


return len(self.graph.nodes)<EOL>

Return the number of physical qubits in this graph.


default = {'<STR_LIT>': False,  <EOL>'<STR_LIT>': False,  <EOL>'<STR_LIT>': <NUM_LIT:1000>}  <EOL>passmanager_level = {k: v for k, v in self.passmanager_options.items() if v is not None}<EOL>passset_level = {k: v for k, v in passset_options.items() if v is not None}<EOL>return {**default, **passmanager_level, **passset_level}<EOL>

Set the options of each passset, based on precedence rules:
        passset options (set via ``PassManager.append()``) override
        passmanager options (set via ``PassManager.__init__()``), which override Default.
        .


def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,<EOL>initial_layout=None, seed_mapper=None, pass_manager=None):

transpile one or more circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        basis_gates (list[str]): list of basis gate names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits. The final
            layout is not guaranteed to be the same, as the transpiler may permute
            qubits through swaps or other means.

        seed_mapper (int): random seed for the swap_mapper
        pass_manager (PassManager): a pass_manager for the transpiler stages

    Returns:
        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes


def transpile_dag(dag, basis_gates=None, coupling_map=None,<EOL>initial_layout=None, seed_mapper=None, pass_manager=None):

warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", DeprecationWarning)<EOL>if basis_gates is None:<EOL><INDENT>basis_gates = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:id>']<EOL><DEDENT>if pass_manager is None:<EOL><INDENT>if coupling_map:<EOL><INDENT>pass_manager = default_pass_manager(basis_gates,<EOL>CouplingMap(coupling_map),<EOL>initial_layout,<EOL>seed_transpiler=seed_mapper)<EOL><DEDENT>else:<EOL><INDENT>pass_manager = default_pass_manager_simulator(basis_gates)<EOL><DEDENT><DEDENT>name = dag.name<EOL>circuit = dag_to_circuit(dag)<EOL>circuit = pass_manager.run(circuit)<EOL>dag = circuit_to_dag(circuit)<EOL>dag.name = name<EOL>return dag<EOL>

Deprecated - Use qiskit.compiler.transpile for transpiling from
    circuits to circuits.
    Transform a dag circuit into another dag circuit
    (transpile), through consecutive passes on the dag.

    Args:
        dag (DAGCircuit): dag circuit to transform via transpilation
        basis_gates (list[str]): list of basis gate names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): A graph of coupling::

            [
             [control0(int), target0(int)],
             [control1(int), target1(int)],
            ]

            eg. [[0, 2], [1, 2], [1, 3], [3, 4]}

        initial_layout (Layout or None): A layout object
        seed_mapper (int): random seed_mapper for the swap mapper
        pass_manager (PassManager): pass manager instance for the transpilation process
            If None, a default set of passes are run.
            Otherwise, the passes defined in it will run.
            If contains no passes in it, no dag transformations occur.

    Returns:
        DAGCircuit: transformed dag


return isinstance(self, TransformationPass)<EOL>

If the pass is a TransformationPass, that means that the pass can manipulate the DAG,
        but cannot modify the property set (but it can be read).


raise NotImplementedError<EOL>

Run a pass on the DAGCircuit. This is implemented by the pass developer.
Args:
    dag (DAGCircuit): the dag on which the pass is run.
Raises:
    NotImplementedError: when this is left unimplemented for a pass.


self._p2v = {}<EOL>self._v2p = {}<EOL>if input_dict is not None:<EOL><INDENT>if not isinstance(input_dict, dict):<EOL><INDENT>raise LayoutError("<STR_LIT>")<EOL><DEDENT>self.from_dict(input_dict)<EOL><DEDENT>

construct a Layout from a bijective dictionary, mapping
        virtual qubits to physical qubits


<EOL>if len(input_dict) >= <NUM_LIT:1>:<EOL><INDENT>key = list(input_dict.keys())[<NUM_LIT:0>]<EOL>value = input_dict[key]<EOL>if (isinstance(key, tuple) and  <EOL>len(key) == <NUM_LIT:2> and<EOL>isinstance(key[<NUM_LIT:0>], str) and<EOL>isinstance(key[<NUM_LIT:1>], int) and<EOL>isinstance(value, tuple) and<EOL>len(value) == <NUM_LIT:2> and<EOL>isinstance(key[<NUM_LIT:0>], str) and<EOL>isinstance(key[<NUM_LIT:1>], int)):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>" % (key + value),<EOL>DeprecationWarning)<EOL>qreg_names = {qubit[<NUM_LIT:0>] for qubit in input_dict.keys()}<EOL>qregs = {}<EOL>for qreg_name in qreg_names:<EOL><INDENT>qregs[qreg_name] = QuantumRegister(<EOL>max([qubit[<NUM_LIT:1>] for qubit in input_dict.keys() if qubit[<NUM_LIT:0>] == qreg_name]) + <NUM_LIT:1>,<EOL>qreg_name)<EOL><DEDENT>new_input_dict = {}<EOL>for key, value in input_dict.items():<EOL><INDENT>new_input_dict[value[<NUM_LIT:1>]] = (qregs[key[<NUM_LIT:0>]], key[<NUM_LIT:1>])<EOL><DEDENT>input_dict = new_input_dict<EOL><DEDENT><DEDENT>for key, value in input_dict.items():<EOL><INDENT>virtual, physical = Layout.order_based_on_type(key, value)<EOL>self._p2v[physical] = virtual<EOL>if virtual is None:<EOL><INDENT>continue<EOL><DEDENT>self._v2p[virtual] = physical<EOL><DEDENT>

Populates a Layout from a dictionary.
The dictionary must be a bijective mapping between
virtual qubits (tuple) and physical qubits (int).

Args:
    input_dict (dict):
        e.g.:
        {(QuantumRegister(3, 'qr'), 0): 0,
         (QuantumRegister(3, 'qr'), 1): 1,
         (QuantumRegister(3, 'qr'), 2): 2}

        Can be written more concisely as follows:

        virtual to physical:
            {qr[0]: 0,
             qr[1]: 1,
             qr[2]: 2}

        physical to virtual:
            {0: qr[0],
             1: qr[1],
             2: qr[2]}


layout_copy = type(self)()<EOL>layout_copy._p2v = self._p2v.copy()<EOL>layout_copy._v2p = self._v2p.copy()<EOL>return layout_copy<EOL>


layout = Layout()<EOL>for reg in regs:<EOL><INDENT>layout.add_register(reg)<EOL><DEDENT>return layout<EOL>

Creates a trivial ("one-to-one") Layout with the registers in `regs`.
Args:
    *regs (Registers): registers to include in the layout.
Returns:
    Layout: A layout with all the `regs` in the given order.


if type(left) is not type(right):<EOL><INDENT>raise LayoutError('<STR_LIT>')<EOL><DEDENT>temp = self[left]<EOL>self[left] = self[right]<EOL>self[right] = temp<EOL>

Swaps the map between left and right.
        Args:
            left (tuple or int): Item to swap with right.
            right (tuple or int): Item to swap with left.
        Raises:
            LayoutError: If left and right have not the same type.


super().__init__(*msg)<EOL>self.msg = '<STR_LIT:U+0020>'.join(msg)<EOL>


super().__init__()<EOL>self._property = property_to_check<EOL>

Args:
    property_to_check (str): The property to check if a fixed point was reached.


diagonal_1q_gates = (RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, U1Gate)<EOL>diagonal_2q_gates = (CzGate, CrzGate, Cu1Gate, RZZGate)<EOL>nodes_to_remove = set()<EOL>for measure in dag.op_nodes(Measure):<EOL><INDENT>predecessor = dag.quantum_predecessors(measure)[<NUM_LIT:0>]<EOL>if predecessor.type == '<STR_LIT>' and isinstance(predecessor.op, diagonal_1q_gates):<EOL><INDENT>nodes_to_remove.add(predecessor)<EOL><DEDENT>if predecessor.type == '<STR_LIT>' and isinstance(predecessor.op, diagonal_2q_gates):<EOL><INDENT>successors = dag.quantum_successors(predecessor)<EOL>if all([s.type == '<STR_LIT>' and isinstance(s.op, Measure) for s in successors]):<EOL><INDENT>nodes_to_remove.add(predecessor)<EOL><DEDENT><DEDENT><DEDENT>for node_to_remove in nodes_to_remove:<EOL><INDENT>dag.remove_op_node(node_to_remove)<EOL><DEDENT>return dag<EOL>

Return a new circuit that has been optimized.


resets = dag.op_nodes(Reset)<EOL>for reset in resets:<EOL><INDENT>predecessor = next(dag.predecessors(reset))<EOL>if predecessor.type == '<STR_LIT>':<EOL><INDENT>dag.remove_op_node(reset)<EOL><DEDENT><DEDENT>return dag<EOL>


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>

Choose a TrivialLayout.

Args:
    coupling_map (Coupling): directed graph representing a coupling map.

Raises:
    TranspilerError: if invalid options


sizes = [qr.size for qr in qregs.values()]<EOL>reg_idx = np.cumsum([<NUM_LIT:0>]+sizes)<EOL>regint = {}<EOL>for ind, qreg in enumerate(qregs.values()):<EOL><INDENT>regint[qreg] = ind<EOL><DEDENT>out = np.zeros(<NUM_LIT:2>*len(gates), dtype=np.int32)<EOL>for idx, gate in enumerate(gates):<EOL><INDENT>out[<NUM_LIT:2>*idx] = reg_idx[regint[gate[<NUM_LIT:0>][<NUM_LIT:0>]]]+gate[<NUM_LIT:0>][<NUM_LIT:1>]<EOL>out[<NUM_LIT:2>*idx+<NUM_LIT:1>] = reg_idx[regint[gate[<NUM_LIT:1>][<NUM_LIT:0>]]]+gate[<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT>return out<EOL>

Converts gate tuples into a nested list of integers.

    Args:
        gates (list): List of (QuantumRegister, int) pairs
                      representing gates.
        qregs (dict): List of )QuantumRegister, int) tuples.

    Returns:
        list: Nested list of integers for gates.


sizes = [qr.size for qr in qregs.values()]<EOL>reg_idx = np.cumsum([<NUM_LIT:0>]+sizes)<EOL>regint = {}<EOL>for ind, qreg in enumerate(qregs.values()):<EOL><INDENT>regint[qreg] = ind<EOL><DEDENT>out = np.zeros(len(items), dtype=np.int32)<EOL>for idx, val in enumerate(items):<EOL><INDENT>out[idx] = reg_idx[regint[val[<NUM_LIT:0>]]]+val[<NUM_LIT:1>]<EOL><DEDENT>return out<EOL>

Takes (QuantumRegister, int) tuples and converts
    them into an integer array.

    Args:
        items (list): List of tuples of (QuantumRegister, int)
                      to convert.
        qregs (dict): List of )QuantumRegister, int) tuples.
    Returns:
        ndarray: Array of integers.


reliab_store = {}<EOL>for hw_qubit in self.available_hw_qubits:<EOL><INDENT>reliab = <NUM_LIT:1><EOL>for n in self.prog_graph.neighbors(prog_qubit):<EOL><INDENT>if n in self.prog2hw:<EOL><INDENT>reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit]<EOL><DEDENT><DEDENT>reliab *= self.readout_errors[hw_qubit]<EOL>reliab_store[hw_qubit] = reliab<EOL><DEDENT>max_reliab = <NUM_LIT:0><EOL>best_hw_qubit = None<EOL>for hw_qubit in reliab_store:<EOL><INDENT>if reliab_store[hw_qubit] > max_reliab:<EOL><INDENT>max_reliab = reliab_store[hw_qubit]<EOL>best_hw_qubit = hw_qubit<EOL><DEDENT><DEDENT>return best_hw_qubit<EOL>

Select the best remaining hardware qubit for the next program qubit.


if self.layout is None:<EOL><INDENT>if self.property_set["<STR_LIT>"]:<EOL><INDENT>self.layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.layout = Layout.generate_trivial_layout(*dag.qregs.values())<EOL><DEDENT><DEDENT>self.property_set['<STR_LIT>'] = True<EOL>edges = self.coupling_map.get_edges()<EOL>for gate in dag.twoQ_gates():<EOL><INDENT>physical_q0 = self.layout[gate.qargs[<NUM_LIT:0>]]<EOL>physical_q1 = self.layout[gate.qargs[<NUM_LIT:1>]]<EOL>if isinstance(gate.op, (CXBase, CnotGate)) and (<EOL>physical_q0, physical_q1) not in edges:<EOL><INDENT>self.property_set['<STR_LIT>'] = False<EOL>return<EOL><DEDENT><DEDENT>

If `dag` is mapped and the direction is correct the property
`is_direction_mapped` is set to True (or to False otherwise).

Args:
    dag (DAGCircuit): DAG to check.


def __init__(self, coupling_map, initial_layout=None):

super().__init__()<EOL>self.layout = initial_layout<EOL>self.coupling_map = coupling_map<EOL>

Checks if the CNOTs in DAGCircuit are in the allowed direction with
respect to `coupling_map`.
Args:
    coupling_map (CouplingMap): Directed graph representing a coupling map.
    initial_layout (Layout): The initial layout of the DAG to analyze.


if dag.width() > self.coupling_map.size():<EOL><INDENT>raise TranspilerError("<STR_LIT>")<EOL><DEDENT>layerlist = list(dag.layers())<EOL>if self.initial_layout is None and self.property_set["<STR_LIT>"]:<EOL><INDENT>self.initial_layout = self.property_set["<STR_LIT>"]<EOL><DEDENT>if self.initial_layout is not None:<EOL><INDENT>virtual_qubits = self.initial_layout.get_virtual_bits()<EOL>self.initial_layout = {(v[<NUM_LIT:0>].name, v[<NUM_LIT:1>]): ('<STR_LIT:q>', self.initial_layout[v]) for v in<EOL>virtual_qubits}<EOL>device_register = QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>')<EOL>initial_layout = {(dag.qregs[k[<NUM_LIT:0>]], k[<NUM_LIT:1>]): (device_register, v[<NUM_LIT:1>])<EOL>for k, v in self.initial_layout.items()}<EOL>circ_qubits = dag.qubits()<EOL>coup_qubits = [(QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>'), wire) for wire in<EOL>self.coupling_map.physical_qubits]<EOL>qubit_subset = []<EOL>for k, v in initial_layout.items():<EOL><INDENT>qubit_subset.append(v)<EOL>if k not in circ_qubits:<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>" % (k[<NUM_LIT:0>].name, k[<NUM_LIT:1>]))<EOL><DEDENT>if v not in coup_qubits:<EOL><INDENT>raise TranspilerError("<STR_LIT>"<EOL>"<STR_LIT>" % (v[<NUM_LIT:0>].name, v[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>qubit_subset = [(QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>'), wire) for wire in<EOL>self.coupling_map.physical_qubits]<EOL>qubit_subset = qubit_subset[<NUM_LIT:0>:dag.width()]<EOL>initial_layout = {a: b for a, b in zip(dag.qubits(), qubit_subset)}<EOL><DEDENT>layout = initial_layout.copy()<EOL>dagcircuit_output = DAGCircuit()<EOL>dagcircuit_output.name = dag.name<EOL>dagcircuit_output.add_qreg(QuantumRegister(self.coupling_map.size(), "<STR_LIT:q>"))<EOL>for creg in dag.cregs.values():<EOL><INDENT>dagcircuit_output.add_creg(creg)<EOL><DEDENT>identity_wire_map = {}<EOL>q = QuantumRegister(self.coupling_map.size(), '<STR_LIT:q>')<EOL>for j in range(self.coupling_map.size()):<EOL><INDENT>identity_wire_map[(q, j)] = (q, j)<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>for j in range(creg.size):<EOL><INDENT>identity_wire_map[(creg, j)] = (creg, j)<EOL><DEDENT><DEDENT>first_layer = True  <EOL>for i, layer in enumerate(layerlist):<EOL><INDENT>success_flag, best_circ, best_d, best_layout, trivial_flag= self.layer_permutation(layer["<STR_LIT>"], layout, qubit_subset)<EOL>if not success_flag:<EOL><INDENT>serial_layerlist = list(layer["<STR_LIT>"].serial_layers())<EOL>for j, serial_layer in enumerate(serial_layerlist):<EOL><INDENT>success_flag, best_circ, best_d, best_layout, trivial_flag= self.layer_permutation(serial_layer["<STR_LIT>"], layout, qubit_subset)<EOL>if not success_flag:<EOL><INDENT>raise TranspilerError("<STR_LIT>" +<EOL>"<STR_LIT>" % (i, j))<EOL><DEDENT>if trivial_flag and first_layer:<EOL><INDENT>continue<EOL><DEDENT>layout = best_layout<EOL>dagcircuit_output.compose_back(<EOL>self.swap_mapper_layer_update(j,<EOL>first_layer,<EOL>best_layout,<EOL>best_d,<EOL>best_circ,<EOL>serial_layerlist),<EOL>identity_wire_map)<EOL>if first_layer:<EOL><INDENT>initial_layout = layout<EOL>first_layer = False<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>layout = best_layout<EOL>dagcircuit_output.compose_back(<EOL>self.swap_mapper_layer_update(i,<EOL>first_layer,<EOL>best_layout,<EOL>best_d,<EOL>best_circ,<EOL>layerlist),<EOL>identity_wire_map)<EOL>if first_layer:<EOL><INDENT>initial_layout = layout<EOL>first_layer = False<EOL><DEDENT><DEDENT><DEDENT>if first_layer:<EOL><INDENT>layout = initial_layout<EOL>for i, layer in enumerate(layerlist):<EOL><INDENT>dagcircuit_output.compose_back(layer["<STR_LIT>"], layout)<EOL><DEDENT><DEDENT>return dagcircuit_output<EOL>

Map a DAGCircuit onto a CouplingGraph using swap gates.

        Args:
            dag (DAGCircuit): input DAG circuit

        Returns:
            DAGCircuit: object containing a circuit equivalent to
            circuit_graph that respects couplings in coupling_map, and
            a layout dict mapping qubits of circuit_graph into qubits
            of coupling_map. The layout may differ from the initial_layout
            if the first layer of gates cannot be executed on the
            initial_layout.

        Raises:
            TranspilerError: if there was any error during the mapping or with the
                parameters.


<EOL>final_op_types = ['<STR_LIT>', '<STR_LIT>']<EOL>final_ops = []<EOL>for candidate_node in dag.named_nodes(*final_op_types):<EOL><INDENT>is_final_op = True<EOL>for _, child_successors in dag.bfs_successors(candidate_node):<EOL><INDENT>if any(suc.type == '<STR_LIT>' and suc.name not in final_op_types<EOL>for suc in child_successors):<EOL><INDENT>is_final_op = False<EOL>break<EOL><DEDENT><DEDENT>if is_final_op:<EOL><INDENT>final_ops.append(candidate_node)<EOL><DEDENT><DEDENT>if not final_ops:<EOL><INDENT>return dag<EOL><DEDENT>barrier_layer = DAGCircuit()<EOL>for qreg in dag.qregs.values():<EOL><INDENT>barrier_layer.add_qreg(qreg)<EOL><DEDENT>for creg in dag.cregs.values():<EOL><INDENT>barrier_layer.add_creg(creg)<EOL><DEDENT>final_qubits = set(final_op.qargs[<NUM_LIT:0>] for final_op in final_ops)<EOL>barrier_layer.apply_operation_back(<EOL>Barrier(len(final_qubits)), list(final_qubits), [])<EOL>ordered_final_nodes = [node for node in dag.topological_op_nodes()<EOL>if node in set(final_ops)]<EOL>for final_node in ordered_final_nodes:<EOL><INDENT>barrier_layer.apply_operation_back(final_node.op,<EOL>final_node.qargs,<EOL>final_node.cargs)<EOL><DEDENT>for final_op in final_ops:<EOL><INDENT>dag.remove_op_node(final_op)<EOL><DEDENT>dag.extend_back(barrier_layer)<EOL>adjacent_pass = MergeAdjacentBarriers()<EOL>return adjacent_pass.run(dag)<EOL>

Return a circuit with a barrier before last measurements.


if n_qubits == <NUM_LIT:1>:<EOL><INDENT>return np.array([<NUM_LIT:0>])<EOL><DEDENT>device_qubits = self.coupling_map.size()<EOL>cmap = np.asarray(self.coupling_map.get_edges())<EOL>data = np.ones_like(cmap[:, <NUM_LIT:0>])<EOL>sp_cmap = sp.coo_matrix((data, (cmap[:, <NUM_LIT:0>], cmap[:, <NUM_LIT:1>])),<EOL>shape=(device_qubits, device_qubits)).tocsr()<EOL>best = <NUM_LIT:0><EOL>best_map = None<EOL>for k in range(sp_cmap.shape[<NUM_LIT:0>]):<EOL><INDENT>bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,<EOL>return_predecessors=False)<EOL>connection_count = <NUM_LIT:0><EOL>sub_graph = []<EOL>for i in range(n_qubits):<EOL><INDENT>node_idx = bfs[i]<EOL>for j in range(sp_cmap.indptr[node_idx],<EOL>sp_cmap.indptr[node_idx + <NUM_LIT:1>]):<EOL><INDENT>node = sp_cmap.indices[j]<EOL>for counter in range(n_qubits):<EOL><INDENT>if node == bfs[counter]:<EOL><INDENT>connection_count += <NUM_LIT:1><EOL>sub_graph.append([node_idx, node])<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if connection_count > best:<EOL><INDENT>best = connection_count<EOL>best_map = bfs[<NUM_LIT:0>:n_qubits]<EOL>mapping = {}<EOL>for edge in range(best_map.shape[<NUM_LIT:0>]):<EOL><INDENT>mapping[best_map[edge]] = edge<EOL><DEDENT>new_cmap = [[mapping[c[<NUM_LIT:0>]], mapping[c[<NUM_LIT:1>]]] for c in sub_graph]<EOL>rows = [edge[<NUM_LIT:0>] for edge in new_cmap]<EOL>cols = [edge[<NUM_LIT:1>] for edge in new_cmap]<EOL>data = [<NUM_LIT:1>]*len(rows)<EOL>sp_sub_graph = sp.coo_matrix((data, (rows, cols)),<EOL>shape=(n_qubits, n_qubits)).tocsr()<EOL>perm = cs.reverse_cuthill_mckee(sp_sub_graph)<EOL>best_map = best_map[perm]<EOL><DEDENT><DEDENT>return best_map<EOL>

Computes the qubit mapping with the best connectivity.

        Args:
            n_qubits (int): Number of subset qubits to consider.

        Returns:
            ndarray: Array of qubits to use for best connectivity mapping.


device_qreg = QuantumRegister(len(layout.get_physical_bits()), '<STR_LIT:q>')<EOL>qreg_edge = [(device_qreg, i) for i in edge]<EOL>return [<EOL>DAGNode({'<STR_LIT>': SwapGate(), '<STR_LIT>': qreg_edge, '<STR_LIT>': [], '<STR_LIT:type>': '<STR_LIT>'})<EOL>]<EOL>

Generate list of ops to implement a SWAP gate along a coupling edge.


super().__init__()<EOL>self.coupling_map = coupling_map<EOL>self.initial_layout = initial_layout<EOL>self.requires.append(BarrierBeforeFinalMeasurements())<EOL>

Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
    coupling_map (CouplingMap): Directed graph represented a coupling map.
    initial_layout (Layout): initial layout of qubits in mapping


@staticmethod<EOL><INDENT>def compose_u3(theta1, phi1, lambda1, theta2, phi2, lambda2):<DEDENT>

<EOL>thetap, phip, lambdap = Optimize1qGates.yzy_to_zyz((lambda1 + phi2), theta1, theta2)<EOL>(theta, phi, lamb) = (thetap, phi1 + phip, lambda2 + lambdap)<EOL>return (theta, phi, lamb)<EOL>

Return a triple theta, phi, lambda for the product.

        u3(theta, phi, lambda)
           = u3(theta1, phi1, lambda1).u3(theta2, phi2, lambda2)
           = Rz(phi1).Ry(theta1).Rz(lambda1+phi2).Ry(theta2).Rz(lambda2)
           = Rz(phi1).Rz(phi').Ry(theta').Rz(lambda').Rz(lambda2)
           = u3(theta', phi1 + phi', lambda2 + lambda')

        Return theta, phi, lambda.


start = time.time()<EOL>self._number_of_qubits = experiment.header.n_qubits<EOL>self._validate_initial_unitary()<EOL>self._initialize_unitary()<EOL>for operation in experiment.instructions:<EOL><INDENT>if operation.name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>params = getattr(operation, '<STR_LIT>', None)<EOL>qubit = operation.qubits[<NUM_LIT:0>]<EOL>gate = single_gate_matrix(operation.name, params)<EOL>self._add_unitary_single(gate, qubit)<EOL><DEDENT>elif operation.name in ('<STR_LIT:id>', '<STR_LIT>'):<EOL><INDENT>pass<EOL><DEDENT>elif operation.name in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>qubit0 = operation.qubits[<NUM_LIT:0>]<EOL>qubit1 = operation.qubits[<NUM_LIT:1>]<EOL>gate = cx_gate_matrix()<EOL>self._add_unitary_two(gate, qubit0, qubit1)<EOL><DEDENT>elif operation.name == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>backend = self.name()<EOL>err_msg = '<STR_LIT>'<EOL>raise BasicAerError(err_msg.format(backend, operation.name))<EOL><DEDENT><DEDENT>data = {'<STR_LIT>': self._get_unitary()}<EOL>end = time.time()<EOL>return {'<STR_LIT:name>': experiment.header.name,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT:status>': '<STR_LIT>',<EOL>'<STR_LIT:success>': True,<EOL>'<STR_LIT>': (end - start),<EOL>'<STR_LIT>': experiment.header.as_dict()}<EOL>

Run an experiment (circuit) and return a single experiment result.

        Args:
            experiment (QobjExperiment): experiment from qobj experiments list

        Returns:
            dict: A result dictionary which looks something like::

                {
                "name": name of this experiment (obtained from qobj.experiment header)
                "seed": random seed used for simulation
                "shots": number of shots used in the simulation
                "data":
                    {
                    "unitary": [[[0.0, 0.0], [1.0, 0.0]],
                                [[1.0, 0.0], [0.0, 0.0]]]
                    },
                "status": status string for the simulation
                "success": boolean
                "time taken": simulation time of this single experiment
                }

        Raises:
            BasicAerError: if the number of qubits in the circuit is greater than 24.
            Note that the practical qubit limit is much lower than 24.


unitary = np.reshape(self._unitary, <NUM_LIT:2> * [<NUM_LIT:2> ** self._number_of_qubits])<EOL>unitary = np.stack((unitary.real, unitary.imag), axis=-<NUM_LIT:1>)<EOL>unitary[abs(unitary) < self._chop_threshold] = <NUM_LIT:0.0><EOL>return unitary<EOL>

Return the current unitary in JSON Result spec format


def _add_qasm_measure(self, qubit, cmembit, cregbit=None):

<EOL>outcome, probability = self._get_measure_outcome(qubit)<EOL>membit = <NUM_LIT:1> << cmembit<EOL>self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit)<EOL>if cregbit is not None:<EOL><INDENT>regbit = <NUM_LIT:1> << cregbit<EOL>self._classical_register =(self._classical_register & (~regbit)) | (int(outcome) << cregbit)<EOL><DEDENT>if outcome == '<STR_LIT:0>':<EOL><INDENT>update_diag = [[<NUM_LIT:1> / np.sqrt(probability), <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>update_diag = [[<NUM_LIT:0>, <NUM_LIT:0>], [<NUM_LIT:0>, <NUM_LIT:1> / np.sqrt(probability)]]<EOL><DEDENT>self._add_unitary_single(update_diag, qubit)<EOL>

Apply a measure instruction to a qubit.

        Args:
            qubit (int): qubit is the qubit measured.
            cmembit (int): is the classical memory bit to store outcome in.
            cregbit (int, optional): is the classical register bit to store outcome in.


def run(self, qobj, backend_options=None):

self._set_options(qobj_config=qobj.config,<EOL>backend_options=backend_options)<EOL>job_id = str(uuid.uuid4())<EOL>job = BasicAerJob(self, job_id, self._run_job, qobj)<EOL>job.submit()<EOL>return job<EOL>

Run qobj asynchronously.

        Args:
            qobj (Qobj): payload of the experiment
            backend_options (dict): backend options

        Returns:
            BasicAerJob: derived from BaseJob

        Additional Information:
            backend_options: Is a dict of options for the backend. It may contain
                * "initial_statevector": vector_like

            The "initial_statevector" option specifies a custom initial
            initial statevector for the simulator to be used instead of the all
            zero state. This size of this vector must be correct for the number
            of qubits in all experiments in the qobj.

            Example::

                backend_options = {
                    "initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
                }


def _add_unitary_single(self, gate, qubit):

<EOL>indexes = einsum_vecmul_index([qubit], self._number_of_qubits)<EOL>gate_tensor = np.array(gate, dtype=complex)<EOL>self._statevector = np.einsum(indexes, gate_tensor,<EOL>self._statevector,<EOL>dtype=complex,<EOL>casting='<STR_LIT>')<EOL>

Apply an arbitrary 1-qubit unitary matrix.

        Args:
            gate (matrix_like): a single qubit gate matrix
            qubit (int): the qubit to apply gate to


def _set_options(self, qobj_config=None, backend_options=None):

<EOL>self._initial_statevector = self.DEFAULT_OPTIONS["<STR_LIT>"]<EOL>self._chop_threshold = self.DEFAULT_OPTIONS["<STR_LIT>"]<EOL>if backend_options is None:<EOL><INDENT>backend_options = {}<EOL><DEDENT>if '<STR_LIT>' in backend_options:<EOL><INDENT>self._initial_statevector = np.array(backend_options['<STR_LIT>'],<EOL>dtype=complex)<EOL><DEDENT>elif hasattr(qobj_config, '<STR_LIT>'):<EOL><INDENT>self._initial_statevector = np.array(qobj_config.initial_statevector,<EOL>dtype=complex)<EOL><DEDENT>if self._initial_statevector is not None:<EOL><INDENT>norm = np.linalg.norm(self._initial_statevector)<EOL>if round(norm, <NUM_LIT:12>) != <NUM_LIT:1>:<EOL><INDENT>raise BasicAerError('<STR_LIT>' +<EOL>'<STR_LIT>'.format(norm))<EOL><DEDENT><DEDENT>if '<STR_LIT>' in backend_options:<EOL><INDENT>self._chop_threshold = backend_options['<STR_LIT>']<EOL><DEDENT>elif hasattr(qobj_config, '<STR_LIT>'):<EOL><INDENT>self._chop_threshold = qobj_config.chop_threshold<EOL><DEDENT>

Set the backend options for all experiments in a qobj


n_qubits = qobj.config.n_qubits<EOL>max_qubits = self.configuration().n_qubits<EOL>if n_qubits > max_qubits:<EOL><INDENT>raise BasicAerError('<STR_LIT>'.format(n_qubits) +<EOL>'<STR_LIT>'.format(max_qubits) +<EOL>'<STR_LIT>'.format(self.name()))<EOL><DEDENT>if qobj.config.shots != <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>',<EOL>self.name())<EOL>qobj.config.shots = <NUM_LIT:1><EOL><DEDENT>for experiment in qobj.experiments:<EOL><INDENT>name = experiment.header.name<EOL>if getattr(experiment.config, '<STR_LIT>', <NUM_LIT:1>) != <NUM_LIT:1>:<EOL><INDENT>logger.info('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>self.name(), name)<EOL>experiment.config.shots = <NUM_LIT:1><EOL><DEDENT><DEDENT>

Semantic validations of the qobj which cannot be done via schemas.
        Some of these may later move to backend schemas.

        1. No shots
        2. No measurements in the middle


<EOL>(theta, phi, lam) = map(float, single_gate_params(gate, params))<EOL>return np.array([[np.cos(theta / <NUM_LIT:2>),<EOL>-np.exp(<NUM_LIT> * lam) * np.sin(theta / <NUM_LIT:2>)],<EOL>[np.exp(<NUM_LIT> * phi) * np.sin(theta / <NUM_LIT:2>),<EOL>np.exp(<NUM_LIT> * phi + <NUM_LIT> * lam) * np.cos(theta / <NUM_LIT:2>)]])<EOL>

Get the matrix for a single qubit.

    Args:
        gate(str): the single qubit gate name
        params(list): the operation parameters op['params']
    Returns:
        array: A numpy array representing the matrix


return np.array([[<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>],<EOL>[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>],<EOL>[<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>]], dtype=complex)<EOL>

Get the matrix for a controlled-NOT gate.


super().__init__(*message)<EOL>self.message = '<STR_LIT:U+0020>'.join(message)<EOL>


return self._future.result(timeout=timeout)<EOL>

Get job result. The behavior is the same as the underlying
        concurrent Future objects,

        https://docs.python.org/3/library/concurrent.futures.html#future-objects

        Args:
            timeout (float): number of seconds to wait for results.

        Returns:
            qiskit.Result: Result object

        Raises:
            concurrent.futures.TimeoutError: if timeout occurred.
            concurrent.futures.CancelledError: if job cancelled before completed.


if self._future is not None:<EOL><INDENT>raise JobError("<STR_LIT>")<EOL><DEDENT>validate_qobj_against_schema(self._qobj)<EOL>self._future = self._executor.submit(self._fn, self._job_id, self._qobj)<EOL>

Submit the job to the backend for execution.

        Raises:
            QobjValidationError: if the JSON serialization of the Qobj passed
            during construction does not validate against the Qobj schema.

            JobError: if trying to re-submit the job.


<EOL>try:<EOL><INDENT>backend_instance = backend_cls(provider=self)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise QiskitError('<STR_LIT>' %<EOL>(backend_cls, err))<EOL><DEDENT>return backend_instance<EOL>

Return an instance of a backend from its class.

Args:
    backend_cls (class): Backend class.
Returns:
    BaseBackend: a backend instance.
Raises:
    QiskitError: if the backend could not be instantiated.


pass<EOL>


@abstractmethod<EOL><INDENT>def __init__(self, configuration, provider=None):<DEDENT>

self._configuration = configuration<EOL>self._provider = provider<EOL>

Base class for backends.

        This method should initialize the module and its configuration, and
        raise an exception if a component of the module is
        not available.

        Args:
            configuration (BackendConfiguration): backend configuration
            provider (BaseProvider): provider responsible for this backend

        Raises:
            FileNotFoundError if backend executable is not available.
            QiskitError: if there is no name in the configuration


return BackendStatus(backend_name=self.name(),<EOL>backend_version=__version__,<EOL>operational=True,<EOL>pending_jobs=<NUM_LIT:0>,<EOL>status_msg='<STR_LIT>')<EOL>

Return backend status.

        Returns:
            BackendStatus: the status of the backend.


return "<STR_LIT>".format(self.__class__.__name__,<EOL>self.name(),<EOL>self._provider)<EOL>

Official string representation of a Backend.

        Note that, by Qiskit convention, it is consciously *not* a fully valid
        Python expression. Subclasses should provide 'a string of the form
        <...some useful description...>'. [0]

        [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__


return self._provider<EOL>

Return the backend Provider.

        Returns:
            BaseProvider: the Provider responsible for the backend.


def _deserialize(self, value, attr, data):

try:<EOL><INDENT>return super()._deserialize(value, attr, data)<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>if '<STR_LIT>' in ex.messages[<NUM_LIT:0>]:<EOL><INDENT>ex.messages[<NUM_LIT:0>] = '<STR_LIT>'<EOL><DEDENT>raise<EOL><DEDENT>

Override ``_deserialize`` for customizing the exception raised.


def from_dict_selector(self, choices, *args, **kwargs):

raise NotImplementedError<EOL>

Return an schema in ``choices`` for deserialization.


def check_type(self, value, attr, data):

if self.many and not is_collection(value):<EOL><INDENT>raise self._not_expected_type(<EOL>value, Iterable, fields=[self], field_names=attr, data=data)<EOL><DEDENT>_check_type = super().check_type<EOL>errors = []<EOL>values = value if self.many else [value]<EOL>for idx, v in enumerate(values):<EOL><INDENT>try:<EOL><INDENT>_check_type(v, idx, values)<EOL><DEDENT>except ValidationError as err:<EOL><INDENT>errors.append(err.messages)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>errors = errors if self.many else errors[<NUM_LIT:0>]<EOL>raise ValidationError(errors)<EOL><DEDENT>return value<EOL>

Validate if the value is of the type of the schema's model.

        Assumes the nested schema is a ``BaseSchema``.


try:<EOL><INDENT>data, _ = self.schema.dump(self)<EOL><DEDENT>except ValidationError as ex:<EOL><INDENT>raise ModelValidationError(<EOL>ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None<EOL><DEDENT>return data<EOL>

Serialize the model into a Python dict of simple types.

        Note that this method requires that the model is bound with
        ``@bind_schema``.


return item in self.__dict__<EOL>

Custom implementation of membership test.

        Implement the ``__contains__`` method for catering to the common case
        of finding out if a model contains a certain key (``key in model``).


return _SchemaBinder(schema)<EOL>

Class decorator for adding schema validation to its instances.

    Instances of the decorated class are automatically validated after
    instantiation and they are augmented to allow further validations with the
    private method ``_validate()``.

    The decorator also adds the class attribute ``schema`` with the schema used
    for validation, along with a class attribute ``shallow_schema`` used for
    validation during instantiation.

    It also allows using the ``to_dict`` and ``from_dict`` in the model class,
    with perform serialization/deserialization to/from simple Python objects
    respectively.

    The same schema cannot be bound more than once. If you need to reuse a
    schema for a different class, create a new schema subclassing the one you
    want to reuse and leave the new empty::

        class MySchema(BaseSchema):
            title = String()

        class AnotherSchema(MySchema):
            pass

        @bind_schema(MySchema):
        class MyModel(BaseModel):
            pass

        @bind_schema(AnotherSchema):
        class AnotherModel(BaseModel):
            pass

    Raises:
        ValueError: when trying to bind the same schema more than once.

    Return:
        type: the same class with validation capabilities.


expected_types = self._expected_types()<EOL>if not isinstance(value, expected_types):<EOL><INDENT>raise self._not_expected_type(<EOL>value, expected_types, fields=[self], field_names=attr, data=data)<EOL><DEDENT>return value<EOL>

Validates a value against the correct type of the field.

        It calls ``_expected_types`` to get a list of valid types.

        Subclasses can do one of the following:

            1. They can override the ``valid_types`` property with a tuple with
            the expected types for this field.

            2. They can override the ``_expected_types`` method to return a
            tuple of expected types for the field.

            3. They can change ``check_type`` completely to customize
            validation.

        This method or the overrides must return the ``value`` parameter
        untouched.


def _get_validator(name, schema=None, check_schema=True,<EOL>validator_class=None, **validator_kwargs):

if schema is None:<EOL><INDENT>try:<EOL><INDENT>schema = _SCHEMAS[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise SchemaValidationError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if name not in _VALIDATORS:<EOL><INDENT>if validator_class is None:<EOL><INDENT>validator_class = jsonschema.validators.validator_for(schema)<EOL><DEDENT>_VALIDATORS[name] = validator_class(schema, **validator_kwargs)<EOL><DEDENT>validator = _VALIDATORS[name]<EOL>if check_schema:<EOL><INDENT>validator.check_schema(schema)<EOL><DEDENT>return validator<EOL>

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 provided searches for schema
            in `_SCHEMAS`.
        check_schema (bool): Verify schema is valid.
        validator_class (jsonschema.IValidator): jsonschema IValidator instance.
            Default behavior is to determine this from the schema `$schema`
            field.
        **validator_kwargs (dict): Additional keyword arguments for validator.

    Return:
        jsonschema.IValidator: Validator for JSON schema.

    Raises:
        SchemaValidationError: Raised if validation fails.


<EOL>for children in obj.children:<EOL><INDENT>self.verify_declared_bit(children)<EOL><DEDENT>


program[<NUM_LIT:0>] = node.CustomUnitary([program[<NUM_LIT:1>], program[<NUM_LIT:4>]])<EOL>self.verify_as_gate(program[<NUM_LIT:1>], program[<NUM_LIT:4>])<EOL>self.verify_reg_list(program[<NUM_LIT:4>], '<STR_LIT>')<EOL>self.verify_distinct([program[<NUM_LIT:4>]])<EOL>


def verify_reg_list(self, obj, object_type):

<EOL>for children in obj.children:<EOL><INDENT>self.verify_reg(children, object_type)<EOL><DEDENT>


self.current_symtab = self.symbols.pop()<EOL>


program[<NUM_LIT:0>] = node.CustomUnitary([program[<NUM_LIT:1>], program[<NUM_LIT:3>], program[<NUM_LIT:5>]])<EOL>self.verify_as_gate(program[<NUM_LIT:1>], program[<NUM_LIT:5>], arglist=program[<NUM_LIT:3>])<EOL>self.verify_bit_list(program[<NUM_LIT:5>])<EOL>self.verify_exp_list(program[<NUM_LIT:3>])<EOL>self.verify_distinct([program[<NUM_LIT:5>]])<EOL>

gate_op : id '(' exp_list ')' id_list ';'


program[<NUM_LIT:0>] = node.Barrier([program[<NUM_LIT:2>]])<EOL>self.verify_bit_list(program[<NUM_LIT:2>])<EOL>self.verify_distinct([program[<NUM_LIT:2>]])<EOL>


if token is None:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>last_cr = input_.rfind('<STR_LIT:\n>', <NUM_LIT:0>, token.lexpos)<EOL>if last_cr < <NUM_LIT:0>:<EOL><INDENT>last_cr = <NUM_LIT:0><EOL><DEDENT>column = (token.lexpos - last_cr) + <NUM_LIT:1><EOL>return column<EOL>

Compute the column.

        Input is the input text string.
        token is a token instance.


if id_node.type != "<STR_LIT:id>":<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>bit_list = []<EOL>try:<EOL><INDENT>g_sym = self.current_symtab[id_node.name]<EOL><DEDENT>except KeyError:<EOL><INDENT>g_sym = self.global_symtab[id_node.name]<EOL><DEDENT>if g_sym.type == "<STR_LIT>" or g_sym.type == "<STR_LIT>":<EOL><INDENT>for idx in range(g_sym.index):<EOL><INDENT>bit_list.append((id_node.name, idx))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>bit_list.append((id_node.name, -<NUM_LIT:1>))<EOL><DEDENT>return bit_list<EOL>

Return a list of (name, index) tuples for this id node.


raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>"<EOL>+ str(program[<NUM_LIT:2>].value) + "<STR_LIT:'>")<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:3>])<EOL>self.update_symtab(program[<NUM_LIT:3>])<EOL>


program[<NUM_LIT:0>] = program[<NUM_LIT:1>]<EOL>program[<NUM_LIT:0>].add_child(program[<NUM_LIT:3>])<EOL>


raise QasmError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL>


raise QasmError("<STR_LIT>")<EOL>


try:<EOL><INDENT>while True:<EOL><INDENT>token = self.lexer.token()<EOL>if not token:<EOL><INDENT>break<EOL><DEDENT>yield token<EOL><DEDENT><DEDENT>except QasmError as e:<EOL><INDENT>print('<STR_LIT>', e.msg)<EOL><DEDENT>


program[<NUM_LIT:0>] = node.UniversalUnitary([program[<NUM_LIT:3>], program[<NUM_LIT:5>]])<EOL>self.verify_reg(program[<NUM_LIT:5>], '<STR_LIT>')<EOL>self.verify_exp_list(program[<NUM_LIT:3>])<EOL>


return self._filename<EOL>


def __init__(self, filename=None, data=None):

if filename is None and data is None:<EOL><INDENT>raise QasmError("<STR_LIT>")<EOL><DEDENT>if filename is not None and data is not None:<EOL><INDENT>raise QasmError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._filename = filename<EOL>self._data = data<EOL>


super().__init__('<STR_LIT>', children, None)<EOL>


def latex(self, prec=<NUM_LIT:15>, nested_scope=None):

<EOL>return "<STR_LIT>" % self.value<EOL>

Return the corresponding math mode latex string.


return "<STR_LIT:(>" + self.children[<NUM_LIT:1>].qasm(prec) + self.children[<NUM_LIT:0>].value +self.children[<NUM_LIT:2>].qasm(prec) + "<STR_LIT:)>"<EOL>

Return the corresponding OPENQASM string.


<EOL>return sympy.latex(self.sym(nested_scope))<EOL>


operation = self.children[<NUM_LIT:0>].operation()<EOL>lhs = self.children[<NUM_LIT:1>].real(nested_scope)<EOL>rhs = self.children[<NUM_LIT:2>].real(nested_scope)<EOL>return operation(lhs, rhs)<EOL>

Return the correspond floating point number.


<EOL>return self.value<EOL>


super().__init__('<STR_LIT>', None, None)<EOL>self.value = operation<EOL>


super().__init__('<STR_LIT>', children, None)<EOL>self.id = children[<NUM_LIT:0>]<EOL>self.name = self.id.name<EOL>self.line = self.id.line<EOL>self.file = self.id.file<EOL>if len(children) == <NUM_LIT:3>:<EOL><INDENT>self.arguments = children[<NUM_LIT:1>]<EOL>self.bitlist = children[<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>self.arguments = None<EOL>self.bitlist = children[<NUM_LIT:1>]<EOL><DEDENT>


string = "<STR_LIT>"<EOL>for children in self.children:<EOL><INDENT>string += children.qasm(prec) + "<STR_LIT:\n>"<EOL><DEDENT>return string<EOL>


return "<STR_LIT>" + self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT>" +self.children[<NUM_LIT:1>].qasm(prec) + "<STR_LIT:;>"<EOL>


return "<STR_LIT:U+002C>".join([self.children[j].qasm(prec)<EOL>for j in range(self.size())])<EOL>


return "<STR_LIT>" + self.children[<NUM_LIT:0>].qasm(prec) + "<STR_LIT>"+ str(self.children[<NUM_LIT:1>].value) + "<STR_LIT>" +self.children[<NUM_LIT:2>].qasm(prec)<EOL>


if not nested_scope:<EOL><INDENT>return "<STR_LIT>" + self.name + "<STR_LIT:}>"<EOL><DEDENT>else:<EOL><INDENT>if self.name not in nested_scope[-<NUM_LIT:1>]:<EOL><INDENT>raise NodeException("<STR_LIT>",<EOL>"<STR_LIT>" % self.name,<EOL>"<STR_LIT>" % self.line,<EOL>"<STR_LIT>" % self.file)<EOL><DEDENT>else:<EOL><INDENT>return nested_scope[-<NUM_LIT:1>][self.name].latex(prec,<EOL>nested_scope[<NUM_LIT:0>:-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>

Return the correspond math mode latex string.


<EOL>return self.name<EOL>


return "<STR_LIT>" % (self.majorversion, self.minorversion)<EOL>


return len(self.children)<EOL>


if self.arguments:<EOL><INDENT>return self.arguments.size()<EOL><DEDENT>return <NUM_LIT:0><EOL>

Return the number of parameter expressions.


return self.bitlist.size()<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT>')<EOL>self.children[<NUM_LIT:0>].to_string(indent + <NUM_LIT:3>)<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>print(ind, '<STR_LIT>', self.value)<EOL>


ind = indent * '<STR_LIT:U+0020>'<EOL>if self.root:<EOL><INDENT>print(ind, self.type, '<STR_LIT>', self.root)<EOL><DEDENT>else:<EOL><INDENT>print(ind, self.type)<EOL><DEDENT>indent = indent + <NUM_LIT:3><EOL>ind = indent * '<STR_LIT:U+0020>'<EOL>for children in self.children:<EOL><INDENT>if children is None:<EOL><INDENT>print("<STR_LIT>", type(self))<EOL>print(self.children)<EOL><DEDENT>if isinstance(children, str):<EOL><INDENT>print(ind, children)<EOL><DEDENT>elif isinstance(children, int):<EOL><INDENT>print(ind, str(children))<EOL><DEDENT>elif isinstance(children, float):<EOL><INDENT>print(ind, str(children))<EOL><DEDENT>else:<EOL><INDENT>children.to_string(indent)<EOL><DEDENT><DEDENT>


<EOL>return self.name + "<STR_LIT>" % self.index<EOL>


return t<EOL>


t.type = self.reserved.get(t.value, '<STR_LIT>')<EOL>if t.type == '<STR_LIT>':<EOL><INDENT>t.value = node.Id(t.value, self.lineno, self.filename)<EOL><DEDENT>return t<EOL>


t.value = int(t.value)<EOL>return t<EOL>


super().__init__(*msg)<EOL>self.msg = '<STR_LIT:U+0020>'.join(msg)<EOL>


command_dict = {<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': shift+instruction.start_time,<EOL>'<STR_LIT>': instruction.channels[<NUM_LIT:0>].name,<EOL>'<STR_LIT>': instruction.command.value<EOL>}<EOL>return self._qobj_model(**command_dict)<EOL>

Return converted `PersistentValueInstruction`.

        Args:
            shift(int): Offset time.
            instruction (PersistentValueInstruction): persistent value instruction.
        Returns:
            dict: Dictionary of required parameters.


try:<EOL><INDENT>return self._bound_instructions[type(instruction)]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise PulseError('<STR_LIT>' % instruction)<EOL><DEDENT>


try:<EOL><INDENT>_m_los = self.default_meas_los.copy()<EOL><DEDENT>except KeyError:<EOL><INDENT>raise PulseError('<STR_LIT>')<EOL><DEDENT>for channel, lo_freq in user_lo_config.meas_lo_dict().items():<EOL><INDENT>_m_los[channel.index] = lo_freq<EOL><DEDENT>if _m_los == self.default_meas_los:<EOL><INDENT>return None<EOL><DEDENT>return _m_los<EOL>

Embed default meas LO frequencies from backend and format them to list object.
        If configured lo frequency is the same as default, this method returns `None`.

        Args:
            user_lo_config (LoConfig): A dictionary of LOs to format.

        Returns:
            list: A list of meas LOs.

        Raises:
            PulseError: when LO frequencies are missing.


warnings.warn("<STR_LIT>", DeprecationWarning, stacklevel=<NUM_LIT:2>)<EOL>return maybe_single(list(iterable))<EOL>

Given an iterable, return the items as a list. If the iterable contains
exactly one item, return that item. Correlary function to always_iterable.


base_types = six.text_type, bytes, collections.abc.Mapping<EOL>return more_itertools.always_iterable(item, base_type=base_types)<EOL>

Given an object, always return an iterable. If the item is not
already iterable, return a tuple containing only the item. If item is
None, an empty iterable is returned.

>>> always_iterable([1,2,3])
<list_iterator...>
>>> always_iterable('foo')
<tuple_iterator...>
>>> always_iterable(None)
<tuple_iterator...>
>>> always_iterable(range(10))
<range_iterator...>
>>> def _test_func(): yield "I'm iterable"
>>> print(next(always_iterable(_test_func())))
I'm iterable

Although mappings are iterable, treat each like a singleton, as
it's more like an object than a sequence.

>>> next(always_iterable(dict(a=1)))
{'a': 1}


items = iter(iterable)<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>yield next(items)<EOL>next(items)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Yield every other item from the iterable

>>> ' '.join(every_other('abcdefg'))
'a c e g'


iterset = [iter]<EOL>while len(iterset) < n:<EOL><INDENT>iterset[-<NUM_LIT:1>:] = itertools.tee(iterset[-<NUM_LIT:1>])<EOL>next(iterset[-<NUM_LIT:1>], None)<EOL><DEDENT>return six.moves.zip(*iterset)<EOL>

Like pairwise, except returns n-tuples of adjacent items.
s -> (s0,s1,...,sn), (s1,s2,...,s(n+1)), ...


for item in iterable:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return item<EOL><DEDENT>except NameError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Return the last item from the iterable, discarding the rest.

>>> last(range(20))
19
>>> last([])
Traceback (most recent call last):
...
ValueError: Iterable contains no items


key = kwargs.pop('<STR_LIT:key>', lambda x: x)<EOL>assert not kwargs<EOL>zipped = more_itertools.collate(*iterables, key=key)<EOL>grouped = itertools.groupby(zipped, key=key)<EOL>groups = (<EOL>tuple(g)<EOL>for k, g in grouped<EOL>)<EOL>def has_dupes(group):<EOL><INDENT>return len(group) > <NUM_LIT:1><EOL><DEDENT>return filter(has_dupes, groups)<EOL>

Yield duplicate items from any number of sorted iterables of items

>>> items_a = [1, 2, 3]
>>> items_b = [0, 3, 4, 5, 6]
>>> list(duplicates(items_a, items_b))
[(3, 3)]

It won't behave as you expect if the iterables aren't ordered

>>> items_b.append(1)
>>> list(duplicates(items_a, items_b))
[(3, 3)]
>>> list(duplicates(items_a, sorted(items_b)))
[(1, 1), (3, 3)]

This function is most interesting when it's operating on a key
of more complex objects.

>>> items_a = [dict(email='joe@example.com', id=1)]
>>> items_b = [dict(email='joe@example.com', id=2), dict(email='other')]
>>> dupe, = duplicates(items_a, items_b, key=operator.itemgetter('email'))
>>> dupe[0]['email'] == dupe[1]['email'] == 'joe@example.com'
True
>>> dupe[0]['id']
1
>>> dupe[1]['id']
2


return itertools.islice(iterable, <NUM_LIT:1>, None)<EOL>

Skip the first element of an iterable

>>> tuple(skip_first(range(10)))
(1, 2, 3, 4, 5, 6, 7, 8, 9)


while dict:<EOL><INDENT>prev_key = next(iter(dict))<EOL>yield prev_key, dict.pop(prev_key)<EOL><DEDENT>

Iterate over items in the dict, yielding the first one, but allowing
it to be mutated during the process.
>>> d = dict(a=1)
>>> it = _mutable_iter(d)
>>> next(it)
('a', 1)
>>> d
{}
>>> d.update(b=2)
>>> list(it)
[('b', 2)]


return itertools.chain.from_iterable(six.moves.map(<EOL>every_other, six.moves.map(<EOL>operator.itemgetter(<NUM_LIT:1>),<EOL>itertools.groupby(iterable, key)<EOL>)))<EOL>

Given an iterable with items that may come in as sequential duplicates,
remove those duplicates.

Unlike unique_justseen, this function does not remove triplicates.

>>> ' '.join(remove_duplicates('abcaabbccaaabbbcccbcbc'))
'a b c a b c a a b b c c b c b c'
>>> ' '.join(remove_duplicates('aaaabbbbb'))
'a a b b b'


return list(map(list, map(reversed, lists)))<EOL>


if isinstance(upload_sets, UploadSet):<EOL><INDENT>upload_sets = (upload_sets,)<EOL><DEDENT>if not hasattr(app, '<STR_LIT>'):<EOL><INDENT>app.upload_set_config = {}<EOL><DEDENT>set_config = app.upload_set_config<EOL>defaults = dict(dest=app.config.get('<STR_LIT>'),<EOL>url=app.config.get('<STR_LIT>'))<EOL>for uset in upload_sets:<EOL><INDENT>config = config_for_set(uset, app, defaults)<EOL>set_config[uset.name] = config<EOL><DEDENT>should_serve = any(s.base_url is None for s in set_config.values())<EOL>if '<STR_LIT>' not in app.blueprints and should_serve:<EOL><INDENT>app.register_blueprint(uploads_mod)<EOL><DEDENT>

Call this after the app has been configured. It will go through all the
upload sets, get their configuration, and store the configuration on the
app. It will also register the uploads module if it hasn't been set. This
can be called multiple times with different upload sets.

.. versionchanged:: 0.1.3
   The uploads module/blueprint will only be registered if it is needed
   to serve the upload sets.

:param app: The `~flask.Flask` instance to get the configuration from.
:param upload_sets: The `UploadSet` instances to configure.


def save(self, storage, folder=None, name=None):

if not isinstance(storage, FileStorage):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if folder is None and name is not None and "<STR_LIT:/>" in name:<EOL><INDENT>folder, name = os.path.split(name)<EOL><DEDENT>basename = self.get_basename(storage.filename)<EOL>if name:<EOL><INDENT>if name.endswith('<STR_LIT:.>'):<EOL><INDENT>basename = name + extension(basename)<EOL><DEDENT>else:<EOL><INDENT>basename = name<EOL><DEDENT><DEDENT>if not self.file_allowed(storage, basename):<EOL><INDENT>raise UploadNotAllowed()<EOL><DEDENT>if folder:<EOL><INDENT>target_folder = os.path.join(self.config.destination, folder)<EOL><DEDENT>else:<EOL><INDENT>target_folder = self.config.destination<EOL><DEDENT>if not os.path.exists(target_folder):<EOL><INDENT>os.makedirs(target_folder)<EOL><DEDENT>if os.path.exists(os.path.join(target_folder, basename)):<EOL><INDENT>basename = self.resolve_conflict(target_folder, basename)<EOL><DEDENT>target = os.path.join(target_folder, basename)<EOL>storage.save(target)<EOL>if folder:<EOL><INDENT>return posixpath.join(folder, basename)<EOL><DEDENT>else:<EOL><INDENT>return basename<EOL><DEDENT>

This saves a `werkzeug.FileStorage` into this upload set. If the
upload is not allowed, an `UploadNotAllowed` error will be raised.
Otherwise, the file will be saved and its name (including the folder)
will be returned.

:param storage: The uploaded file to save.
:param folder: The subfolder within the upload set to save to.
:param name: The name to save the file as. If it ends with a dot, the
             file's extension will be appended to the end. (If you
             are using `name`, you can include the folder in the
             `name` instead of explicitly using `folder`, i.e.
             ``uset.save(file, name="someguy/photo_123.")``


if folder is not None:<EOL><INDENT>target_folder = os.path.join(self.config.destination, folder)<EOL><DEDENT>else:<EOL><INDENT>target_folder = self.config.destination<EOL><DEDENT>return os.path.join(target_folder, filename)<EOL>

This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.

:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
               to save to.


def file_allowed(self, storage, basename):

return self.extension_allowed(extension(basename))<EOL>

This tells whether a file is allowed. It should return `True` if the
given `werkzeug.FileStorage` object can be saved with the given
basename, and `False` if it can't. The default implementation just
checks the extension, so you can override this if you want.

:param storage: The `werkzeug.FileStorage` to check.
:param basename: The basename it will be saved under.


def patch_request_class(app, size=<NUM_LIT:64> * <NUM_LIT> * <NUM_LIT>):

if size is None:<EOL><INDENT>if isinstance(app.request_class.__dict__['<STR_LIT>'],<EOL>property):<EOL><INDENT>return<EOL><DEDENT>size = app.config.get('<STR_LIT>')<EOL><DEDENT>reqclass = app.request_class<EOL>patched = type(reqclass.__name__, (reqclass,),<EOL>{'<STR_LIT>': size})<EOL>app.request_class = patched<EOL>

By default, Flask will accept uploads to an arbitrary size. While Werkzeug
switches uploads from memory to a temporary file when they hit 500 KiB,
it's still possible for someone to overload your disk space with a
gigantic file.

This patches the app's request class's
`~werkzeug.BaseRequest.max_content_length` attribute so that any upload
larger than the given size is rejected with an HTTP error.

.. note::

   In Flask 0.6, you can do this by setting the `MAX_CONTENT_LENGTH`
   setting, without patching the request class. To emulate this behavior,
   you can pass `None` as the size (you must pass it explicitly). That is
   the best way to call this function, as it won't break the Flask 0.6
   functionality if it exists.

.. versionchanged:: 0.1.1

:param app: The app to patch the request class of.
:param size: The maximum size to accept, in bytes. The default is 64 MiB.
             If it is `None`, the app's `MAX_CONTENT_LENGTH` configuration
             setting will be used to patch.


return ((ext in self.config.allow) or<EOL>(ext in self.extensions and ext not in self.config.deny))<EOL>

This determines whether a specific extension is allowed. It is called
by `file_allowed`, so if you override that but still want to check
extensions, call back into this.

:param ext: The extension to check, without the dot.


def update_path(self, board, color, path):

wins = board.score(BLACK) >= board.score(WHITE)<EOL>for node in path:<EOL><INDENT>if color == BLACK:<EOL><INDENT>color = WHITE<EOL><DEDENT>else:<EOL><INDENT>color = BLACK<EOL><DEDENT>if wins == (color == BLACK):<EOL><INDENT>node.wins += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>node.losses += <NUM_LIT:1><EOL><DEDENT>if node.parent:<EOL><INDENT>node.parent.bestchild = node.parent.best_child()<EOL><DEDENT><DEDENT>


if self.unexplored:<EOL><INDENT>i = random.randrange(len(self.unexplored))<EOL>pos = self.unexplored[i]<EOL>self.unexplored[i] = self.unexplored[len(self.unexplored) - <NUM_LIT:1>]<EOL>self.unexplored.pop()<EOL>return pos<EOL><DEDENT>elif self.bestchild:<EOL><INDENT>return self.bestchild.pos<EOL><DEDENT>else:<EOL><INDENT>return PASS<EOL><DEDENT>

select move; unexplored children first, then according to uct value


df = int(round(df))<EOL>highest_table_df = len(_T_DIST_95_CONF_LEVELS)<EOL>if df >= <NUM_LIT:200>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT:100>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT:50>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= <NUM_LIT>:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>if df >= highest_table_df:<EOL><INDENT>return _T_DIST_95_CONF_LEVELS[highest_table_df - <NUM_LIT:1>]<EOL><DEDENT>return _T_DIST_95_CONF_LEVELS[df]<EOL>

Approximate the 95% confidence interval for Student's T distribution.

    Given the degrees of freedom, returns an approximation to the 95%
    confidence interval for the Student's T distribution.

    Args:
        df: An integer, the number of degrees of freedom.

    Returns:
        A float.


deg_freedom = len(sample1) + len(sample2) - <NUM_LIT:2><EOL>critical_value = tdist95conf_level(deg_freedom)<EOL>t_score = tscore(sample1, sample2)<EOL>return (abs(t_score) >= critical_value, t_score)<EOL>

Determine whether two samples differ significantly.

    This uses a Student's two-sample, two-tailed t-test with alpha=0.95.

    Args:
        sample1: one sample.
        sample2: the other sample.

    Returns:
        (significant, t_score) where significant is a bool indicating whether
        the two samples differ significantly; t_score is the score from the
        two-sample T test.


fname = '<STR_LIT>'<EOL>downlad_file(url, fname)<EOL>unzip_file(fname)<EOL>print("<STR_LIT>".format(fname))<EOL>os.unlink(fname)<EOL>


canvas = np.zeros((height, width, <NUM_LIT:3>), dtype=np.uint8)<EOL>return canvas.view(Canvas)<EOL>

Return a blank canvas to annotate.

        :param width: xdim (int)
        :param height: ydim (int)
        :returns: :class:`jicbioimage.illustrate.Canvas`


@staticmethod<EOL><INDENT>def from_grayscale(im, channels_on=(True, True, True)):<DEDENT>

xdim, ydim = im.shape<EOL>canvas = np.zeros((xdim, ydim, <NUM_LIT:3>), dtype=np.uint8)<EOL>for i, include in enumerate(channels_on):<EOL><INDENT>if include:<EOL><INDENT>canvas[:, :, i] = im<EOL><DEDENT><DEDENT>return canvas.view(AnnotatedImage)<EOL>

Return a canvas from a grayscale image.

        :param im: single channel image
        :channels_on: channels to populate with input image
        :returns: :class:`jicbioimage.illustrate.Canvas`


def mask_region(self, region, color=(<NUM_LIT:0>, <NUM_LIT:255>, <NUM_LIT:0>)):

self[region] = color<EOL>

Mask a region with a color.

        :param region: :class:`jicbioimage.core.region.Region`
        :param color: RGB tuple


def intersection(self, coordinates, objects=False):

if objects:<EOL><INDENT>return self._intersection_obj(coordinates, objects)<EOL><DEDENT>p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>p_num_results = ctypes.c_uint64(<NUM_LIT:0>)<EOL>it = ctypes.pointer(ctypes.c_int64())<EOL>core.rt.Index_Intersects_id(self.handle,<EOL>p_mins,<EOL>p_maxs,<EOL>self.properties.dimension,<EOL>ctypes.byref(it),<EOL>ctypes.byref(p_num_results))<EOL>return self._get_ids(it, p_num_results.value)<EOL>

Return ids or objects in the index that intersect the given
        coordinates.

        :param coordinates: sequence or array
            This may be an object that satisfies the numpy array
            protocol, providing the index's dimension * 2 coordinate
            pairs representing the `mink` and `maxk` coordinates in
            each dimension defining the bounds of the query window.

        :param objects: True or False or 'raw'
            If True, the intersection method will return index objects that
            were pickled when they were stored with each index entry, as well
            as the id and bounds of the index entries. If 'raw', the objects
            will be returned without the :class:`rtree.index.Item` wrapper.

        The following example queries the index for any objects any objects
        that were stored in the index intersect the bounds given in the
        coordinates::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.insert(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734),
            ...            obj=42)

            >>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
            >>> [(item.object, item.bbox) for item in hits if item.id == 4321]
            ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
            [(42, [34.37768294..., 26.73758537..., 49.37768294...,
                   41.73758537...])]

        If the :class:`rtree.index.Item` wrapper is not used, it is faster to
        request the 'raw' objects::

            >>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
            [42]


if args:<EOL><INDENT>if isinstance(args[<NUM_LIT:0>], rtree.index.string_types)or isinstance(args[<NUM_LIT:0>], bytes)or isinstance(args[<NUM_LIT:0>], rtree.index.ICustomStorage):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% self.__class__)<EOL><DEDENT><DEDENT>self._objects = {}<EOL>return super(RtreeContainer, self).__init__(*args, **kwargs)<EOL>

Creates a new index

        :param stream:
            If the first argument in the constructor is not of type basestring,
            it is assumed to be an iterable stream of data that will raise a
            StopIteration.  It must be in the form defined by the
            :attr:`interleaved` attribute of the index. The following example
            would assume :attr:`interleaved` is False::

            (obj, (minx, maxx, miny, maxy, minz, maxz, ..., ..., mink, maxk))

        :param interleaved: True or False, defaults to True.
            This parameter determines the coordinate order for all methods that
            take in coordinates.

        :param properties: An :class:`index.Property` object
            This object sets both the creation and instantiation properties
            for the object and they are passed down into libspatialindex.
            A few properties are curried from instantiation parameters
            for you like ``pagesize`` to ensure compatibility with previous
            versions of the library.  All other properties must be set on the
            object.

        .. warning::
            The coordinate ordering for all functions are sensitive the
            index's :attr:`interleaved` data member.  If :attr:`interleaved`
            is False, the coordinates must be in the form
            [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If
            :attr:`interleaved` is True, the coordinates must be in the form
            [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax].

        A basic example
        ::

            >>> from rtree import index
            >>> p = index.Property()

            >>> idx = index.RtreeContainer(properties=p)
            >>> idx  # doctest: +ELLIPSIS
            <rtree.index.RtreeContainer object at 0x...>

        Insert an item into the index::

            >>> idx.insert(object(),
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))

        Query::

            >>> hits = idx.intersection((0, 0, 60, 60), bbox=True)
            >>> for obj in hits:
            ...     obj.object
            ...     obj.bbox  # doctest: +ELLIPSIS
            <object object at 0x...>
            [34.37768294..., 26.73758537..., 49.37768294..., 41.73758537...]


def deleteByteArray(self, context, page, returnError):

returnError.contents.value = self.IllegalStateError<EOL>raise NotImplementedError("<STR_LIT>")<EOL>


def __init__(self, loads, handle, owned=False):

if handle:<EOL><INDENT>self.handle = handle<EOL><DEDENT>self.owned = owned<EOL>self.id = core.rt.IndexItem_GetID(self.handle)<EOL>self.object = None<EOL>self.object = self.get_object(loads)<EOL>self.bounds = _get_bounds(<EOL>self.handle, core.rt.IndexItem_GetBounds, False)<EOL>

There should be no reason to instantiate these yourself. Items are
        created automatically when you call
        :meth:`rtree.index.Index.intersection` (or other index querying
        methods) with objects=True given the parameters of the function.


p_mins, p_maxs = self.get_coordinate_pointers(coordinates)<EOL>core.rt.Index_DeleteData(<EOL>self.handle, id, p_mins, p_maxs, self.properties.dimension)<EOL>

Deletes items from the index with the given ``'id'`` within the
        specified coordinates.

        :param id: long integer
            A long integer that is the identifier for this index entry.  IDs
            need not be unique to be inserted into the index, and it is up
            to the user to ensure they are unique if this is a requirement.

        :param coordinates: sequence or array
            Dimension * 2 coordinate pairs, representing the min
            and max coordinates in each dimension of the item to be
            deleted from the index. Their ordering will depend on the
            index's :attr:`interleaved` data member.
            These are not the coordinates of a space containing the
            item, but those of the item itself. Together with the
            id parameter, they determine which item will be deleted.
            This may be an object that satisfies the numpy array protocol.

        Example::

            >>> from rtree import index
            >>> idx = index.Index()
            >>> idx.delete(4321,
            ...            (34.3776829412, 26.7375853734, 49.3776829412,
            ...             41.7375853734))


def loadByteArray(self, page, returnError):

returnError.contents.value = self.IllegalStateError<EOL>raise NotImplementedError("<STR_LIT>")<EOL>return '<STR_LIT>'<EOL>

Must be overridden. Must return a string with the loaded data.


def destroy(self, context, returnError):


def deleteByteArray(self, page, returnError):


def check_value_free(result, func, cargs):

count = rt.Error_GetErrorCount()<EOL>if count != <NUM_LIT:0>:<EOL><INDENT>s = rt.Error_GetLastErrorMsg().decode()<EOL>msg = '<STR_LIT>' % (func.__name__, s)<EOL>rt.Error_Reset()<EOL>raise RTreeError(msg)<EOL><DEDENT>return result<EOL>


if result != <NUM_LIT:0>:<EOL><INDENT>s = rt.Error_GetLastErrorMsg().decode()<EOL>msg = '<STR_LIT>' %(func.__name__, s)<EOL>rt.Error_Reset()<EOL>raise RTreeError(msg)<EOL><DEDENT>return True<EOL>


failure_description = None<EOL>if self.interactive:<EOL><INDENT>failure_description = _ask_user_to_verify(description)<EOL>if failure_description is not None:<EOL><INDENT>self.fail(failure_description)<EOL><DEDENT><DEDENT>

Ask a question to verify the current test result. Uses the console or an external gui
        as no window is available.


screenshot_name = self._get_next_screenshot_name()<EOL>screenshot_file_name = self._get_screenshot_session_file_name(screenshot_name)<EOL>if window is not None:<EOL><INDENT>window.switch_to()<EOL><DEDENT>get_buffer_manager().get_color_buffer().image_data.save(screenshot_file_name)<EOL>self.screenshots.append(screenshot_name)<EOL>self._schedule_commit()<EOL>return screenshot_name<EOL>

Take a screenshot to allow visual verification.


super(WorldViewMouseRotatable,self).on_menu_exit(new)<EOL>self.world.peng.window.toggle_exclusivity(False)<EOL>

Fake event handler, same as :py:meth:`WorldView.on_menu_exit()` but force-disables mouse exclusivity.


for actor in self.actors.values():<EOL><INDENT>actor.render(view)<EOL><DEDENT>

Renders the world in 3d-mode.

If you want to render custom terrain, you may override this method. Be careful that you still call the original method or else actors may not be rendered.


super(WorldViewMouseRotatable,self).on_menu_enter(old)<EOL>self.world.peng.window.toggle_exclusivity(True)<EOL>

Fake event handler, same as :py:meth:`WorldView.on_menu_enter()` but forces mouse exclusivity.


self.ensureModelData(obj)<EOL>data = obj._modeldata<EOL>vlists = data["<STR_LIT>"]["<STR_LIT>"]<EOL>for name,region in self.modeldata["<STR_LIT>"].items():<EOL><INDENT>vlists[name].vertices = region.getVertices(data)<EOL>if region.enable_tex:<EOL><INDENT>vlists[name].tex_coords = region.getTexCoords(data)<EOL><DEDENT><DEDENT>

Redraws the model of the given object.

Note that currently this method probably won't change any data since all movement and animation is done through pyglet groups.


self.ensureModelData(obj)<EOL>data = obj._modeldata<EOL>if animation not in self.modeldata["<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>"%(animation,self.modelname))<EOL><DEDENT>if data.get("<STR_LIT>",{}).get("<STR_LIT>",None)==animation and not force:<EOL><INDENT>return <EOL><DEDENT>anim = self.modeldata["<STR_LIT>"][animation]<EOL>if transition is None:<EOL><INDENT>transition = anim.default_jt<EOL><DEDENT>anim.startAnimation(data,transition)<EOL>if "<STR_LIT>" not in data:<EOL><INDENT>data["<STR_LIT>"]={}<EOL><DEDENT>adata = data["<STR_LIT>"]<EOL>adata["<STR_LIT>"]=animation<EOL>if "<STR_LIT>" in adata:<EOL><INDENT>pyglet.clock.unschedule(adata["<STR_LIT>"])<EOL><DEDENT>def schedfunc(*args):<EOL><INDENT>anim.tickEntity(data)<EOL><DEDENT>pyglet.clock.schedule_interval(schedfunc,<NUM_LIT:1.>/(anim.kps if anim.atype=="<STR_LIT>" else <NUM_LIT>))<EOL>adata["<STR_LIT>"] = schedfunc<EOL>

Sets the animation to be used by the object.

See :py:meth:`Actor.setAnimation()` for more information.


self.parent.setRotate(data)<EOL>glPushMatrix()<EOL>x,y = self.getRot(data)<EOL>pivot = self.getPivotPoint(data)<EOL>px,py,pz = pivot<EOL>normx = [<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:0>] <EOL>normy = [<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:1>]<EOL>glTranslatef(px,py,pz)<EOL>glRotatef(x-self.start_rot[<NUM_LIT:0>], normx[<NUM_LIT:0>],normx[<NUM_LIT:1>],normx[<NUM_LIT:2>])<EOL>glRotatef(y-self.start_rot[<NUM_LIT:1>], normy[<NUM_LIT:0>],normy[<NUM_LIT:1>],normy[<NUM_LIT:2>])<EOL>glTranslatef(-px,-py,-pz)<EOL>

Sets the OpenGL state required for proper drawing of the model.

Mostly rotates and translates the camera.

It is important to call :py:meth:`unsetRotate()` after calling this method to properly unset state and avoid OpenGL errors.


return self.geometry_type<EOL>

Returns the OpenGL constant representing the type of primitives used by this region.

May be one of :py:data:`GL_QUADS`\ , :py:data:`GL_TRIANGLES`\ , :py:data:`GL_LINES` or :py:data:`GL_POINTS`\ .


return self.rsrcMgr.getTex(self,texname,self.texcat)<EOL>

Read-only property equivalent to a 3-tuple containing :py:attr:`target`\ , :py:attr:`id` and :py:attr:`tex_coords`\ .

Should be faster than getting each value directly. Useful if all of these values are needed.


return self._pos<EOL>

Property for accessing the position of the camera.

This property uses a setter to call the :py:meth:`on_move()` method if set and the new location is not equal to the old location.


return self.actor.rot<EOL>

This property always equals the value of ``self.actor.rot``\ .

This property may also be written to.


self.setup()<EOL>if evloop is not None:<EOL><INDENT>pyglet.app.event_loop = evloop<EOL><DEDENT>pyglet.app.run() <EOL>

Runs the application in the current thread.

This method should not be called directly, especially when using multiple windows, use :py:meth:`Peng.run()` instead.

Note that this method is blocking as rendering needs to happen in the main thread.
It is thus recommendable to run your game logic in another thread that should be started before calling this method.

``evloop`` may optionally be a subclass of :py:class:`pyglet.app.base.EventLoop` to replace the default event loop.


Adds a new texture category with the given name.

If the category already exists, it will be overridden.


nsplit = name.split("<STR_LIT::>")[<NUM_LIT:1>].split("<STR_LIT:.>")<EOL>return os.path.join(self.basepath,"<STR_LIT>",name.split("<STR_LIT::>")[<NUM_LIT:0>],*nsplit)+ext<EOL>

Converts the given resource name to a file path.

A resource path is of the format ``<app>:<cat1>.<cat2>.<name>`` where cat1 and cat2 can be repeated as often as desired.

``ext`` is the file extension to use, e.g. ``.png`` or similar.

As an example, the resource name ``peng3d:some.category.foo`` with the extension ``.png`` results in the path ``<basepath>/assets/peng3d/some/category/foo.png``\ .

This resource naming scheme is used by most other methods of this class.

Note that it is currently not possible to define multiple base paths to search through.


return os.path.exists(self.resourceNameToPath(name,ext))<EOL>

Returns whether or not the resource with the given name and extension exists.

This must not mean that the resource is meaningful, it simply signals that the file exists.


if category not in self.categoriesTexCache:<EOL><INDENT>return self.getMissingTex(category)<EOL><DEDENT>if name not in self.categoriesTexCache[category]:<EOL><INDENT>self.loadTex(name,category)<EOL><DEDENT>return self.categoriesTexCache[category][name]<EOL>

Gets the texture associated with the given name and category.

``category`` must have been created using :py:meth:`addCategory()` before.

If it was loaded previously, a cached version will be returned.
If it was not loaded, it will be loaded and inserted into the cache.

See :py:meth:`loadTex()` for more information.


for layer in self.layers:<EOL><INDENT>layer.on_menu_enter(old)<EOL><DEDENT>

Same as :py:meth:`BasicMenu.on_enter()`\ , but also calls :py:meth:`Layer.on_menu_enter()` on every layer.


pass<EOL>

This method is called if it is time to render the menu.

Override this method in subclasses to customize behavior and actually draw stuff.


if self.cfg["<STR_LIT>"]!="<STR_LIT>" and event not in self.event_list:<EOL><INDENT>self.event_list.add(event)<EOL><DEDENT>if event not in self.eventHandlers:<EOL><INDENT>if event not in self.events_ignored or self.events_ignored[event]<=self.cfg["<STR_LIT>"]: <EOL><INDENT>self.events_ignored[event] = self.events_ignored.get(event,<NUM_LIT:0>)+<NUM_LIT:1><EOL><DEDENT>return<EOL><DEDENT>for handler in self.eventHandlers[event]:<EOL><INDENT>f = handler[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>f(event,data)<EOL><DEDENT>except Exception:<EOL><INDENT>if not handler[<NUM_LIT:1>]:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>if self.cfg["<STR_LIT>"]:<EOL><INDENT>self.delEventListener(event,f)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Sends an event with attached data.

``event`` should be a string of format ``<namespace>:<category1>.<subcategory2>.<name>``\ .
There may be an arbitrary amount of subcategories. Also note that this
format is not strictly enforced, but rather recommended by convention.

``data`` may be any Python Object, but it usually is a dictionary containing relevant parameters.
For example, most built-in events use a dictionary containing at least the ``peng`` key set to an instance of this class.

If there are no handlers for the event, a corresponding message will be printed to the log file.
To prevent spam, the maximum amount of ignored messages can be configured via :confval:`events.maxignore` and defaults to 3.

If the config value :confval:`debug.events.dumpfile` is a file path, the event type will be added to an internal list and be saved to the given file during program exit.


if not isinstance(event,str):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if event not in self.eventHandlers:<EOL><INDENT>self.eventHandlers[event]=[]<EOL><DEDENT>self.eventHandlers[event].append([func,raiseErrors])<EOL>

Adds a handler to the given event.

A event may have an arbitrary amount of handlers, though assigning too
many handlers may slow down event processing.

For the format of ``event``\ , see :py:meth:`sendEvent()`\ .

``func`` is the handler which will be executed with two arguments, ``event_type`` and ``data``\ , as supplied to :py:meth:`sendEvent()`\ .

If ``raiseErrors`` is True, exceptions caused by the handler will be re-raised.
Defaults to ``False``\ .


<EOL>if points<=<NUM_LIT:8>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>elif points<=<NUM_LIT:10>:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>elif points<=<NUM_LIT:12>:<EOL><INDENT>return <NUM_LIT:3><EOL><DEDENT>elif points<=<NUM_LIT>:<EOL><INDENT>return <NUM_LIT:4><EOL><DEDENT>elif points<=<NUM_LIT>:<EOL><INDENT>return <NUM_LIT:5><EOL><DEDENT>elif points<=<NUM_LIT>:<EOL><INDENT>return <NUM_LIT:6><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:7><EOL><DEDENT>

Approximate font size converter, converts from Points to HTML ``<font>`` tag font sizes.

Note that this method is very inaccurate, since there are only seven possible output values that represent at least 25 input values.
When in doubt, this function always rounds down, e.g. every input value less than eight is converted to HTML size 1.


if not hasattr(self,"<STR_LIT>"):<EOL><INDENT>self.actions = {}<EOL><DEDENT>if action not in self.actions:<EOL><INDENT>self.actions[action] = []<EOL><DEDENT>self.actions[action].append((func,args,kwargs))<EOL>

Adds a callback to the specified action.

All other positional and keyword arguments will be stored and passed to the function upon activation.


pass<EOL>

Called when this layer needs to be drawn.

Override this method in subclasses to redefine behavior.


self.cam = self.view.cam<EOL>super(LayerWorld,self).predraw()<EOL>

Sets up the attributes used by :py:class:`Layer3D()` and calls :py:meth:`Layer3D.predraw()`\ .


pass<EOL>

Custom fake event handler called by :py:meth:`Menu.on_enter()` for every layer.

Useful for adding and removing event handlers per layer.


self.lang = lang<EOL>self.peng.cfg["<STR_LIT>"] = lang<EOL>if lang not in self.cache:<EOL><INDENT>self.cache[lang]={}<EOL><DEDENT>self.doAction("<STR_LIT>")<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.lang,"<STR_LIT>":self})<EOL>

Sets the default language for all domains.

For recommendations regarding the format of the language code, see
:py:class:`TranslationManager`\ .

Note that the ``lang`` parameter of both :py:meth:`translate()` and
:py:meth:`translate_lazy()` will override this setting.

Also note that the code won't be checked for existence or plausibility.
This may cause the fallback strings to be displayed instead if the language
does not exist.

Calling this method will cause the ``setlang`` action and the
:peng3d:event`peng3d:i18n.set_lang` event to be triggered. Note that both
action and event will be triggered even if the language did not actually change.

This method also automatically updates the :confval:`i18n.lang` config value.


pass<EOL>

Called just before :py:meth:`on_redraw()` is called the first time.


pass<EOL>

Called after calling the :py:meth:`draw()` Method.

Useful for unsetting OpenGL state.


if name not in self.imgs:<EOL><INDENT>raise ValueError("<STR_LIT>"%name)<EOL><DEDENT>elif self.cur_img==name:<EOL><INDENT>return<EOL><DEDENT>self.cur_img = name<EOL>self.on_redraw()<EOL>

Switches the active image to the given name.

:raises ValueError: If there is no such image


return self._layers[name]<EOL>

Returns the layer corresponding to the given name.

:raises KeyError: If there is no Layer with the given name.


for vlist in self._vlists:<EOL><INDENT>vlist.delete()<EOL><DEDENT>self._vlists = []<EOL>

Deletes this Layer.

Currently only deletes VertexLists registered with :py:meth:`regVList()`\ .


Property to be used for setting and getting the offset of the layer.

Note that setting this property causes an immediate redraw.


return self.change_on_press and self.widget.pressed<EOL>

Read-only helper property to be used by styles for determining if the layer should be rendered as pressed or not.

Note that this property may not represent the actual pressed state, it will always be False if ``change_on_press`` is disabled.


return self._nmax<EOL>

Property representing the maximum value of the progressbar. Typically ``100`` to represent percentages easily.


if name not in self.categories:<EOL><INDENT>raise KeyError("<STR_LIT>"%name)<EOL><DEDENT>del self.categories[name]<EOL>self.redraw()<EOL>

Deletes the category with the given name.

If the category does not exist, a :py:exc:`KeyError` will be thrown.


assert isinstance(name,basestring) <EOL>if name in self.categories:<EOL><INDENT>raise KeyError("<STR_LIT>"%name)<EOL><DEDENT>self.categories[name]=[nmin,n,nmax]<EOL>self.redraw()<EOL>

Adds a category with the given name.

If the category already exists, a :py:exc:`KeyError` will be thrown. Use
:py:meth:`updateCategory()` instead if you want to update a category.


return self._text.text<EOL>


sx,sy = self.widget.size<EOL>x,y = self.widget.pos<EOL>bx,by = self.border<EOL>return sx,sy,x,y,bx,by<EOL>

Helper function converting the actual widget position and size into a usable and offsetted form.

This function should return a 6-tuple of ``(sx,sy,x,y,bx,by)`` where sx and sy are the size, x and y the position and bx and by are the border size.

All values should be in pixels and already include all offsets, as they are used directly for generation of vertex data.

This method can also be overridden to limit the background to a specific part of its widget.


<EOL>sx,sy = self.size<EOL>x,y = self.pos<EOL>self._label.x = x+sx/<NUM_LIT><EOL>self._label.y = y+sy/<NUM_LIT><EOL>self._label._update()<EOL>

Re-draws the label by calculating its position.

Currently, the label will always be centered on the Button.


super(GUIMenu,self).draw()<EOL>self.submenu.draw()<EOL>

Draws each menu layer and the active submenu.

Note that the layers are drawn first and may be overridden by the submenu and widgets.


if submenu not in self.submenus:<EOL><INDENT>raise ValueError("<STR_LIT>"%submenu)<EOL><DEDENT>elif submenu == self.activeSubMenu:<EOL><INDENT>return <EOL><DEDENT>old = self.activeSubMenu<EOL>self.activeSubMenu = submenu<EOL>if old is not None:<EOL><INDENT>self.submenus[old].on_exit(submenu)<EOL>self.submenus[old].doAction("<STR_LIT>")<EOL><DEDENT>self.submenu.on_enter(old)<EOL>self.submenu.doAction("<STR_LIT>")<EOL>

Changes the submenu that is displayed.

:raises ValueError: if the name was not previously registered


pass<EOL>

Dummy method defined for compatibility with :py:class:`peng3d.gui.SubMenu`, simply does nothing.


<EOL>self.wbtn_confirm = button.Button("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw-<NUM_LIT:4>,sh/<NUM_LIT:2>-bh/<NUM_LIT:2>-bh*<NUM_LIT:2>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label=label_confirm,<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.wbtn_confirm.size = lambda sw,sh: (self.wbtn_confirm._label.font_size*<NUM_LIT:8>,self.wbtn_confirm._label.font_size*<NUM_LIT:2>)<EOL>self.addWidget(self.wbtn_confirm)<EOL>def f():<EOL><INDENT>self.doAction("<STR_LIT>")<EOL>self.exitDialog()<EOL><DEDENT>self.wbtn_confirm.addAction("<STR_LIT>",f)<EOL>

Adds a confirm button to let the user confirm whatever action they were presented with.

This widget can be triggered by setting the label ``label_confirm`` to a string.

This widget will be positioned slightly below the main label and to the left
of the cancel button.


<EOL>self.wbtn_cancel = button.Button("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>+<NUM_LIT:4>,sh/<NUM_LIT:2>-bh/<NUM_LIT:2>-bh*<NUM_LIT:2>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label=label_cancel,<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.wbtn_cancel.size = lambda sw,sh: (self.wbtn_cancel._label.font_size*<NUM_LIT:8>,self.wbtn_cancel._label.font_size*<NUM_LIT:2>)<EOL>self.addWidget(self.wbtn_cancel)<EOL>def f():<EOL><INDENT>self.doAction("<STR_LIT>")<EOL>self.exitDialog()<EOL><DEDENT>self.wbtn_cancel.addAction("<STR_LIT>",f)<EOL>

Adds a cancel button to let the user cancel whatever choice they were given.

This widget can be triggered by setting the label ``label_cancel`` to a string.

This widget will be positioned slightly below the main label and to the right
of the confirm button.


return self.wbtn_confirm.label<EOL>

Property that proxies the ``label_confirm`` label.

Setting this property will cause the ``label_confirm_change`` action to trigger.

Note that trying to access this property if the widget is not used may cause
an error.


return self.wprogressbar.nmax<EOL>

Property that proxies the ``progress_nmax`` label.

Setting this property will cause the progressbar label to be recalculated.

Note that setting this property if the widget has not been initialized may
cause various errors to occur.


return self.wprogressbar.n<EOL>

Property that proxies the ``progress_n`` label.

Setting this property will cause the progressbar label to be recalculated.

Additionally, if the supplied value is higher than the maximum value and
:py:attr:`auto_exit` is true, the dialog will exit.


return self.wprogressbar.addCategory(*args,**kwargs)<EOL>

Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.addCategory()`\ .


return self.wbtn_cancel.label<EOL>

Property that proxies the ``label_cancel`` label.

Setting this property will cause the ``label_cancel_change`` action to trigger.

Note that trying to access this property if the widget is not used may cause
an error.


pass<EOL>

Called just before the background will be drawn the first time.

Commonly used to initialize vertex lists.

It is recommended to add all vertex lists to the ``submenu.batch2d`` Batch to speed up rendering and preventing glitches with grouping.


if self.do_redraw:<EOL><INDENT>self.on_redraw()<EOL>self.do_redraw = False<EOL><DEDENT>

Draws all vertex lists associated with this widget.


if not isinstance(self.submenu,Container):<EOL><INDENT>return self.submenu.name == self.submenu.menu.activeSubMenu and self.submenu.menu.name == self.window.activeMenu and self.enabled<EOL><DEDENT>else:<EOL><INDENT>return self.submenu.clickable and self.enabled<EOL><DEDENT>

Property used for determining if the widget should be clickable by the user.

This is only true if the submenu of this widget is active and this widget is enabled.

The widget may be either disabled by setting this property or the :py:attr:`enabled` attribute.


if not self.enabled:<EOL><INDENT>return<EOL><DEDENT>speed = self.movespeed<EOL>d = dt * speed <EOL>dx, dy, dz = self.get_motion_vector()<EOL>dx, dy, dz = dx * d, dy * d, dz * d<EOL>x,y,z = self.actor._pos<EOL>newpos = dx+x, dy+y, dz+z<EOL>self.actor.pos = newpos<EOL>

Should be called regularly to move the actor.

This method does nothing if the :py:attr:`enabled` property is set to false.

Note that this method is called automatically and should not be manually called.


Registers the up and down handlers.

Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.


if any(self.move):<EOL><INDENT>x, y = self.actor._rot<EOL>strafe = math.degrees(math.atan2(*self.move))<EOL>y_angle = math.radians(y)<EOL>x_angle = math.radians(x + strafe)<EOL>dy = <NUM_LIT:0.0><EOL>dx = math.cos(x_angle)<EOL>dz = math.sin(x_angle)<EOL><DEDENT>else:<EOL><INDENT>dy = <NUM_LIT:0.0><EOL>dx = <NUM_LIT:0.0><EOL>dz = <NUM_LIT:0.0><EOL><DEDENT>return (dx, dy, dz)<EOL>

Returns the movement vector according to held buttons and the rotation.

:return: 3-Tuple of ``(dx,dy,dz)``
:rtype: tuple


return self._pos<EOL>

Property allowing access to the position of this actor.

This actor is read-write but calls :py:meth:`on_move()` if it is set.


x, y = self._rot<EOL>y_angle = math.radians(y)<EOL>x_angle = math.radians(x)<EOL>m = math.cos(y_angle)<EOL>dy = math.sin(y_angle)<EOL>dy = <NUM_LIT:0.0><EOL>dx = math.cos(x_angle)<EOL>dz = math.sin(x_angle)<EOL>dx,dy,dz = dx*dist,dy*dist,dz*dist<EOL>x,y,z = self._pos<EOL>self.pos = x+dx,y+dy,z+dz<EOL>return dx,dy,dz<EOL>

Moves the actor using standard trigonometry along the current rotational vector.

:param float dist: Distance to move

.. todo::

   Test this method, also with negative distances


pass<EOL>

Method to be overridden by subclasses for registering event handlers.

Automatically called upon object creation.


if self.model is not None:<EOL><INDENT>self.model.cleanup(self)<EOL><DEDENT>self.model = model<EOL>model.create(self)<EOL>

Sets the model this actor should use when drawing.

This method also automatically initializes the new model and removes the old, if any.


if self.model is not None:<EOL><INDENT>self.model.draw(self)<EOL><DEDENT>

Called by :py:meth:`World.render3d()` to render this actor.

By default, this method calls the draw method of its model, if any.

For custom render behavior, it is recommended to extend this method or modify the model.


Handles a key combination and dispatches associated events.

First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(combo,symbol,modifiers,release,mod)`` is sent to the :py:class:`Peng()` instance.

Also sends the events :peng3d:event:`peng3d:keybind.combo`\, :peng3d:event:`peng3d:keybind.combo.press` and :peng3d:event`peng3d:keybind.combo.release`\ .

:params str combo: Key combination pressed
:params int symbol: Key pressed, passed from the same argument within pyglet
:params int modifiers: Modifiers held while the key was pressed
:params bool release: If the combo was released
:params bool mod: If the combo was sent without mods


def decorate(wrapped):<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>arg_names, varargs, _, defaults = inspect.getargspec(wrapped)<EOL><DEDENT>else:<EOL><INDENT>arg_names, varargs, _, defaults = inspect.getfullargspec(wrapped)[:<NUM_LIT:4>]<EOL><DEDENT>if not defaults:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>first_default_index = len(arg_names) - len(defaults)<EOL>if name is FIRST_DEFAULT_ARG:<EOL><INDENT>first_kwonly_index = first_default_index<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>first_kwonly_index = arg_names.index(name)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>" % (<EOL>getattr(wrapped, '<STR_LIT>', '<STR_LIT:?>'), name))<EOL><DEDENT><DEDENT>if first_kwonly_index < first_default_index:<EOL><INDENT>raise ValueError("<STR_LIT>" % (name,))<EOL><DEDENT>kwonly_defaults = defaults[-(len(arg_names)-first_kwonly_index):]<EOL>kwonly_args = tuple(zip(arg_names[first_kwonly_index:], kwonly_defaults))<EOL>required_kwonly_args = frozenset(arg for arg, default in kwonly_args if default is KWONLY_REQUIRED)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>if required_kwonly_args:<EOL><INDENT>missing_kwonly_args = required_kwonly_args.difference(kwargs.keys())<EOL>if missing_kwonly_args:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>getattr(wrapped, '<STR_LIT>', '<STR_LIT:?>'), len(missing_kwonly_args),<EOL>'<STR_LIT:U+002CU+0020>'.join(sorted(missing_kwonly_args))))<EOL><DEDENT><DEDENT>if len(args) > first_kwonly_index:<EOL><INDENT>if varargs is None:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>getattr(wrapped, '<STR_LIT>', '<STR_LIT:?>'), first_kwonly_index, len(args)))<EOL><DEDENT>kwonly_args_from_kwargs = tuple(kwargs.pop(arg, default) for arg, default in kwonly_args)<EOL>args = args[:first_kwonly_index] + kwonly_args_from_kwargs + args[first_kwonly_index:]<EOL><DEDENT>return wrapped(*args, **kwargs)<EOL><DEDENT>return update_wrapper(wrapper, wrapped)<EOL><DEDENT>return decorate<EOL>

Emulates keyword-only arguments under python2. Works with both python2 and python3.
    With this decorator you can convert all or some of the default arguments of your function
    into kwonly arguments. Use ``KWONLY_REQUIRED`` as the default value of required kwonly args.

    :param name: The name of the first default argument to be treated as a keyword-only argument. This default
    argument along with all default arguments that follow this one will be treated as keyword only arguments.

    You can also pass here the ``FIRST_DEFAULT_ARG`` constant in order to select the first default argument. This
    way you turn all default arguments into keyword-only arguments. As a shortcut you can use the
    ``@kwonly_defaults`` decorator (without any parameters) instead of ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``.

        >>> from kwonly_args import first_kwonly_arg, KWONLY_REQUIRED, FIRST_DEFAULT_ARG, kwonly_defaults
        >>>
        >>> # this decoration converts the ``d1`` and ``d2`` default args into kwonly args
        >>> @first_kwonly_arg('d1')
        >>> def func(a0, a1, d0='d0', d1='d1', d2='d2', *args, **kwargs):
        >>>     print(a0, a1, d0, d1, d2, args, kwargs)
        >>>
        >>> func(0, 1, 2, 3, 4)
        0 1 2 d1 d2 (3, 4) {}
        >>>
        >>> func(0, 1, 2, 3, 4, d2='my_param')
        0 1 2 d1 my_param (3, 4) {}
        >>>
        >>> # d0 is an optional deyword argument, d1 is required
        >>> def func(d0='d0', d1=KWONLY_REQUIRED):
        >>>     print(d0, d1)
        >>>
        >>> # The ``FIRST_DEFAULT_ARG`` constant automatically selects the first default argument so it
        >>> # turns all default arguments into keyword-only ones. Both d0 and d1 are keyword-only arguments.
        >>> @first_kwonly_arg(FIRST_DEFAULT_ARG)
        >>> def func(a0, a1, d0='d0', d1='d1'):
        >>>     print(a0, a1, d0, d1)
        >>>
        >>> # ``@kwonly_defaults`` is a shortcut for the ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``
        >>> # in the previous example. This example has the same effect as the previous one.
        >>> @kwonly_defaults
        >>> def func(a0, a1, d0='d0', d1='d1'):
        >>>     print(a0, a1, d0, d1)


try:<EOL><INDENT>if not items:<EOL><INDENT>from .example import ExampleCommand<EOL>from .version import Version<EOL>items = [(ExampleCommand.NAME, ExampleCommand),<EOL>(Version.NAME, Version)]<EOL><DEDENT>main("<STR_LIT>", items=items)<EOL><DEDENT>except Stop as stop:<EOL><INDENT>print(stop)<EOL>sys.exit(stop.rc)<EOL><DEDENT>except SystemExit:<EOL><INDENT>raise<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>except Exception:<EOL><INDENT>traceback.print_exc()<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>

External entry point which calls main() and
if Stop is raised, calls sys.exit()


def main(fw_name, args=None, items=None):

global DEBUG_LEVEL<EOL>global FRAMEWORK_NAME<EOL>debug_name = "<STR_LIT>" % fw_name.upper()<EOL>if debug_name in os.environ:<EOL><INDENT>try:<EOL><INDENT>DEBUG_LEVEL = int(os.environ.get(debug_name))<EOL><DEDENT>except ValueError:<EOL><INDENT>DEBUG_LEVEL = <NUM_LIT:10>  <EOL><DEDENT><DEDENT>FRAMEWORK_NAME = fw_name<EOL>if args is None:<EOL><INDENT>args = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>if items is None:<EOL><INDENT>items = list(globals().items())<EOL><DEDENT>yaclifw_parser, sub_parsers = parsers()<EOL>for name, MyCommand in sorted(items):<EOL><INDENT>if not isinstance(MyCommand, type):<EOL><INDENT>continue<EOL><DEDENT>if not issubclass(MyCommand, Command):<EOL><INDENT>continue<EOL><DEDENT>if MyCommand.NAME == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>MyCommand(sub_parsers)<EOL><DEDENT>ns = yaclifw_parser.parse_args(args)<EOL>ns.func(ns)<EOL>if hasattr(ns, '<STR_LIT>'):<EOL><INDENT>if callable(ns.callback):<EOL><INDENT>ns.callback()<EOL><DEDENT>else:<EOL><INDENT>raise Stop(<NUM_LIT:3>, "<STR_LIT>")<EOL><DEDENT><DEDENT>

Reusable entry point. Arguments are parsed
via the argparse-subcommands configured via
each Command class found in globals(). Stop
exceptions are propagated to callers.

The name of the framework will be used in logging
and similar.


def get_relationship_info(tree, media, image_sizes):

if tree is None:<EOL><INDENT>return {}<EOL><DEDENT>result = {}<EOL>for el in tree.iter():<EOL><INDENT>el_id = el.get('<STR_LIT>')<EOL>if el_id is None:<EOL><INDENT>continue<EOL><DEDENT>target = el.get('<STR_LIT>')<EOL>if any(<EOL>target.lower().endswith(ext) for<EOL>ext in IMAGE_EXTENSIONS_TO_SKIP):<EOL><INDENT>continue<EOL><DEDENT>if target in media:<EOL><INDENT>image_size = image_sizes.get(el_id)<EOL>target = convert_image(media[target], image_size)<EOL><DEDENT>result[el_id] = cgi.escape(target)<EOL><DEDENT>return result<EOL>

There is a separate file holds the targets to links as well as the targets
for images. Return a dictionary based on the relationship id and the
target.


ilvls = li.xpath('<STR_LIT>', namespaces=li.nsmap)<EOL>if len(ilvls) == <NUM_LIT:0>:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>return int(ilvls[<NUM_LIT:0>].get('<STR_LIT>' % w_namespace))<EOL>

The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.


<EOL>table_el = etree.Element('<STR_LIT>')<EOL>w_namespace = get_namespace(table, '<STR_LIT:w>')<EOL>row_spans = get_rowspan_data(table)<EOL>for el in table:<EOL><INDENT>if el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>tr_el = build_tr(<EOL>el,<EOL>meta_data,<EOL>row_spans,<EOL>)<EOL>table_el.append(tr_el)<EOL><DEDENT><DEDENT>visited_nodes = list(table.iter())<EOL>return table_el, visited_nodes<EOL>

This returns a table object with all rows and cells correctly populated.