def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Create a DAG node out of a parsed AST op node.

        Args:
            name (str): operation name to apply to the dag.
            params (list): op parameters
            qargs (list(QuantumRegister, int)): qubits to attach to

        Raises:
            QiskitError: if encountering a non-basis opaque gate
        """
        if arg_1 == "u0":
            arg_4 = U0Gate
        elif arg_1 == "u1":
            arg_4 = U1Gate
        elif arg_1 == "u2":
            arg_4 = U2Gate
        elif arg_1 == "u3":
            arg_4 = U3Gate
        elif arg_1 == "x":
            arg_4 = XGate
        elif arg_1 == "y":
            arg_4 = YGate
        elif arg_1 == "z":
            arg_4 = ZGate
        elif arg_1 == "t":
            arg_4 = TGate
        elif arg_1 == "tdg":
            arg_4 = TdgGate
        elif arg_1 == "s":
            arg_4 = SGate
        elif arg_1 == "sdg":
            arg_4 = SdgGate
        elif arg_1 == "swap":
            arg_4 = SwapGate
        elif arg_1 == "rx":
            arg_4 = RXGate
        elif arg_1 == "ry":
            arg_4 = RYGate
        elif arg_1 == "rz":
            arg_4 = RZGate
        elif arg_1 == "rzz":
            arg_4 = RZZGate
        elif arg_1 == "id":
            arg_4 = IdGate
        elif arg_1 == "h":
            arg_4 = HGate
        elif arg_1 == "cx":
            arg_4 = CnotGate
        elif arg_1 == "cy":
            arg_4 = CyGate
        elif arg_1 == "cz":
            arg_4 = CzGate
        elif arg_1 == "ch":
            arg_4 = CHGate
        elif arg_1 == "crz":
            arg_4 = CrzGate
        elif arg_1 == "cu1":
            arg_4 = Cu1Gate
        elif arg_1 == "cu3":
            arg_4 = Cu3Gate
        elif arg_1 == "ccx":
            arg_4 = ToffoliGate
        elif arg_1 == "cswap":
            arg_4 = FredkinGate
        else:
            raise QiskitError("unknown operation for ast node name %s" % arg_1)

        arg_5 = arg_4(*arg_2)

        arg_0.dag.apply_operation_back(arg_5, arg_3, [], condition=arg_0.condition)


def Func(arg_0, *arg_1: arg_2[arg_3]) -> int:
        """Return duration of supplied channels.

        Args:
            *channels: Supplied channels
        """
        return arg_0.timeslots.Func(*arg_1)


def Func(arg_0, *arg_1: arg_2[arg_3]) -> int:
        """Return minimum start time for supplied channels.

        Args:
            *channels: Supplied channels
        """
        return arg_0.timeslots.Func(*arg_1)


def Func(arg_0, *arg_1: arg_2[arg_3]) -> int:
        """Return maximum start time for supplied channels.

        Args:
            *channels: Supplied channels
        """
        return arg_0.timeslots.Func(*arg_1)


def Func(arg_0, arg_1: arg_2 = 0) -> Iterable[Tuple[arg_2, 'Instruction']]:
        """Iterable for flattening Schedule tree.

        Args:
            time: Shifted time due to parent

        Yields:
            Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
                at and the flattened `ScheduleComponent`.
        """
        for arg_3, arg_4 in arg_0.children:
            yield from arg_4.Func(arg_1 + arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Include unknown fields after load.

        Unknown fields are added with no processing at all.

        Args:
            valid_data (dict or list): validated data returned by ``load()``.
            many (bool): if True, data and original_data are a list.
            original_data (dict or list): data passed to ``load()`` in the
                first place.

        Returns:
            dict: the same ``valid_data`` extended with the unknown attributes.

        Inspired by https://github.com/marshmallow-code/marshmallow/pull/595.
        """
        if arg_2:
            for arg_4, arg_5 in enumerate(arg_1):
                arg_6 = set(arg_3[arg_4]) - set(arg_1[arg_4])
                for arg_7 in arg_6:
                    arg_1[arg_4][arg_7] = arg_3[arg_4][arg_7]
        else:
            arg_6 = set(arg_3) - set(arg_1)
            for arg_7 in arg_6:
                arg_1[arg_7] = arg_3[arg_7]

        return arg_1


def Func(arg_0):
        """Add validation after instantiation."""

        @wraps(arg_0)
        def _decorated(arg_1, **arg_2):
            try:
                arg_3 = arg_1.shallow_schema.validate(arg_2)
            except ValidationError as ex:
                raise ModelValidationError(
                    ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None

            arg_0(arg_1, **arg_2)

        return _decorated


def Func(arg_0):
        """Serialize the model into a Python dict of simple types.

        Note that this method requires that the model is bound with
        ``@bind_schema``.
        """
        try:
            arg_1, arg_2 = arg_0.schema.dump(arg_0)
        except ValidationError as ex:
            raise ModelValidationError(
                ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwargs) from None

        return arg_1


def Func(arg_0, arg_1, arg_2):
    """n-qubit QFT on q in circ."""
    for arg_3 in range(arg_2):
        for arg_4 in range(arg_3):
            arg_0.cu1(math.pi / float(2**(arg_3 - arg_4)), arg_1[arg_3], arg_1[arg_4])
        arg_0.h(arg_1[arg_3])


def Func(arg_0, arg_1, arg_2, arg_3=True):
    """
    Partial trace over subsystems of multi-partite vector.

    Args:
        vec (vector_like): complex vector N
        trace_systems (list(int)): a list of subsystems (starting from 0) to
                                  trace over.
        dimensions (list(int)): a list of the dimensions of the subsystems.
                                If this is not set it will assume all
                                subsystems are qubits.
        reverse (bool): ordering of systems in operator.
            If True system-0 is the right most system in tensor product.
            If False system-0 is the left most system in tensor product.

    Returns:
        ndarray: A density matrix with the appropriate subsystems traced over.
    """

    # trace sys positions
    if arg_3:
        arg_2 = arg_2[::-1]
        arg_1 = len(arg_2) - 1 - np.array(arg_1)

    arg_4 = arg_0.reshape(arg_2)
    arg_4 = np.tensordot(arg_4, arg_4.conj(), axes=(arg_1, arg_1))
    arg_5 = int(np.sqrt(np.product(arg_4.shape)))

    return arg_4.reshape(arg_5, arg_5)


def Func(arg_0, arg_1='col'):
    """Devectorize a vectorized square matrix.

    Args:
        vectorized_mat (ndarray): a vectorized density matrix.
        method (str): the method of devectorization. Allowed values are
            - 'col' (default): flattens to column-major vector.
            - 'row': flattens to row-major vector.
            - 'pauli': flattens in the n-qubit Pauli basis.
            - 'pauli-weights': flattens in the n-qubit Pauli basis ordered by
               weight.

    Returns:
        ndarray: the resulting matrix.
    Raises:
        Exception: if input state is not a n-qubit state
    """
    arg_0 = np.array(arg_0)
    arg_2 = int(np.sqrt(arg_0.size))
    if len(arg_0) != arg_2 * arg_2:
        raise Exception('Input is not a vectorized square matrix')

    if arg_1 == 'col':
        return arg_0.reshape(arg_2, arg_2, order='F')
    elif arg_1 == 'row':
        return arg_0.reshape(arg_2, arg_2, order='C')
    elif arg_1 in ['pauli', 'pauli_weights']:
        arg_3 = int(np.log2(arg_2))  # number of qubits
        if arg_2 != 2 ** arg_3:
            raise Exception('Input state must be n-qubit state')
        if arg_1 == 'pauli_weights':
            arg_4 = pauli_group(arg_3, case='weight')
        else:
            arg_4 = pauli_group(arg_3, case='tensor')
        arg_5 = np.array([p.to_matrix() for p in arg_4]) / 2 ** arg_3
        return np.tensordot(arg_0, arg_5, axes=1)
    return None


def Func(arg_0, arg_1=1):
    """
    Convert a Choi-matrix to a Pauli-basis superoperator.

    Note that this function assumes that the Choi-matrix
    is defined in the standard column-stacking convention
    and is normalized to have trace 1. For a channel E this
    is defined as: choi = (I \\otimes E)(bell_state).

    The resulting 'rauli' R acts on input states as
    |rho_out>_p = R.|rho_in>_p
    where |rho> = vectorize(rho, method='pauli') for order=1
    and |rho> = vectorize(rho, method='pauli_weights') for order=0.

    Args:
        choi (matrix): the input Choi-matrix.
        order (int): ordering of the Pauli group vector.
            order=1 (default) is standard lexicographic ordering.
                Eg: [II, IX, IY, IZ, XI, XX, XY,...]
            order=0 is ordered by weights.
                Eg. [II, IX, IY, IZ, XI, XY, XZ, XX, XY,...]

    Returns:
        np.array: A superoperator in the Pauli basis.
    """
    if arg_1 == 0:
        arg_1 = 'weight'
    elif arg_1 == 1:
        arg_1 = 'tensor'

    # get number of qubits'
    arg_2 = int(np.log2(np.sqrt(len(arg_0))))
    arg_3 = pauli_group(arg_2, case=arg_1)
    arg_4 = []
    for arg_5 in arg_3:
        for arg_6 in arg_3:
            arg_7 = np.kron(arg_6.to_matrix().T, arg_5.to_matrix())
            arg_4 += [np.trace(np.dot(arg_0, arg_7))]
    return np.array(arg_4).reshape(4 ** arg_2, 4 ** arg_2)


def Func(arg_0, arg_1=None):
    """
    Construct the Func product of two vectors.

    The second vector argument is optional, if absent the projector
    of the first vector will be returned.

    Args:
        vector1 (ndarray): the first vector.
        vector2 (ndarray): the (optional) second vector.

    Returns:
        np.array: The matrix |v1><v2|.

    """
    if arg_1 is None:
        arg_1 = np.array(arg_0).conj()
    else:
        arg_1 = np.array(arg_1).conj()
    return np.Func(arg_0, arg_1)


def Func(arg_0, arg_1=2):
    """
    Compute the Shannon entropy of a probability vector.

    The shannon entropy of a probability vector pv is defined as
    $H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.

    Args:
        pvec (array_like): a probability vector.
        base (int): the base of the logarith

    Returns:
        float: The Shannon entropy H(pvec).
    """
    # pylint: disable=missing-docstring
    if arg_1 == 2:
        def logfn(arg_2):
            return - arg_2 * np.log2(arg_2)
    elif arg_1 == np.e:
        def logfn(arg_2):
            return - arg_2 * np.log(arg_2)
    else:
        def logfn(arg_2):
            return -arg_2 * np.log(arg_2) / np.log(arg_1)

    arg_3 = 0.
    for arg_2 in arg_0:
        if 0 < arg_2 < 1:
            arg_3 += logfn(arg_2)
    return arg_3


def Func(arg_0):
    """
    Compute the von-Neumann Func of a quantum state.

    Args:
        state (array_like): a density matrix or state vector.

    Returns:
        float: The von-Neumann Func S(rho).
    """

    arg_1 = np.array(arg_0)
    if arg_1.ndim == 1:
        return 0
    arg_2 = np.maximum(np.linalg.eigvalsh(arg_0), 0.)
    return shannon_Func(arg_2, base=np.e)


def Func(arg_0, arg_1, arg_2=None):
    """
    Compute the mutual information of a bipartite state.

    Args:
        state (array_like): a bipartite state-vector or density-matrix.
        d0 (int): dimension of the first subsystem.
        d1 (int or None): dimension of the second subsystem.

    Returns:
        float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).
    """
    if arg_2 is None:
        arg_2 = int(len(arg_0) / arg_1)
    arg_3 = entropy(partial_trace(arg_0, [0], dimensions=[arg_1, arg_2]))
    arg_3 += entropy(partial_trace(arg_0, [1], dimensions=[arg_1, arg_2]))
    arg_3 -= entropy(arg_0)
    return arg_3


def Func(arg_0, arg_1, arg_2=None):
    """
    Compute the entanglement of formation of quantum state.

    The input quantum state must be either a bipartite state vector, or a
    2-qubit density matrix.

    Args:
        state (array_like): (N) array_like or (4,4) array_like, a
            bipartite quantum state.
        d0 (int): the dimension of the first subsystem.
        d1 (int or None): the dimension of the second subsystem.

    Returns:
        float: The entanglement of formation.
    """
    arg_0 = np.array(arg_0)

    if arg_2 is None:
        arg_2 = int(len(arg_0) / arg_1)

    if arg_0.ndim == 2 and len(arg_0) == 4 and arg_1 == 2 and arg_2 == 2:
        return __eof_qubit(arg_0)
    elif arg_0.ndim == 1:
        # trace out largest dimension
        if arg_1 < arg_2:
            arg_3 = [1]
        else:
            arg_3 = [0]
        arg_0 = partial_trace(arg_0, arg_3, dimensions=[arg_1, arg_2])
        return entropy(arg_0)
    else:
        print('Input must be a state-vector or 2-qubit density matrix.')
    return None


def Func(arg_0):
    """
    Compute the Entanglement of Formation of a 2-qubit density matrix.

    Args:
        rho ((array_like): (4,4) array_like, input density matrix.

    Returns:
        float: The entanglement of formation.
    """
    arg_1 = concurrence(arg_0)
    arg_1 = 0.5 + 0.5 * np.sqrt(1 - arg_1 * arg_1)
    return shannon_entropy([arg_1, 1 - arg_1])


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5 = None) -> Schedule:
    """Return schedule Funced by `time`.

    Args:
        schedule: The schedule to Func
        time: The time to Func by
        name: Name of Funced schedule. Defaults to name of `schedule`
    """
    if arg_4 is None:
        arg_4 = arg_0.name
    return union((arg_2, arg_0), arg_4=arg_4)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_1,
           arg_5: arg_6 = None) -> Schedule:
    """Return a new schedule with the `child` schedule Funced into the `parent` at `start_time`.

    Args:
        parent: Schedule to be Funced into
        time: Time to be Funced defined with respect to `parent`
        child: Schedule to Func
        name: Name of the new schedule. Defaults to name of parent
    """
    return union(arg_0, (arg_2, arg_4), arg_5=arg_5)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Apply Func to q."""
    return arg_0.append(U3Gate(arg_1, arg_2, arg_3), [arg_4], [])


def Func(arg_0, arg_1):
        """Start the progress bar.

        Parameters:
            iterations (int): Number of iterations.
        """
        arg_0.touched = True
        arg_0.iter = int(arg_1)
        arg_0.t_Func = time.time()


def Func(arg_0):
    """Dissasemble a qobj and return the circuits, run_config, and user header

    Args:
        qobj (Qobj): The input qobj object to dissasemble
    Returns:
        circuits (list): A list of quantum circuits
        run_config (dict): The dist of the run config
        user_qobj_header (dict): The dict of any user headers in the qobj

    """
    arg_1 = arg_0.config.to_dict()
    arg_2 = arg_0.header.to_dict()
    arg_3 = _experiments_to_circuits(arg_0)

    return arg_3, arg_1, arg_2


def Func(arg_0, arg_1):
    """Calculate the Hamming distance between two bit strings

    Args:
        str1 (str): First string.
        str2 (str): Second string.
    Returns:
        int: Distance between strings.
    Raises:
        VisualizationError: Strings not same length
    """
    if len(arg_0) != len(arg_1):
        raise VisualizationError('Strings not same length.')
    return sum(arg_2 != arg_3 for arg_2, arg_3 in zip(arg_0, arg_1))


def Func(arg_0, arg_1):
    """Return quaternion for rotation about given axis.

    Args:
        angle (float): Angle in radians.
        axis (str): Axis for rotation

    Returns:
        Quaternion: Quaternion for axis rotation.

    Raises:
        ValueError: Invalid input axis.
    """
    arg_2 = np.zeros(4, dtype=float)
    if arg_1 == 'x':
        arg_2[1] = 1
    elif arg_1 == 'y':
        arg_2[2] = 1
    elif arg_1 == 'z':
        arg_2[3] = 1
    else:
        raise ValueError('Invalid axis input.')
    arg_2 *= math.sin(arg_0/2.0)
    arg_2[0] = math.cos(arg_0/2.0)
    return Quaternion(arg_2)


def Func(arg_0, arg_1=False):
        """Normalizes a Quaternion to unit length
        so that it represents a valid rotation.

        Args:
            inplace (bool): Do an inplace normalization.

        Returns:
            Quaternion: Normalized quaternion.
        """
        if arg_1:
            arg_2 = arg_0.norm()
            arg_0.data /= arg_2
            return None
        arg_2 = arg_0.norm()
        arg_3 = np.array(arg_0.data, copy=True)
        arg_3 /= arg_2
        return Quaternion(arg_3)


def Func(arg_0):
        """Converts a unit-length quaternion to a rotation matrix.

        Returns:
            ndarray: Rotation matrix.
        """
        arg_1, arg_2, arg_3, arg_4 = arg_0.normalize().data  # pylint: disable=C0103
        arg_5 = np.array([
            [1-2*arg_3**2-2*arg_4**2, 2*arg_2*arg_3-2*arg_4*arg_1, 2*arg_2*arg_4+2*arg_3*arg_1],
            [2*arg_2*arg_3+2*arg_4*arg_1, 1-2*arg_2**2-2*arg_4**2, 2*arg_3*arg_4-2*arg_2*arg_1],
            [2*arg_2*arg_4-2*arg_3*arg_1, 2*arg_3*arg_4+2*arg_2*arg_1, 1-2*arg_2**2-2*arg_3**2]
        ], dtype=float)
        return arg_5


def Func(arg_0, arg_1, arg_2, arg_3):
        """Customize Func for handling containers."""
        # Check the type in the standard way first, in order to fail quickly
        # in case of invalid values.
        arg_4 = super(InstructionParameter, arg_0).Func(
            arg_1, arg_2, arg_3)

        if is_collection(arg_1):
            arg_5 = [super(InstructionParameter, arg_0).Func(item, arg_2, arg_3)
                 for item in arg_1]

        return arg_4


def Func(arg_0, arg_1):
        """Check that j is a valid index into self."""
        if isinstance(arg_1, int):
            if arg_1 < 0 or arg_1 >= arg_0.size:
                raise QiskitIndexError("register index out of range")
            elif isinstance(arg_1, slice):
                if arg_1.start < 0 or arg_1.stop >= arg_0.size or (arg_1.step is not None and
                                                          arg_1.step <= 0):
                    raise QiskitIndexError("register index slice out of range")


def Func(arg_0):
    """Test if an array is a square matrix."""
    arg_0 = np.array(arg_0)
    if arg_0.ndim != 2:
        return False
    arg_1 = arg_0.shape
    return arg_1[0] == arg_1[1]


def Func(arg_0, arg_1=arg_2, arg_3=arg_4):
    """Test if an array is a diagonal matrix"""
    if arg_3 is None:
        arg_3 = arg_4
    if arg_1 is None:
        arg_1 = arg_2
    arg_0 = np.array(arg_0)
    if arg_0.ndim != 2:
        return False
    return np.allclose(arg_0, np.diag(np.diagonal(arg_0)), arg_1=arg_1, arg_3=arg_3)


def Func(arg_0, arg_1=arg_2, arg_3=arg_4):
    """Test if an array is a symmetrix matrix"""
    if arg_3 is None:
        arg_3 = arg_4
    if arg_1 is None:
        arg_1 = arg_2
    arg_5 = np.array(arg_0)
    if arg_5.ndim != 2:
        return False
    return np.allclose(arg_5, arg_5.T, arg_1=arg_1, arg_3=arg_3)


def Func(arg_0, arg_1=arg_2, arg_3=arg_4):
    """Test if an array is a Hermitian matrix"""
    if arg_3 is None:
        arg_3 = arg_4
    if arg_1 is None:
        arg_1 = arg_2
    arg_0 = np.array(arg_0)
    if arg_0.ndim != 2:
        return False
    return np.allclose(arg_0, np.conj(arg_0.T), arg_1=arg_1, arg_3=arg_3)


def Func(arg_0,
                       arg_1=False,
                       arg_2=arg_3,
                       arg_4=arg_5):
    """Test if an array is an identity matrix."""
    if arg_4 is None:
        arg_4 = arg_5
    if arg_2 is None:
        arg_2 = arg_3
    arg_0 = np.array(arg_0)
    if arg_0.ndim != 2:
        return False
    if arg_1:
        # If the matrix is equal to an identity up to a phase, we can
        # remove the phase by multiplying each entry by the complex
        # conjugate of the phase of the [0, 0] entry.
        arg_6 = np.angle(arg_0[0, 0])
        arg_0 = np.exp(-1j * arg_6) * arg_0
    # Check if square identity
    arg_7 = np.eye(len(arg_0))
    return np.allclose(arg_0, arg_7, arg_2=arg_2, arg_4=arg_4)


def Func(arg_0, arg_1=arg_2, arg_3=arg_4):
    """Test if an array is a unitary matrix."""
    if arg_3 is None:
        arg_3 = arg_4
    if arg_1 is None:
        arg_1 = arg_2
    arg_0 = np.array(arg_0)
    # Compute A^dagger.A and see if it is identity matrix
    arg_0 = np.conj(arg_0.T).dot(arg_0)
    return is_identity_matrix(arg_0, ignore_phase=False, arg_1=arg_1, arg_3=arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Transform a QuantumChannel to the Choi representation."""
    if arg_0 == 'Choi':
        return arg_1
    if arg_0 == 'Operator':
        return _from_operator('Choi', arg_1, arg_2, arg_3)
    if arg_0 == 'SuperOp':
        return _superopFunc(arg_1, arg_2, arg_3)
    if arg_0 == 'Kraus':
        return _krausFunc(arg_1, arg_2, arg_3)
    if arg_0 == 'Chi':
        return _chiFunc(arg_1, arg_2, arg_3)
    if arg_0 == 'PTM':
        arg_1 = _ptm_to_superop(arg_1, arg_2, arg_3)
        return _superopFunc(arg_1, arg_2, arg_3)
    if arg_0 == 'Stinespring':
        return _stinespringFunc(arg_1, arg_2, arg_3)
    raise QiskitError('Invalid QuantumChannel {}'.format(arg_0))


def Func(arg_0, arg_1, arg_2, arg_3):
    """Transform a QuantumChannel to the PTM representation."""
    if arg_0 == 'PTM':
        return arg_1
    # Check valid n-qubit input
    _check_nqubit_dim(arg_2, arg_3)
    if arg_0 == 'Operator':
        return _from_operator('PTM', arg_1, arg_2, arg_3)
    # Convert via Superoperator representation
    if arg_0 != 'SuperOp':
        arg_1 = _to_superop(arg_0, arg_1, arg_2, arg_3)
    return _superopFunc(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Transform Operator representation to other representation."""
    if arg_0 == 'Operator':
        return arg_1
    if arg_0 == 'SuperOp':
        return np.kron(np.conj(arg_1), arg_1)
    if arg_0 == 'Choi':
        arg_4 = np.ravel(arg_1, order='F')
        return np.outer(arg_4, np.conj(arg_4))
    if arg_0 == 'Kraus':
        return ([arg_1], None)
    if arg_0 == 'Stinespring':
        return (arg_1, None)
    if arg_0 == 'Chi':
        _check_nqubit_dim(arg_2, arg_3)
        arg_1 = Func('Choi', arg_1, arg_2, arg_3)
        return _choi_to_chi(arg_1, arg_2, arg_3)
    if arg_0 == 'PTM':
        _check_nqubit_dim(arg_2, arg_3)
        arg_1 = Func('SuperOp', arg_1, arg_2, arg_3)
        return _superop_to_ptm(arg_1, arg_2, arg_3)
    raise QiskitError('Invalid QuantumChannel {}'.format(arg_0))


def Func(arg_0, arg_1, arg_2):
    """Transform Stinespring representation to Operator representation."""
    arg_3 = arg_0[0].shape[0] // arg_2
    if arg_0[1] is not None or arg_3 != 1:
        raise QiskitError(
            'Channel cannot be converted to Operator representation')
    return arg_0[0]


def Func(arg_0, arg_1, arg_2):
    """Transform SuperOp representation to Choi representation."""
    arg_3 = (arg_2, arg_2, arg_1, arg_1)
    return _reshuffle(arg_0, arg_3)


def Func(arg_0, arg_1, arg_2):
    """Transform Choi to SuperOp representation."""
    arg_3 = (arg_1, arg_2, arg_1, arg_2)
    return _reshuffle(arg_0, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3=arg_4):
    """Transform Choi representation to Kraus representation."""
    # Check if hermitian matrix
    if is_hermitian_matrix(arg_0, arg_3=arg_3):
        # Get eigen-decomposition of Choi-matrix
        arg_5, arg_6 = la.eigh(arg_0)
        # Check eigenvaleus are non-negative
        if len(arg_5[arg_5 < -arg_3]) == 0:
            # CP-map Kraus representation
            arg_7 = []
            for arg_8, arg_9 in zip(arg_5, arg_6.T):
                if abs(arg_8) > arg_3:
                    arg_10 = np.sqrt(arg_8) * arg_9.reshape(
                        (arg_2, arg_1), order='F')
                    arg_7.append(arg_10)
            # If we are converting a zero matrix, we need to return a Kraus set
            # with a single zero-element Kraus matrix
            if not arg_7:
                arg_7.append(np.zeros((arg_2, arg_1), dtype=complex))
            return (arg_7, None)
    # Non-CP-map generalized Kraus representation
    arg_11, arg_12, arg_13 = la.svd(arg_0)
    arg_14 = []
    arg_15 = []
    for arg_8, arg_16, arg_17 in zip(arg_12, arg_11.T, arg_13.conj()):
        arg_14.append(
            np.sqrt(arg_8) * arg_16.reshape((arg_2, arg_1), order='F'))
        arg_15.append(
            np.sqrt(arg_8) * arg_17.reshape((arg_2, arg_1), order='F'))
    return (arg_14, arg_15)


def Func(arg_0, arg_1, arg_2):
    """Transform Stinespring representation to Choi representation."""
    arg_3 = arg_0[0].shape[0] // arg_2
    arg_4 = np.reshape(arg_0[0], (arg_2, arg_3, arg_1))
    if arg_0[1] is None:
        arg_5 = arg_4
    else:
        arg_5 = np.reshape(arg_0[1], (arg_2, arg_3, arg_1))
    return np.reshape(
        np.einsum('iAj,kAl->jilk', arg_4, arg_5.conj()),
        2 * [arg_1 * arg_2])


def Func(arg_0, arg_1, arg_2):
    """Transform Chi representation to a Choi representation."""
    arg_3 = int(np.log2(arg_1))
    return _transform_from_pauli(arg_0, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Reravel two bipartite matrices."""
    # Reshuffle indicies
    arg_4 = arg_2[:2] + arg_3[:2]
    arg_5 = arg_2[2:] + arg_3[2:]
    arg_6 = arg_4 + arg_5
    arg_7 = (np.product(arg_4), np.product(arg_5))
    # Tensor product matrices
    arg_8 = np.kron(arg_0, arg_1)
    arg_8 = np.reshape(
        np.transpose(np.reshape(arg_8, arg_6), (0, 2, 1, 3, 4, 6, 5, 7)),
        arg_7)
    return arg_8


def Func(arg_0):
        """Resets Bloch sphere data sets to empty.
        """
        arg_0.points = []
        arg_0.vectors = []
        arg_0.point_style = []
        arg_0.annotations = []


def Func(arg_0, arg_1, arg_2, **arg_3):
        """Add a text or LaTeX annotation to Bloch sphere,
        parametrized by a qubit state or a vector.

        Args:
            state_or_vector (array_like):
                Position for the annotation.
                Qobj of a qubit or a vector of 3 elements.
            text (str):
                Annotation text.
                You can use LaTeX, but remember to use raw string
                e.g. r"$\\langle x \\rangle$"
                or escape backslashes
                e.g. "$\\\\langle x \\\\rangle$".
            **kwargs:
                Options as for mplot3d.axes3d.text, including:
                fontsize, color, horizontalalignment, verticalalignment.
        Raises:
            Exception: If input not array_like or tuple.
        """
        if isinstance(arg_1, (list, np.ndarray, tuple)) \
                and len(arg_1) == 3:
            arg_4 = arg_1
        else:
            raise Exception("Position needs to be specified by a qubit " +
                            "state or a 3D vector.")
        arg_0.annotations.append({'position': arg_4,
                                 'text': arg_2,
                                 'opts': arg_3})


def Func(arg_0, arg_1=''):
        """
        Render the Bloch sphere and its data sets in on given figure and axes.
        """
        if arg_0._Funced:
            arg_0.axes.clear()

        arg_0._Funced = True

        # Figure instance for Bloch sphere plot
        if not arg_0._ext_fig:
            arg_0.fig = plt.figure(figsize=arg_0.figsize)

        if not arg_0._ext_axes:
            arg_0.axes = Axes3D(arg_0.fig, azim=arg_0.view[0], elev=arg_0.view[1])

        if arg_0.background:
            arg_0.axes.clear()
            arg_0.axes.set_xlim3d(-1.3, 1.3)
            arg_0.axes.set_ylim3d(-1.3, 1.3)
            arg_0.axes.set_zlim3d(-1.3, 1.3)
        else:
            arg_0.plot_axes()
            arg_0.axes.set_axis_off()
            arg_0.axes.set_xlim3d(-0.7, 0.7)
            arg_0.axes.set_ylim3d(-0.7, 0.7)
            arg_0.axes.set_zlim3d(-0.7, 0.7)

        arg_0.axes.grid(False)
        arg_0.plot_back()
        arg_0.plot_points()
        arg_0.plot_vectors()
        arg_0.plot_front()
        arg_0.plot_axes_labels()
        arg_0.plot_annotations()
        arg_0.axes.set_title(arg_1, fontsize=arg_0.font_size, y=1.08)


def Func(arg_0):
        """front half of sphere"""
        arg_1 = np.linspace(-np.pi, 0, 25)
        arg_2 = np.linspace(0, np.pi, 25)
        arg_3 = np.outer(np.cos(arg_1), np.sin(arg_2))
        arg_4 = np.outer(np.sin(arg_1), np.sin(arg_2))
        arg_5 = np.outer(np.ones(arg_1.shape[0]), np.cos(arg_2))
        arg_0.axes.plot_surface(arg_3, arg_4, arg_5, rstride=2, cstride=2,
                               color=arg_0.sphere_color, linewidth=0,
                               alpha=arg_0.sphere_alpha)
        # wireframe
        arg_0.axes.plot_wireframe(arg_3, arg_4, arg_5, rstride=5, cstride=5,
                                 color=arg_0.frame_color,
                                 alpha=arg_0.frame_alpha)
        # equator
        arg_0.axes.plot(1.0 * np.cos(arg_1), 1.0 * np.sin(arg_1),
                       zs=0, zdir='z', lw=arg_0.frame_width,
                       color=arg_0.frame_color)
        arg_0.axes.plot(1.0 * np.cos(arg_1), 1.0 * np.sin(arg_1),
                       zs=0, zdir='x', lw=arg_0.frame_width,
                       color=arg_0.frame_color)


def Func(arg_0, arg_1=''):
        """
        Display Bloch sphere and corresponding data sets.
        """
        arg_0.render(arg_1=arg_1)
        if arg_0.fig:
            plt.Func(arg_0.fig)


def Func(arg_0):
        """ Constructs the Func line of the element"""
        arg_1 = arg_0.Func_format % arg_0.Func_connect.center(
            arg_0.width, arg_0.Func_pad)
        if arg_0.right_fill:
            arg_1 = arg_1.ljust(arg_0.right_fill, arg_0.Func_pad)
        if arg_0.left_fill:
            arg_1 = arg_1.rjust(arg_0.left_fill, arg_0.Func_pad)
        arg_1 = arg_1.center(arg_0.layer_width, arg_0.Func_bck)
        return arg_1


def Func(arg_0):
        """ Constructs the Functom line of the element"""
        arg_1 = arg_0.Func_format % arg_0.Func_connect.center(
            arg_0.width, arg_0.Func_pad)
        if arg_0.right_fill:
            arg_1 = arg_1.ljust(arg_0.right_fill, arg_0.Func_pad)
        if arg_0.left_fill:
            arg_1 = arg_1.rjust(arg_0.left_fill, arg_0.Func_pad)
        arg_1 = arg_1.center(arg_0.layer_width, arg_0.Func_bck)
        return arg_1


def Func(arg_0):
        """Get the params and format them to add them to a label. None if there
         are no params of if the params are numpy.ndarrays."""

        if not hasattr(arg_0.op, 'params'):
            return None
        if all([isinstance(arg_1, ndarray) for arg_1 in arg_0.op.params]):
            return None

        arg_2 = []
        for arg_1 in arg_0.op.params:
            if isinstance(arg_1, (sympy.Number, float)):
                arg_2.append('%.5g' % arg_1)
            else:
                arg_2.append('%s' % arg_1)
        return arg_2


def Func(arg_0):
        """ Creates the label for a box."""
        arg_1 = arg_0.name.capitalize()
        arg_2 = TextDrawing.params_for_label(arg_0)
        if arg_2:
            arg_1 += "(%s)" % ','.join(arg_2)
        return arg_1


def Func():
    """Apply filters to deprecation warnings.

    Force the `DeprecationWarning` warnings to be displayed for the qiskit
    module, overriding the system configuration as they are ignored by default
    [1] for end-users. Additionally, silence the `ChangedInMarshmallow3Warning`
    messages.

    TODO: on Python 3.7, this might not be needed due to PEP-0565 [2].

    [1] https://docs.python.org/3/library/warnings.html#default-warning-filters
    [2] https://www.python.org/dev/peps/pep-0565/
    """
    arg_0 = ('always', None, DeprecationWarning,
                          re.compile(r'^qiskit\.*', re.UNICODE), 0)

    # Instead of using warnings.simple_filter() directly, the internal
    # _add_filter() function is used for being able to match against the
    # module.
    try:
        warnings._add_filter(*arg_0, append=False)
    except AttributeError:
        # ._add_filter is internal and not available in some Python versions.
        pass

    # Add a filter for ignoring ChangedInMarshmallow3Warning, as we depend on
    # marhsmallow 2 explicitly. 2.17.0 introduced new deprecation warnings that
    # are useful for eventually migrating, but too verbose for our purposes.
    warnings.simplefilter('ignore', category=ChangedInMarshmallow3Warning)


def Func():
    """Basic hardware information about the local machine.

    Gives actual number of CPU's in the machine, even when hyperthreading is
    turned on. CPU count defaults to 1 when true count can't be determined.

    Returns:
        dict: The hardware information.
    """
    arg_0 = {
        'os': platform.system(),
        'memory': psutil.virtual_memory().total / (1024 ** 3),
        'cpus': psutil.cpu_count(logical=False) or 1
    }
    return arg_0


def Func(arg_0, arg_1, arg_2, arg_3,
                  arg_4=False):
    """Internal function that updates the status
    of a HTML job monitor.

    Args:
        job_var (BaseJob): The job to keep track of.
        interval (int): The status check interval
        status (widget): HTML ipywidget for output ot screen
        header (str): String representing HTML code for status.
        _interval_set (bool): Was interval set by user?
    """
    arg_5 = arg_0.status()
    arg_6 = arg_5.name
    arg_7 = arg_5.value
    arg_2.value = arg_3 % (arg_7)
    while arg_6 not in ['DONE', 'CANCELLED']:
        time.sleep(arg_1)
        arg_5 = arg_0.status()
        arg_6 = arg_5.name
        arg_7 = arg_5.value
        if arg_6 == 'ERROR':
            break
        else:
            if arg_6 == 'QUEUED':
                arg_7 += ' (%s)' % arg_0.queue_position()
                if not arg_4:
                    arg_1 = max(arg_0.queue_position(), 2)
            else:
                if not arg_4:
                    arg_1 = 2
            arg_2.value = arg_3 % (arg_7)

    arg_2.value = arg_3 % (arg_7)


def Func(arg_0: arg_1.ndarray, arg_3: arg_4) -> arg_1.ndarray:
    """Continuous Func pulse.

    Args:
        times: Times to output pulse for.
        amp: Complex pulse amplitude.
    """
    return arg_1.full(len(arg_0), arg_3, dtype=arg_1.complex_)


def Func(arg_0: arg_1.ndarray, arg_3: arg_4, arg_5: arg_6, arg_7: arg_6 = 0) -> arg_1.ndarray:
    """Continuous Func wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt.
        phase: Pulse phase.
    """
    return arg_3*(-2*arg_1.abs(sawtooth(arg_0, 1, arg_5, (arg_7-arg_1.pi/2)/2)) + 1).astype(arg_1.complex_)


def Func(arg_0: arg_1.ndarray, arg_3: arg_4, arg_5: arg_6, arg_7: arg_6 = 0) -> arg_1.ndarray:
    """Continuous Funcine wave.

    Args:
        times: Times to output wave for.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt.
        phase: Pulse phase.
    """
    return arg_3*arg_1.Func(2*arg_1.pi*arg_5*arg_0+arg_7).astype(arg_1.complex_)


def Func(arg_0, arg_1: arg_2, arg_3: arg_2, arg_4: arg_2,
                        arg_5: arg_6[None, arg_2] = None, arg_7: arg_8 = False,
                        arg_9: arg_8 = False) -> np.ndarray:
    r"""Enforce that the supplied gaussian pulse is zeroed at a specific width.

    This is acheived by subtracting $\Omega_g(center \pm zeroed_width/2)$ from all samples.

    amp: Pulse amplitude at `2\times center+1`.
    center: Center (mean) of pulse.
    sigma: Width (standard deviation) of pulse.
    zeroed_width: Subtract baseline to gaussian pulses to make sure
             $\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
             large discontinuities at the start of a gaussian pulse. If unsupplied,
             defaults to $2*(center+1)$ such that the samples are zero at $\Omega_g(-1)$.
    rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
                 be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
    ret_scale_factor: Return amplitude scale factor.
    """
    if arg_5 is None:
        arg_5 = 2*(arg_3+1)

    arg_10 = gaussian(np.array([-arg_5/2]), arg_1, arg_3, arg_4)
    arg_0 -= arg_10
    arg_11 = 1.
    if arg_7:
        arg_11 = arg_1/(arg_1-arg_10)
        arg_0 *= arg_11

    if arg_9:
        return arg_0, arg_11
    return arg_0


def Func(arg_0: arg_1.ndarray, arg_3: arg_4, arg_5: arg_6, arg_7: arg_6,
             arg_8: arg_9[None, arg_6] = None, arg_10: arg_11 = False,
             arg_12: arg_11 = False) -> arg_9[arg_1.ndarray, Tuple[arg_1.ndarray, arg_1.ndarray]]:
    r"""Continuous unnormalized Func pulse.

    Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`. If `zeroed_width` is set pulse amplitude at center
            will be $amp-\Omega_g(center\pm zeroed_width/2)$ unless `rescale_amp` is set,
            in which case all samples will be rescaled such that the center
            amplitude will be `amp`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        zeroed_width: Subtract baseline to Func pulses to make sure
                 $\Omega_g(center \pm zeroed_width/2)=0$ is satisfied. This is used to avoid
                 large discontinuities at the start of a Func pulse.
        rescale_amp: If `zeroed_width` is not `None` and `rescale_amp=True` the pulse will
                     be rescaled so that $\Omega_g(center)-\Omega_g(center\pm zeroed_width/2)=amp$.
        ret_x: Return centered and standard deviation normalized pulse location.
               $x=(times-center)/sigma.
    """
    arg_0 = arg_1.asarray(arg_0, dtype=arg_1.complex_)
    arg_13 = (arg_0-arg_5)/arg_7
    arg_14 = arg_3*arg_1.exp(-arg_13**2/2).astype(arg_1.complex_)

    if arg_8 is not None:
        arg_14 = _fix_Func_width(arg_14, arg_3=arg_3, arg_5=arg_5, arg_7=arg_7,
                                    arg_8=arg_8, arg_10=arg_10)

    if arg_12:
        return arg_14, arg_13
    return arg_14


def Func(arg_0: arg_1.ndarray, arg_3: arg_4, arg_5: arg_6, arg_7: arg_6,
                   arg_8: arg_9 = False) -> arg_1.ndarray:
    """Continuous unnormalized gaussian derivative pulse.

    Args:
        times: Times to output pulse for.
        amp: Pulse amplitude at `center`.
        center: Center (mean) of pulse.
        sigma: Width (standard deviation) of pulse.
        ret_gaussian: Return gaussian with which derivative was taken with.
    """
    arg_10, arg_11 = gaussian(arg_0, arg_3=arg_3, arg_5=arg_5, arg_7=arg_7, ret_x=True)
    arg_12 = -arg_11/arg_7*arg_10
    if arg_8:
        return arg_12, arg_10
    return arg_12


def Func(arg_0, arg_1):
        """
        Test if this circuit has the register r.

        Args:
            register (Register): a quantum or classical register.

        Returns:
            bool: True if the register is contained in this circuit.
        """
        arg_2 = False
        if (isinstance(arg_1, QuantumRegister) and
                arg_1 in arg_0.qregs):
            arg_2 = True
        elif (isinstance(arg_1, ClassicalRegister) and
              arg_1 in arg_0.cregs):
            arg_2 = True
        return arg_2


def Func(arg_0):
        """Mirror the circuit by reversing the instructions.

        This is done by recursively Funcing all instructions.
        It does not invert any gate.

        Returns:
            QuantumCircuit: the Funced circuit
        """
        arg_1 = arg_0.copy(name=arg_0.name+'_Func')
        arg_1.data = []
        for arg_3, arg_4, arg_5 in reversed(arg_0.data):
            arg_1.data.append((arg_3.Func(), arg_4, arg_5))
        return arg_1


def Func(arg_0):
        """Invert this circuit.

        This is done by recursively inverting all gates.

        Returns:
            QuantumCircuit: the inverted circuit

        Raises:
            QiskitError: if the circuit cannot be inverted.
        """
        arg_1 = arg_0.copy(name=arg_0.name+'_dg')
        arg_1.data = []
        for arg_3, arg_4, arg_5 in reversed(arg_0.data):
            arg_1.data.append((arg_3.Func(), arg_4, arg_5))
        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
        """DEPRECATED after 0.8"""
        arg_0.append(arg_1, arg_2, arg_3)


def Func(arg_0, *arg_1):
        """Add registers."""
        if not arg_1:
            return

        if any([isinstance(arg_2, int) for arg_2 in arg_1]):
            # QuantumCircuit defined without registers
            if len(arg_1) == 1 and isinstance(arg_1[0], int):
                # QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2)
                arg_1 = (QuantumRegister(arg_1[0], 'q'),)
            elif len(arg_1) == 2 and all([isinstance(arg_2, int) for arg_2 in arg_1]):
                # QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)
                arg_1 = (QuantumRegister(arg_1[0], 'q'), ClassicalRegister(arg_1[1], 'c'))
            else:
                raise QiskitError("QuantumCircuit parameters can be Registers or Integers."
                                  " If Integers, up to 2 arguments. QuantumCircuit was called"
                                  " with %s." % (arg_1,))

        for arg_3 in arg_1:
            if arg_3 in arg_0.qregs or arg_3 in arg_0.cregs:
                raise QiskitError("register name \"%s\" already exists"
                                  % arg_3.name)
            if isinstance(arg_3, QuantumRegister):
                arg_0.qregs.append(arg_3)
            elif isinstance(arg_3, ClassicalRegister):
                arg_0.cregs.append(arg_3)
            else:
                raise QiskitError("expected a register")


def Func(arg_0, arg_1):
        """Raise exception if list of qubits contains duplicates."""
        arg_2 = set(arg_1)
        if len(arg_2) != len(arg_1):
            raise QiskitError("duplicate qubit arguments")


def Func(arg_0, arg_1):
        """Raise exception if a qarg is not in this circuit or bad format."""
        if not all(isinstance(arg_2, tuple) and
                   isinstance(arg_2[0], QuantumRegister) and
                   isinstance(arg_2[1], int) for arg_2 in arg_1):
            raise QiskitError("qarg not (QuantumRegister, int) tuple")
        if not all(arg_0.has_register(arg_2[0]) for arg_2 in arg_1):
            raise QiskitError("register not in this circuit")
        for arg_3 in arg_1:
            arg_3[0].check_range(arg_3[1])


def Func(arg_0, arg_1):
        """Raise exception if clbit is not in this circuit or bad format."""
        if not all(isinstance(arg_2, tuple) and
                   isinstance(arg_2[0], ClassicalRegister) and
                   isinstance(arg_2[1], int) for arg_2 in arg_1):
            raise QiskitError("carg not (ClassicalRegister, int) tuple")
        if not all(arg_0.has_register(arg_2[0]) for arg_2 in arg_1):
            raise QiskitError("register not in this circuit")
        for arg_3 in arg_1:
            arg_3[0].check_range(arg_3[1])


def Func(arg_0, arg_1):
        """Raise exception if the circuits are defined on incompatible registers"""
        arg_2 = arg_0.qregs + arg_0.cregs
        arg_3 = arg_1.qregs + arg_1.cregs
        for arg_4 in arg_2:
            for arg_5 in arg_3:
                if arg_5.name == arg_4.name:
                    if arg_4 != arg_5:
                        raise QiskitError("circuits are not compatible")


def Func(arg_0):
        """Return OpenQASM string."""
        arg_1 = arg_0.header + "\n"
        arg_1 += arg_0.extension_lib + "\n"
        for arg_2 in arg_0.qregs:
            arg_1 += arg_2.Func() + "\n"
        for arg_2 in arg_0.cregs:
            arg_1 += arg_2.Func() + "\n"
        for arg_3, arg_4, arg_5 in arg_0.data:
            if arg_3.name == 'measure':
                arg_6 = arg_4[0]
                arg_7 = arg_5[0]
                arg_1 += "%s %s[%d] -> %s[%d];\n" % (arg_3.Func(),
                                                           arg_6[0].name, arg_6[1],
                                                           arg_7[0].name, arg_7[1])
            else:
                arg_1 += "%s %s;\n" % (arg_3.Func(),
                                             ",".join(["%s[%d]" % (arg_8[0].name, arg_8[1])
                                                       for arg_8 in arg_4 + arg_5]))
        return arg_1


def Func(arg_0):
        """Count each operation kind in the circuit.

        Returns:
            dict: a breakdown of how many operations of each kind.
        """
        Func = {}
        for arg_2, arg_3, arg_3 in arg_0.data:
            if arg_2.name in Func.keys():
                Func[arg_2.name] += 1
            else:
                Func[arg_2.name] = 1
        return Func


def Func(arg_0, arg_1=False):
        """How many non-entangled subcircuits can the circuit be factored to.

        Args:
            unitary_only (bool): Compute only unitary part of graph.

        Returns:
            int: Number of connected components in circuit.
        """
        # Convert registers to ints (as done in depth).
        arg_2 = 0
        arg_3 = {}

        if arg_1:
            arg_4 = arg_0.qregs
        else:
            arg_4 = arg_0.qregs+arg_0.cregs

        for arg_5 in arg_4:
            arg_3[arg_5.name] = arg_2
            arg_2 += arg_5.size
        # Start with each qubit or cbit being its own subgraph.
        arg_7 = [[bit] for bit in range(arg_2)]

        arg_8 = len(arg_7)

        # Here we are traversing the gates and looking to see
        # which of the sub_graphs the gate joins together.
        for arg_9, arg_10, arg_11 in arg_0.data:
            if arg_1:
                arg_12 = arg_10
                arg_13 = len(arg_12)
            else:
                arg_12 = arg_10+arg_11
                arg_13 = len(arg_12) + (1 if arg_9.control else 0)

            if arg_13 >= 2 and arg_9.name not in ['barrier', 'snapshot']:
                arg_14 = []
                arg_15 = 0
                # Controls necessarily join all the cbits in the
                # register that they use.
                if arg_9.control and not arg_1:
                    arg_16 = arg_9.control[0]
                    arg_17 = arg_3[arg_16.name]
                    for arg_18 in range(arg_16.size):
                        arg_19 = arg_17+arg_18
                        for arg_20 in range(arg_8):
                            if arg_19 in arg_7[arg_20]:
                                arg_14.append(arg_20)
                                arg_15 += 1
                                break

                for arg_21 in arg_12:
                    arg_22 = arg_3[arg_21[0].name]+arg_21[1]
                    for arg_20 in range(arg_8):
                        if arg_22 in arg_7[arg_20]:
                            if arg_20 not in arg_14:
                                arg_14.append(arg_20)
                                arg_15 += 1
                                break

                # If the gate touches more than one subgraph
                # join those graphs together and return
                # reduced number of subgraphs
                if arg_15 > 1:
                    arg_23 = []
                    for arg_24 in arg_14:
                        arg_23.extend(arg_7[arg_24])
                    arg_25 = []
                    for arg_24 in range(arg_8):
                        if arg_24 not in arg_14:
                            arg_25.append(arg_7[arg_24])
                    arg_25.append(arg_23)
                    arg_7 = arg_25
                    arg_8 -= (arg_15-1)
            # Cannot go lower than one so break
            if arg_8 == 1:
                break
        return arg_8


def Func(arg_0, arg_1):
        """Assign parameters to values yielding a new circuit.

        Args:
            value_dict (dict): {parameter: value, ...}

        Raises:
            QiskitError: If value_dict contains parameters not present in the circuit

        Returns:
            QuantumCircuit: copy of self with assignment substitution.
        """
        arg_2 = arg_0.copy()

        if arg_1.keys() > arg_0.parameters:
            raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format(
                [str(arg_3) for arg_3 in arg_1.keys() - arg_0.parameters]))

        for arg_4, arg_5 in arg_1.items():
            arg_2._bind_parameter(arg_4, arg_5)
        # clear evaluated expressions
        for arg_4 in arg_1:
            del arg_2._parameter_table[arg_4]
        return arg_2


def Func(arg_0, arg_1, arg_2=None, arg_3='None',
                 arg_4=None, arg_5=False,
                 arg_6=150, arg_7=1000, arg_8=(6, 5)):
    """Plot the interpolated envelope of pulse

    Args:
        samples (ndarray): Data points of complex pulse envelope.
        duration (int): Pulse length (number of points).
        dt (float): Time interval of samples.
        interp_method (str): Method of interpolation
            (set `None` for turn off the interpolation).
        filename (str): Name required to save pulse image.
        interactive (bool): When set true show the circuit in a new window
            (this depends on the matplotlib backend being used supporting this).
        dpi (int): Resolution of saved image.
        nop (int): Data points for interpolation.
        size (tuple): Size of figure.
    Returns:
        matplotlib.figure: A matplotlib figure object for the pulse envelope.
    Raises:
        ImportError: when the output methods requieres non-installed libraries.
        QiskitError: when invalid interpolation method is specified.
    """

    try:
        from matplotlib import pyplot as plt
    except ImportError:
        raise ImportError('Func need matplotlib. '
                          'Run "pip install matplotlib" before.')

    if arg_2:
        arg_9 = arg_2
    else:
        arg_9 = 1

    arg_10 = np.real(arg_0)
    arg_11 = np.imag(arg_0)

    arg_12 = plt.figure(figsize=arg_8)
    arg_13 = arg_12.add_subplot(111)

    if arg_3 == 'CubicSpline':
        # spline interpolation, use mid-point of dt
        arg_14 = np.arange(0, arg_1 + 1) * arg_9 + 0.5 * arg_9
        arg_15 = CubicSpline(arg_14[:-1], arg_10)
        arg_16 = CubicSpline(arg_14[:-1], arg_11)

        arg_17 = np.linspace(0, arg_1 * arg_9, arg_7)
        arg_18 = arg_15(arg_17)
        arg_19 = arg_16(arg_17)
    elif arg_3 == 'None':
        # pseudo-DAC output
        arg_14 = np.arange(0, arg_1 + 1) * arg_9

        arg_17 = np.r_[arg_14[0], np.repeat(arg_14[1:-1], 2), arg_14[-1]]
        arg_18 = np.repeat(arg_10, 2)
        arg_19 = np.repeat(arg_11, 2)
    else:
        raise QiskitError('Invalid interpolation method "%s"' % arg_3)

    # plot
    arg_13.fill_between(x=arg_17, y1=arg_18, y2=np.zeros_like(arg_17),
                     facecolor='red', alpha=0.3,
                     edgecolor='red', linewidth=1.5,
                     label='real part')
    arg_13.fill_between(x=arg_17, y1=arg_19, y2=np.zeros_like(arg_17),
                     facecolor='blue', alpha=0.3,
                     edgecolor='blue', linewidth=1.5,
                     label='imaginary part')

    arg_13.set_xlim(0, arg_1 * arg_9)
    arg_13.grid(b=True, linestyle='-')
    arg_13.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center',
               ncol=2, frameon=False, fontsize=14)

    if arg_4:
        arg_12.savefig(arg_4, arg_6=arg_6, bbox_inches='tight')

    plt.close(arg_12)

    if arg_12 and arg_5:
        plt.show(arg_12)

    return arg_12


def Func(arg_0, arg_1, arg_2,
                            arg_3=arg_4, arg_5=arg_6):
    """Search for SWAPs which allow for application of largest number of gates.

    Arguments:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap of the target backend.
        depth (int): Number of SWAP layers to search before choosing a result.
        width (int): Number of SWAPs to consider at each layer.
    Returns:
        dict: Describes solution step found.
            layout (Layout): Virtual to physical qubit map after SWAPs.
            gates_remaining (list): Gates that could not be mapped.
            gates_mapped (list): Gates that were mapped, including added SWAPs.

    """

    arg_7, arg_8 = _map_free_gates(arg_0, arg_1, arg_2)

    arg_9 = {'layout': arg_0,
                 'swaps_added': 0,
                 'gates_mapped': arg_7,
                 'gates_remaining': arg_8}

    if not arg_8 or arg_3 == 0:
        return arg_9

    arg_10 = arg_2.get_edges()

    def _score_swap(arg_11):
        """Calculate the relative score for a given SWAP."""
        arg_12 = arg_0.copy()
        arg_12.swap(*arg_11)
        return _calc_layout_distance(arg_1, arg_2, arg_12)

    arg_13 = sorted(arg_10, key=_score_swap)

    arg_14, arg_15 = None, None
    for arg_11 in arg_13[:arg_5]:
        arg_12 = arg_0.copy()
        arg_12.swap(*arg_11)
        arg_16 = Func(arg_12, arg_8,
                                            arg_2, arg_3 - 1, arg_5)

        # ranked_swaps already sorted by distance, so distance is the tie-breaker.
        if arg_14 is None or _score_step(arg_16) > _score_step(arg_15):
            arg_14, arg_15 = arg_11, arg_16

    arg_17 = _swap_ops_from_edge(arg_14, arg_0)
    return {
        'layout': arg_15['layout'],
        'swaps_added': 1 + arg_15['swaps_added'],
        'gates_remaining': arg_15['gates_remaining'],
        'gates_mapped': arg_7 + arg_17 + arg_15['gates_mapped'],
    }


def Func(arg_0, arg_1, arg_2):
    """Map all gates that can be executed with the current layout.

    Args:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap for target device topology.

    Returns:
        tuple:
            mapped_gates (list): ops for gates that can be executed, mapped onto layout.
            remaining_gates (list): gates that cannot be executed on the layout.

    """

    arg_3 = set()

    arg_4 = []
    arg_5 = []

    for arg_6 in arg_1:
        # Gates without a partition (barrier, snapshot, save, load, noise) may
        # still have associated qubits. Look for them in the qargs.
        if not arg_6['partition']:
            arg_7 = [n for n in arg_6['graph'].nodes() if n.type == 'op'][0].qargs

            if not arg_7:
                continue

            if arg_3.intersection(arg_7):
                arg_3.update(arg_7)
                arg_5.append(arg_6)
            else:
                arg_8 = _transform_gate_for_layout(arg_6, arg_0)
                arg_4.append(arg_8)
            continue

        arg_7 = arg_6['partition'][0]

        if arg_3.intersection(arg_7):
            arg_3.update(arg_7)
            arg_5.append(arg_6)
        elif len(arg_7) == 1:
            arg_8 = _transform_gate_for_layout(arg_6, arg_0)
            arg_4.append(arg_8)
        elif arg_2.distance(*[arg_0[arg_9] for arg_9 in arg_7]) == 1:
            arg_8 = _transform_gate_for_layout(arg_6, arg_0)
            arg_4.append(arg_8)
        else:
            arg_3.update(arg_7)
            arg_5.append(arg_6)

    return arg_4, arg_5


def Func(arg_0, arg_1, arg_2, arg_3=None):
    """Return the sum of the distances of two-qubit pairs in each CNOT in gates
    according to the layout and the coupling.
    """

    if arg_3 is None:
        arg_3 = 50 + 10 * len(arg_1.physical_qubits)

    return sum(arg_1.distance(*[arg_2[arg_4] for arg_4 in arg_5['partition'][0]])
               for arg_5 in arg_0[:arg_3]
               if arg_5['partition'] and len(arg_5['partition'][0]) == 2)


def Func(arg_0, arg_1):
    """Return a copy of source_dag with metadata but empty.
    Generate only a single qreg in the output DAG, matching the size of the
    coupling_map."""

    arg_2 = DAGCircuit()
    arg_2.name = arg_0.name

    for arg_4 in arg_0.cregs.values():
        arg_2.add_creg(arg_4)

    arg_5 = QuantumRegister(len(arg_1.physical_qubits), 'q')
    arg_2.add_qreg(arg_5)

    return arg_2


def Func(arg_0, arg_1):
    """Return op implementing a virtual gate on given layout."""

    arg_2 = deepcopy([n for n in arg_0['graph'].nodes() if n.type == 'op'][0])

    # Workaround until #1816, apply mapped to qargs to both DAGNode and op
    arg_3 = QuantumRegister(len(arg_1.get_physical_bits()), 'q')
    arg_4 = [(arg_3, arg_1[a]) for a in arg_2.qargs]
    arg_2.qargs = arg_2.op.qargs = arg_4

    arg_2.pop('name')

    return arg_2


def Func(arg_0, arg_1):
    """Generate list of ops to implement a SWAP gate along a coupling edge."""

    arg_2 = QuantumRegister(len(arg_1.get_physical_bits()), 'q')
    arg_3 = [(arg_2, i) for i in arg_0]

    # TODO shouldn't be making other nodes not by the DAG!!
    return [
        DAGNode({'op': SwapGate(), 'qargs': arg_3, 'cargs': [], 'type': 'op'})
    ]


def Func(arg_0, arg_1):
        """Run one pass of the lookahead mapper on the provided DAG.

        Args:
            dag (DAGCircuit): the directed acyclic graph to be mapped
        Returns:
            DAGCircuit: A dag mapped to be compatible with the coupling_map in
                the property_set.
        Raises:
            TranspilerError: if the coupling map or the layout are not
            compatible with the DAG
        """
        arg_2 = arg_0._coupling_map
        arg_3 = list(arg_1.serial_layers())

        if arg_0.initial_layout is None:
            if arg_0.property_set["layout"]:
                arg_0.initial_layout = arg_0.property_set["layout"]
            else:
                arg_0.initial_layout = Layout.generate_trivial_layout(*arg_1.qregs.values())

        if len(arg_1.qubits()) != len(arg_0.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(arg_0._coupling_map.physical_qubits) != len(arg_0.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        arg_5 = []
        arg_6 = arg_0.initial_layout.copy()
        arg_7 = arg_3.copy()

        while arg_7:
            arg_8 = _search_forward_n_swaps(arg_6, arg_7,
                                                arg_2)

            arg_6 = arg_8['layout']
            arg_9 = arg_8['gates_mapped']
            arg_7 = arg_8['gates_remaining']

            arg_5.extend(arg_9)

        # Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
        arg_10 = _copy_circuit_metadata(arg_1, arg_2)

        for arg_11 in arg_5:
            arg_10.apply_operation_back(op=arg_11.op, qargs=arg_11.qargs, cargs=arg_11.cargs)

        return arg_10


def Func(arg_0, arg_1):
        """Add a physical qubit to the coupling graph as a node.

        physical_qubit (int): An integer representing a physical qubit.

        Raises:
            CouplingError: if trying to add duplicate qubit
        """
        if not isinstance(arg_1, int):
            raise CouplingError("Physical qubits should be integers.")
        if arg_1 in arg_0.physical_qubits:
            raise CouplingError(
                "The physical qubit %s is already in the coupling graph" % arg_1)
        arg_0.graph.add_node(arg_1)
        arg_0._dist_matrix = None  # invalidate
        arg_0._qubit_list = None


def Func(arg_0, arg_1):
        """Return a CouplingMap object for a Func of self.

        nodelist (list): list of integer node labels
        """
        arg_2 = CouplingMap()
        arg_2.graph = arg_0.graph.Func(arg_1)
        for arg_4 in arg_1:
            if arg_4 not in arg_2.physical_qubits:
                arg_2.add_physical_qubit(arg_4)
        return arg_2


def Func(arg_0):
        """Returns a sorted list of Func"""
        if arg_0._qubit_list is None:
            arg_0._qubit_list = sorted([pqubit for pqubit in arg_0.graph.nodes])
        return arg_0._qubit_list


def Func(arg_0):
        """Compute the full distance matrix on pairs of nodes.

        The distance map self._dist_matrix is computed from the graph using
        all_pairs_shortest_path_length.
        """
        if not arg_0.is_connected():
            raise CouplingError("coupling graph not connected")
        arg_1 = nx.all_pairs_shortest_path_length(arg_0.graph.to_undirected(as_view=True))
        arg_1 = dict(arg_1)
        arg_2 = len(arg_1)
        arg_3 = arg_5.zeros((arg_2, arg_2))
        for arg_4 in range(arg_2):
            arg_3[arg_4, arg_5.fromiter(arg_1[arg_4].keys(), arg_8=arg_9)] = arg_5.fromiter(
                arg_1[arg_4].values(), arg_8=arg_9)
        arg_0._dist_matrix = arg_3


def Func(arg_0, arg_1, arg_2):
        """Returns the undirected Func between physical_qubit1 and physical_qubit2.

        Args:
            physical_qubit1 (int): A physical qubit
            physical_qubit2 (int): Another physical qubit

        Returns:
            int: The undirected Func

        Raises:
            CouplingError: if the qubits do not exist in the CouplingMap
        """
        if arg_1 not in arg_0.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (arg_1,))
        if arg_2 not in arg_0.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (arg_2,))
        if arg_0._dist_matrix is None:
            arg_0._compute_Func_matrix()
        return arg_0._dist_matrix[arg_1, arg_2]


def Func(arg_0, *arg_1):
        """Add controls to all instructions."""
        for arg_2 in arg_0.instructions:
            arg_2.Func(*arg_1)
        return arg_0


def Func(arg_0, arg_1, arg_2):
        """Add classical control register to all instructions."""
        for arg_3 in arg_0.instructions:
            arg_3.Func(arg_1, arg_2)
        return arg_0


def Func(arg_0, arg_1, arg_2):
        """Subscribes to an event, so when it's emitted all the callbacks Funcd,
        will be executed. We are not allowing double registration.

        Args
            event (string): The event to Funcd in the form of:
                            "terra.<component>.<method>.<action>"
            callback (callable): The callback that will be executed when an event is
                                  emitted.
        """
        if not callable(arg_2):
            raise QiskitError("Callback is not a callable!")

        if arg_1 not in arg_0._Funcrs:
            arg_0._Funcrs[arg_1] = []

        arg_4 = arg_0._Subscription(arg_1, arg_2)
        if arg_4 in arg_0._Funcrs[arg_1]:
            # We are not allowing double subscription
            return False

        arg_0._Funcrs[arg_1].append(arg_4)
        return True


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """Emits an event if there are any subscribers.

        Args
            event (String): The event to be emitted
            args: Arguments linked with the event
            kwargs: Named arguments linked with the event
        """
        # No event, no subscribers.
        if arg_1 not in arg_0._subscribers:
            return

        for arg_4 in arg_0._subscribers[arg_1]:
            arg_4.callback(*arg_2, **arg_3)


def Func(arg_0, arg_1, arg_2):
        """ Unsubscribe the specific callback to the event.

        Args
            event (String): The event to Func
            callback (callable): The callback that won't be executed anymore

        Returns
            True: if we have successfully Funcd to the event
            False: if there's no callback previously registered
        """

        try:
            arg_0._subscribers[arg_1].remove(arg_0._Subscription(arg_1, arg_2))
        except KeyError:
            return False

        return True


def Func(arg_0):
        """
        Call to create a circuit with gates that take the
        desired vector to zero.

        Returns:
            QuantumCircuit: circuit to take self.params vector to |00..0>
        """
        arg_1 = QuantumRegister(arg_0.num_qubits)
        arg_2 = QuantumCircuit(arg_1, name='disentangler')

        # kick start the peeling loop, and disentangle one-by-one from LSB to MSB
        arg_3 = arg_0.params

        for arg_4 in range(arg_0.num_qubits):
            # work out which rotations must be done to disentangle the LSB
            # qubit (we peel away one qubit at a time)
            (arg_3,
             arg_5,
             arg_6) = Initialize._rotations_to_disentangle(arg_3)

            # perform the required rotations to decouple the LSB qubit (so that
            # it can be "factored" out, leaving a shorter amplitude vector to peel away)
            arg_7 = arg_0._multiplex(RZGate, arg_6)
            arg_8 = arg_0._multiplex(RYGate, arg_5)
            arg_2.append(arg_7.to_instruction(), arg_1[arg_4:arg_0.num_qubits])
            arg_2.append(arg_8.to_instruction(), arg_1[arg_4:arg_0.num_qubits])
        return arg_2


def Func(arg_0):
        """Checks if value has the format of a virtual qubit """
        return arg_0 is None or isinstance(arg_0, tuple) and len(arg_0) == 2 and isinstance(
            arg_0[0], Register) and isinstance(arg_0[1], int)


def Func(arg_0):
        """Returns a Func of a Layout instance."""
        arg_1 = type(arg_0)()

        arg_1._p2v = arg_0._p2v.Func()
        arg_1._v2p = arg_0._v2p.Func()

        return arg_1


def Func(arg_0, arg_1):
        """
        Checks if the attribute name is in the list of attributes to protect. If so, raises
        TranspilerAccessError.

        Args:
            name (string): the attribute name to check

        Raises:
            TranspilerAccessError: when name is the list of attributes to protect.
        """
        if arg_1 in object.__getattribute__(arg_0, '_attributes_to_fence'):
            raise TranspilerAccessError("The fenced %s has the property %s protected" %
                                        (type(object.__getattribute__(arg_0, '_wrapped')), arg_1))


def Func(arg_0, arg_1):
        """
        Run the StochasticSwap pass on `dag`.

        Args:
            dag (DAGCircuit): DAG to map.

        Returns:
            DAGCircuit: A mapped DAG.

        Raises:
            TranspilerError: if the coupling map or the layout are not
            compatible with the DAG
        """

        if arg_0.initial_layout is None:
            if arg_0.property_set["layout"]:
                arg_0.initial_layout = arg_0.property_set["layout"]
            else:
                arg_0.initial_layout = Layout.generate_trivial_layout(*arg_1.qregs.values())

        if len(arg_1.qubits()) != len(arg_0.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(arg_0.coupling_map.physical_qubits) != len(arg_0.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        arg_0.input_layout = arg_0.initial_layout.copy()

        arg_0.qregs = arg_1.qregs
        if arg_0.seed is None:
            arg_0.seed = np.random.randint(0, np.iinfo(np.int32).max)
        arg_0.rng = np.random.RandomState(arg_0.seed)
        logger.debug("StochasticSwap RandomState seeded with seed=%s", arg_0.seed)

        arg_7 = arg_0._mapper(arg_1, arg_0.coupling_map, trials=arg_0.trials)
        # self.property_set["layout"] = self.initial_layout
        return arg_7


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                      arg_5, arg_6):
        """Provide a DAGCircuit for a new mapped layer.

        i (int) = layer number
        first_layer (bool) = True if this is the first layer in the
            circuit with any multi-qubit gates
        best_layout (Layout) = layout returned from _layer_permutation
        best_depth (int) = depth returned from _layer_permutation
        best_circuit (DAGCircuit) = swap circuit returned
            from _layer_permutation
        layer_list (list) = list of DAGCircuit objects for each layer,
            output of DAGCircuit layers() method

        Return a DAGCircuit object to append to the output DAGCircuit
        that the _mapper method is building.
        """
        arg_7 = arg_3
        logger.debug("layer_update: layout = %s", pformat(arg_7))
        logger.debug("layer_update: self.initial_layout = %s", pformat(arg_0.initial_layout))
        arg_8 = DAGCircuit()
        for arg_9 in arg_7.get_virtual_bits().keys():
            if arg_9[0] not in arg_8.qregs.values():
                arg_8.add_qreg(arg_9[0])

        # If this is the first layer with multi-qubit gates,
        # output all layers up to this point and ignore any
        # swap gates. Set the initial layout.
        if arg_2:
            logger.debug("layer_update: first multi-qubit gate layer")
            # Output all layers up to this point
            for arg_10 in range(arg_1 + 1):
                # Make qubit edge map and extend by classical bits
                arg_11 = arg_7.combine_into_edge_map(arg_0.initial_layout)
                for arg_12 in arg_8.clbits():
                    arg_11[arg_12] = arg_12
                arg_8.compose_back(arg_6[arg_10]["graph"], arg_11)
        # Otherwise, we output the current layer and the associated swap gates.
        else:
            # Output any swaps
            if arg_4 > 0:
                logger.debug("layer_update: there are swaps in this layer, "
                             "depth %d", arg_4)
                arg_8.extend_back(arg_5)
            else:
                logger.debug("layer_update: there are no swaps in this layer")
            # Make qubit edge map and extend by classical bits
            arg_11 = arg_7.combine_into_edge_map(arg_0.initial_layout)
            for arg_12 in arg_8.clbits():
                arg_11[arg_12] = arg_12
            # Output this layer
            arg_8.compose_back(arg_6[arg_1]["graph"], arg_11)

        return arg_8


def Func(arg_0, arg_1='weight'):
    """Return the Pauli group with 4^n elements.

    The phases have been removed.
    case 'weight' is ordered by Pauli weights and
    case 'tensor' is ordered by I,X,Y,Z counting lowest qubit fastest.

    Args:
        number_of_qubits (int): number of qubits
        case (str): determines ordering of group elements ('weight' or 'tensor')

    Returns:
        list: list of Pauli objects

    Raises:
        QiskitError: case is not 'weight' or 'tensor'
        QiskitError: number_of_qubits is larger than 4
    """
    if arg_0 < 5:
        arg_2 = []

        if arg_1 == 'weight':
            arg_3 = Func(arg_0, arg_1='tensor')
            # sort on the weight of the Pauli operator
            return sorted(arg_3, key=lambda arg_6: -np.count_nonzero(
                np.array(arg_6.to_label(), 'c') == b'I'))
        elif arg_1 == 'tensor':
            # the Pauli set is in tensor order II IX IY IZ XI ...
            for arg_4 in range(4 ** arg_0):
                arg_5 = np.zeros(arg_0, dtype=np.bool)
                arg_6 = np.zeros(arg_0, dtype=np.bool)
                # looping over all the qubits
                for arg_7 in range(arg_0):
                    # making the Pauli for each j fill it in from the
                    # end first
                    arg_8 = (arg_4 // (4 ** arg_7)) % 4
                    if arg_8 == 1:
                        arg_6[arg_7] = True
                    elif arg_8 == 2:
                        arg_5[arg_7] = True
                        arg_6[arg_7] = True
                    elif arg_8 == 3:
                        arg_5[arg_7] = True
                arg_2.append(Pauli(arg_5, arg_6))
            return arg_2
        else:
            raise QiskitError("Only support 'weight' or 'tensor' cases "
                              "but you have {}.".format(arg_1))

    raise QiskitError("Only support number of qubits is less than 5")


def Func(arg_0, arg_1, arg_2):
        """Construct pauli from boolean array.

        Args:
            z (numpy.ndarray): boolean, z vector
            x (numpy.ndarray): boolean, x vector

        Returns:
            Pauli: self

        Raises:
            QiskitError: if z or x are None or the length of z and x are different.
        """
        if arg_1 is None:
            raise QiskitError("z vector must not be None.")
        if arg_2 is None:
            raise QiskitError("x vector must not be None.")
        if len(arg_1) != len(arg_2):
            raise QiskitError("length of z and x vectors must be "
                              "the same. (z: {} vs x: {})".format(len(arg_1), len(arg_2)))

        arg_1 = _make_np_bool(arg_1)
        arg_2 = _make_np_bool(arg_2)
        arg_0._z = arg_1
        arg_0._x = arg_2

        return arg_0


def Func(arg_0):
        """Convert to Operator object."""
        # Place import here to avoid cyclic import from circuit visualization
        from qiskit.quantum_info.operators.operator import Operator
        return Operator(arg_0.to_matrix())


def Func(arg_0):
        """Convert to Pauli circuit instruction."""
        from qiskit.circuit import QuantumCircuit, QuantumRegister
        from qiskit.extensions.standard import IdGate, XGate, YGate, ZGate
        arg_1 = {'I': IdGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()}
        arg_2 = arg_0.to_label()
        arg_3 = arg_0.numberofqubits
        arg_4 = QuantumRegister(arg_3)
        arg_5 = QuantumCircuit(arg_4, name='Pauli:{}'.format(arg_2))
        for arg_6, arg_7 in enumerate(reversed(arg_2)):
            arg_5.append(arg_1[arg_7], [arg_4[arg_6]])
        return arg_5.Func()


def Func(arg_0, arg_1, arg_2=None):
        """
        Update partial or entire x.

        Args:
            x (numpy.ndarray or list): to-be-updated x
            indices (numpy.ndarray or list or optional): to-be-updated qubit indices

        Returns:
            Pauli: self

        Raises:
            QiskitError: when updating whole x, the number of qubits must be the same.
        """
        arg_1 = _make_np_bool(arg_1)
        if arg_2 is None:
            if len(arg_0._x) != len(arg_1):
                raise QiskitError("During updating whole x, you can not change "
                                  "the number of qubits.")
            arg_0._x = arg_1
        else:
            if not isinstance(arg_2, list) and not isinstance(arg_2, np.ndarray):
                arg_2 = [arg_2]
            for arg_4, arg_5 in enumerate(arg_2):
                arg_0._x[arg_5] = arg_1[arg_4]

        return arg_0


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Append pauli at the end.

        Args:
            paulis (Pauli): the to-be-inserted or appended pauli
            pauli_labels (list[str]): the to-be-inserted or appended pauli label

        Returns:
            Pauli: self
        """
        return arg_0.insert_paulis(None, arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1):
        """
        Delete pauli at the indices.

        Args:
            indices(list[int]): the indices of to-be-deleted paulis

        Returns:
            Pauli: self
        """
        if not isinstance(arg_1, list):
            arg_1 = [arg_1]

        arg_0._z = np.delete(arg_0._z, arg_1)
        arg_0._x = np.delete(arg_0._x, arg_1)

        return arg_0


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Generate single qubit pauli at index with pauli_label with length num_qubits.

        Args:
            num_qubits (int): the length of pauli
            index (int): the qubit index to insert the single qubii
            pauli_label (str): pauli

        Returns:
            Pauli: single qubit pauli
        """
        arg_4 = Pauli.from_label(arg_3)
        arg_5 = np.zeros(arg_1, dtype=np.bool)
        arg_6 = np.zeros(arg_1, dtype=np.bool)

        arg_5[arg_2] = arg_4.z[0]
        arg_6[arg_2] = arg_4.x[0]

        return arg_0(arg_5, arg_6)


def Func(arg_0, arg_1):
        """Simulate the outcome of measurement of a qubit.

        Args:
            qubit (int): the qubit to measure

        Return:
            tuple: pair (outcome, probability) where outcome is '0' or '1' and
            probability is the probability of the returned outcome.
        """
        # Axis for numpy.sum to compute probabilities
        arg_2 = list(range(arg_0._number_of_qubits))
        arg_2.remove(arg_0._number_of_qubits - 1 - arg_1)
        arg_3 = np.sum(np.abs(arg_0._statevector) ** 2, arg_2=tuple(arg_2))
        # Compute einsum index string for 1-qubit matrix multiplication
        arg_4 = arg_0._local_random.rand()
        if arg_4 < arg_3[0]:
            return '0', arg_3[0]
        # Else outcome was '1'
        return '1', arg_3[1]


def Func(arg_0, arg_1, arg_2):
        """Generate memory samples from current statevector.

        Args:
            measure_params (list): List of (qubit, cmembit) values for
                                   measure instructions to sample.
            num_samples (int): The number of memory samples to generate.

        Returns:
            list: A list of memory values in hex format.
        """
        # Get unique qubits that are actually measured
        arg_3 = list({arg_6 for arg_6, arg_13 in arg_1})
        arg_4 = len(arg_3)
        # Axis for numpy.sum to compute probabilities
        arg_5 = list(range(arg_0._number_of_qubits))
        for arg_6 in reversed(arg_3):
            # Remove from largest qubit to smallest so list position is correct
            # with respect to position from end of the list
            arg_5.remove(arg_0._number_of_qubits - 1 - arg_6)
        arg_7 = np.reshape(np.sum(np.abs(arg_0._statevector) ** 2,
                                          arg_5=tuple(arg_5)),
                                   2 ** arg_4)
        # Generate samples on measured qubits
        arg_8 = arg_0._local_random.choice(range(2 ** arg_4),
                                            arg_2, p=arg_7)
        # Convert to bit-strings
        arg_9 = []
        for arg_10 in arg_8:
            arg_11 = arg_0._classical_memory
            for arg_12, (arg_6, arg_13) in enumerate(sorted(arg_1)):
                arg_14 = int((arg_10 & (1 << arg_12)) >> arg_12)
                arg_15 = 1 << arg_13
                arg_11 = (arg_11 & (~arg_15)) | (arg_14 << arg_13)
            arg_16 = bin(arg_11)[2:]
            arg_9.append(hex(int(arg_16, 2)))
        return arg_9


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """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.
        """
        # get measure outcome
        arg_4, arg_5 = arg_0._get_measure_outcome(arg_1)
        # update classical state
        arg_6 = 1 << arg_2
        arg_0._classical_memory = (arg_0._classical_memory & (~arg_6)) | (int(arg_4) << arg_2)

        if arg_3 is not None:
            arg_8 = 1 << arg_3
            arg_0._classical_register = \
                (arg_0._classical_register & (~arg_8)) | (int(arg_4) << arg_3)

        # update quantum state
        if arg_4 == '0':
            arg_10 = [[1 / np.sqrt(arg_5), 0], [0, 0]]
        else:
            arg_10 = [[0, 0], [0, 1 / np.sqrt(arg_5)]]
        # update classical state
        arg_0._add_unitary_single(arg_10, arg_1)


def Func(arg_0, arg_1):
        """Apply a reset instruction to a qubit.

        Args:
            qubit (int): the qubit being rest

        This is done by doing a simulating a measurement
        outcome and projecting onto the outcome state while
        renormalizing.
        """
        # get measure outcome
        arg_2, arg_3 = arg_0._get_measure_outcome(arg_1)
        # update quantum state
        if arg_2 == '0':
            arg_4 = [[1 / np.sqrt(arg_3), 0], [0, 0]]
            arg_0._add_unitary_single(arg_4, arg_1)
        else:
            arg_4 = [[0, 1 / np.sqrt(arg_3)], [0, 0]]
            arg_0._add_unitary_single(arg_4, arg_1)


def Func(arg_0):
        """Validate an initial statevector"""
        # If initial statevector isn't set we don't need to validate
        if arg_0._initial_statevector is None:
            return
        # Check statevector is correct length for number of qubits
        arg_1 = len(arg_0._initial_statevector)
        arg_2 = 2 ** arg_0._number_of_qubits
        if arg_1 != arg_2:
            raise BasicAerError('initial statevector is incorrect length: ' +
                                '{} != {}'.format(arg_1, arg_2))


def Func(arg_0):
        """Set the initial statevector for simulation"""
        if arg_0._initial_statevector is None:
            # Set to default state of all qubits in |0>
            arg_0._statevector = np.zeros(2 ** arg_0._number_of_qubits,
                                         dtype=complex)
            arg_0._statevector[0] = 1
        else:
            arg_0._statevector = arg_0._initial_statevector.copy()
        # Reshape to rank-N tensor
        arg_0._statevector = np.reshape(arg_0._statevector,
                                       arg_0._number_of_qubits * [2])


def Func(arg_0, arg_1):
        """Determine if measure sampling is allowed for an experiment

        Args:
            experiment (QobjExperiment): a qobj experiment.
        """
        # If shots=1 we should disable measure sampling.
        # This is also required for statevector simulator to return the
        # correct final statevector without silently dropping final measurements.
        if arg_0._shots <= 1:
            arg_0._sample_measure = False
            return

        # Check for config flag
        if hasattr(arg_1.config, 'allows_measure_sampling'):
            arg_0._sample_measure = arg_1.config.allows_measure_sampling
        # If flag isn't found do a simple test to see if a circuit contains
        # no reset instructions, and no gates instructions after
        # the first measure.
        else:
            arg_3 = False
            for arg_4 in arg_1.instructions:
                # If circuit contains reset operations we cannot sample
                if arg_4.name == "reset":
                    arg_0._sample_measure = False
                    return
                # If circuit contains a measure option then we can
                # sample only if all following operations are measures
                if arg_3:
                    # If we find a non-measure instruction
                    # we cannot do measure sampling
                    if arg_4.name not in ["measure", "barrier", "id", "u0"]:
                        arg_0._sample_measure = False
                        return
                elif arg_4.name == "measure":
                    arg_3 = True
            # If we made it to the end of the circuit without returning
            # measure sampling is allowed
            arg_0._sample_measure = True


def Func(arg_0, arg_1, arg_2=None):
        """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),
                }
        """
        arg_0._set_options(qobj_config=arg_1.config,
                          arg_2=arg_2)
        arg_3 = str(uuid.uuid4())
        arg_4 = BasicAerJob(arg_0, arg_3, arg_0._Func_job, arg_1)
        arg_4.submit()
        return arg_4


def Func(arg_0, arg_1, arg_2):
        """Run experiments in qobj

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object
        """
        arg_0._validate(arg_2)
        arg_3 = []
        arg_0._shots = arg_2.config.shots
        arg_0._memory = getattr(arg_2.config, 'memory', False)
        arg_0._qobj_config = arg_2.config
        arg_7 = time.time()
        for arg_8 in arg_2.experiments:
            arg_3.append(arg_0.run_experiment(arg_8))
        arg_9 = time.time()
        arg_10 = {'backend_name': arg_0.name(),
                  'backend_version': arg_0._configuration.backend_version,
                  'qobj_id': arg_2.qobj_id,
                  'job_id': arg_1,
                  'results': arg_3,
                  'status': 'COMPLETED',
                  'success': True,
                  'time_taken': (arg_9 - arg_7),
                  'header': arg_2.header.as_dict()}

        return Result.from_dict(arg_10)


def Func(arg_0, arg_1):
        """Semantic validations of the qobj which cannot be done via schemas."""
        arg_2 = arg_1.config.n_qubits
        arg_3 = arg_0.configuration().n_qubits
        if arg_2 > arg_3:
            raise BasicAerError('Number of qubits {} '.format(arg_2) +
                                'is greater than maximum ({}) '.format(arg_3) +
                                'for "{}".'.format(arg_0.name()))
        for arg_4 in arg_1.experiments:
            arg_5 = arg_4.header.name
            if arg_4.config.memory_slots == 0:
                logger.warning('No classical registers in circuit "%s", '
                               'counts will be empty.', arg_5)
            elif 'measure' not in [arg_6.name for arg_6 in arg_4.instructions]:
                logger.warning('No measurements in circuit "%s", '
                               'classical register will remain all zeros.', arg_5)


def Func(arg_0):
        """Validate an initial unitary matrix"""
        # If initial unitary isn't set we don't need to validate
        if arg_0._initial_unitary is None:
            return
        # Check unitary is correct length for number of qubits
        arg_1 = np.shape(arg_0._initial_unitary)
        arg_2 = (2 ** arg_0._number_of_qubits,
                          2 ** arg_0._number_of_qubits)
        if arg_1 != arg_2:
            raise BasicAerError('initial unitary is incorrect shape: ' +
                                '{} != 2 ** {}'.format(arg_1, arg_2))


def Func(arg_0):
        """Set the initial unitary for simulation"""
        arg_0._validate_initial_unitary()
        if arg_0._initial_unitary is None:
            # Set to identity matrix
            arg_0._unitary = np.eye(2 ** arg_0._number_of_qubits,
                                   dtype=complex)
        else:
            arg_0._unitary = arg_0._initial_unitary.copy()
        # Reshape to rank-N tensor
        arg_0._unitary = np.reshape(arg_0._unitary,
                                   arg_0._number_of_qubits * [2, 2])


def Func(arg_0):
        """Return the current unitary in JSON Result spec format"""
        arg_1 = np.reshape(arg_0._unitary, 2 * [2 ** arg_0._number_of_qubits])
        # Expand complex numbers
        arg_1 = np.stack((arg_1.real, arg_1.imag), axis=-1)
        # Truncate small values
        arg_1[arg_2(arg_1) < arg_0._chop_threshold] = 0.0
        return arg_1


def Func(arg_0, arg_1):
        """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
        """
        arg_2 = arg_1.config.n_qubits
        arg_3 = arg_0.configuration().n_qubits
        if arg_2 > arg_3:
            raise BasicAerError('Number of qubits {} '.format(arg_2) +
                                'is greater than maximum ({}) '.format(arg_3) +
                                'for "{}".'.format(arg_0.name()))
        if hasattr(arg_1.config, 'shots') and arg_1.config.shots != 1:
            logger.info('"%s" only supports 1 shot. Setting shots=1.',
                        arg_0.name())
            arg_1.config.shots = 1
        for arg_6 in arg_1.experiments:
            arg_7 = arg_6.header.name
            if getattr(arg_6.config, 'shots', 1) != 1:
                logger.info('"%s" only supports 1 shot. '
                            'Setting shots=1 for circuit "%s".',
                            arg_0.name(), arg_7)
                arg_6.config.shots = 1
            for arg_8 in arg_6.instructions:
                if arg_8.name in ['measure', 'reset']:
                    raise BasicAerError('Unsupported "%s" instruction "%s" ' +
                                        'in circuit "%s" ', arg_0.name(),
                                        arg_8.name, arg_7)


def Func(arg_0):
    """Determine if obj is a bit"""
    # If there is a bit type this could be replaced by isinstance.
    if isinstance(arg_0, tuple) and len(arg_0) == 2:
        if isinstance(arg_0[0], Register) and isinstance(arg_0[1], int) and arg_0[1] < len(arg_0[0]):
            return True
    return False


def Func(arg_0, arg_1):
        """
        Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1.

        Args:
            dag (DAGCircuit): DAG to find layout for.

        Raises:
            TranspilerError: if dag wider than self.coupling_map
        """
        arg_2 = sum([qreg.size for qreg in arg_1.qregs.values()])
        if arg_2 > arg_0.coupling_map.size():
            raise TranspilerError('Number of qubits greater than device.')
        arg_0.property_set['layout'] = Layout.generate_trivial_layout(*arg_1.qregs.values())


def Func(arg_0, *arg_1: arg_2[arg_3]) -> int:
        """Return maximum time of timeslots over all channels.

        Args:
            *channels: Channels over which to obtain stop time.
        """
        arg_4 = list(itertools.chain(*(arg_0._table[chan] for chan in arg_1
                                           if chan in arg_0._table)))
        if arg_4:
            return max((arg_5.end for arg_5 in arg_4))
        return 0


def Func(arg_0, arg_1: arg_2) -> 'TimeslotCollection':
        """Return a new TimeslotCollection Funced by `time`.

        Args:
            time: time to be Funced by
        """
        arg_3 = [Timeslot(slot.interval.Func(arg_1), slot.channel) for slot in arg_0.timeslots]
        return TimeslotCollection(*arg_3)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Report on GitHub that the specified branch is failing to build at
        the specified commit. The method will open an issue indicating that
        the branch is failing. If there is an issue already open, it will add a
        comment avoiding to Func twice about the same failure.

        Args:
            branch (str): branch name to Func about.
            commit (str): commit hash at which the build fails.
            infourl (str): URL with extra info about the failure such as the
                build logs.
        """
        arg_4 = arg_0._get_Func_issue_number()
        if arg_4:
            arg_0._Func_as_comment(arg_4, arg_1, arg_2, arg_3)
        else:
            arg_0._Func_as_issue(arg_1, arg_2, arg_3)


def Func(arg_0):
    """ Sort rho data """
    arg_1 = dict()

    arg_2 = int(np.log2(len(arg_0)))
    arg_3 = list(map(lambda x: x.to_label(), pauli_group(arg_2)))
    arg_4 = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), arg_0))),
                      pauli_group(arg_2)))

    for arg_5, arg_6 in enumerate(arg_3):
        arg_1[arg_6] = arg_4[arg_5]
    return arg_1


def Func(arg_0, arg_1=None, arg_2=False, arg_3=False):
    """ Create a paulivec representation.

        Graphical representation of the input array.

        Args:
            rho (array): State vector or density matrix.
            figsize (tuple): Figure size in pixels.
            slider (bool): activate slider
            show_legend (bool): show legend of graph content
    """

    # HTML
    arg_4 = Template("""

    """)

    # JavaScript
    arg_5 = Template("""

    """)
    arg_0 = _validate_input_state(arg_0)
    # set default figure size if none given
    if arg_1 is None:
        arg_1 = (7, 5)

    arg_6 = {'width': arg_1[0], 'height': arg_1[1],
               'slider': int(arg_2), 'show_legend': int(arg_3)}

    # Process data and execute
    arg_7 = str(time.time())
    arg_7 = re.sub('[.]', '', arg_7)

    arg_8 = []
    arg_9 = process_data(arg_0)
    arg_8.append(dict(
        data=arg_9
    ))

    arg_10 = arg_4.substitute({
        'divNumber': arg_7
    })

    arg_11 = arg_5.substitute({
        'divNumber': arg_7,
        'executions': arg_8,
        'options': arg_6
    })

    display(HTML(arg_10 + arg_11))


def Func(arg_0, arg_1, arg_2, arg_3):
    """Apply RZZ to circuit."""
    return arg_0.append(RZZGate(arg_1), [arg_2, arg_3], [])


def Func(arg_0, arg_1, arg_2, arg_3):
    """Apply Fredkin to circuit."""
    return arg_0.append(FredkinGate(), [arg_1, arg_2, arg_3], [])


def Func(arg_0):
        """
        Extract readout and CNOT errors and compute swap costs.
        """
        arg_1 = arg_0.backend_prop
        for arg_2 in arg_1.gates:
            if arg_2.gate == 'cx':
                for arg_3 in arg_2.parameters:
                    if arg_3.name == 'gate_error':
                        arg_4 = 1.0 - arg_3.value
                        break
                    else:
                        arg_4 = 1.0
                arg_5 = -math.log(pow(arg_4, 3))
                arg_0.swap_graph.add_edge(arg_2.qubits[0], arg_2.qubits[1], weight=arg_5)
                arg_0.swap_graph.add_edge(arg_2.qubits[1], arg_2.qubits[0], weight=arg_5)
                arg_0.cx_errors[(arg_2.qubits[0], arg_2.qubits[1])] = arg_4
                arg_0.gate_list.append((arg_2.qubits[0], arg_2.qubits[1]))
        arg_8 = 0
        for arg_9 in arg_1.qubits:
            for arg_10 in arg_9:
                if arg_10.name == 'readout_error':
                    arg_0.readout_errors[arg_8] = 1.0 - arg_10.value
                    arg_0.available_hw_qubits.append(arg_8)
            arg_8 += 1
        for arg_12 in arg_0.cx_errors:
            arg_0.gate_cost[arg_12] = arg_0.cx_errors[arg_12] * arg_0.readout_errors[arg_12[0]] *\
                arg_0.readout_errors[arg_12[1]]
        arg_0.swap_paths, arg_15 = nx.algorithms.shortest_paths.dense.\
            floyd_warshall_predecessor_and_distance(arg_0.swap_graph, weight='weight')
        for arg_16 in arg_15:
            arg_0.swap_costs[arg_16] = {}
            for arg_18 in arg_15[arg_16]:
                if (arg_16, arg_18) in arg_0.cx_errors:
                    arg_0.swap_costs[arg_16][arg_18] = arg_0.cx_errors[(arg_16, arg_18)]
                elif (arg_18, arg_16) in arg_0.cx_errors:
                    arg_0.swap_costs[arg_16][arg_18] = arg_0.cx_errors[(arg_18, arg_16)]
                else:
                    arg_19 = 0.0
                    for arg_20 in arg_0.swap_graph.neighbors(arg_18):
                        if (arg_20, arg_18) in arg_0.cx_errors:
                            arg_21 = math.exp(-arg_15[arg_16][arg_20])*arg_0.cx_errors[(arg_20, arg_18)]
                        else:
                            arg_21 = math.exp(-arg_15[arg_16][arg_20])*arg_0.cx_errors[(arg_18, arg_20)]
                        if arg_21 > arg_19:
                            arg_19 = arg_21
                    arg_0.swap_costs[arg_16][arg_18] = arg_19


def Func(arg_0, arg_1):
        """
        Program graph has virtual qubits as nodes.
        Two nodes have an edge if the corresponding virtual qubits
        participate in a 2-qubit gate. The edge is weighted by the
        number of CNOTs between the pair.
        """
        arg_2 = 0
        for arg_3 in arg_1.qubits():
            arg_0.qarg_to_id[arg_3[0].name + arg_6(arg_3[1])] = arg_2
            arg_2 += 1
        for arg_7 in arg_1.twoQ_gates():
            arg_8 = arg_0._qarg_to_id(arg_7.qargs[0])
            arg_9 = arg_0._qarg_to_id(arg_7.qargs[1])
            arg_10 = min(arg_8, arg_9)
            arg_11 = max(arg_8, arg_9)
            arg_12 = 1
            if arg_0.prog_graph.has_edge(arg_10, arg_11):
                arg_12 = arg_0.prog_graph[arg_10][arg_11]['weight'] + 1
            arg_0.prog_graph.add_edge(arg_10, arg_11, weight=arg_12)
        return arg_2


def Func(arg_0, arg_1):
        """
        Select the best remaining hardware qubit for the next program qubit.
        """
        arg_2 = {}
        for arg_3 in arg_0.available_hw_qubits:
            arg_4 = 1
            for arg_5 in arg_0.prog_graph.neighbors(arg_1):
                if arg_5 in arg_0.prog2hw:
                    arg_4 *= arg_0.swap_costs[arg_0.prog2hw[arg_5]][arg_3]
            arg_4 *= arg_0.readout_errors[arg_3]
            arg_2[arg_3] = arg_4
        arg_6 = 0
        arg_7 = None
        for arg_3 in arg_2:
            if arg_2[arg_3] > arg_6:
                arg_6 = arg_2[arg_3]
                arg_7 = arg_3
        return arg_7


def Func(arg_0):
        """Return a list of instructions for this CompositeGate.

        If the CompositeGate itself contains composites, call
        this method recursively.
        """
        Func = []
        for arg_2 in arg_0.data:
            if isinstance(arg_2, CompositeGate):
                Func.extend(arg_2.instruction_list())
            else:
                Func.append(arg_2)
        return Func


def Func(arg_0):
        """Invert this gate."""
        arg_0.data = [gate.Func() for gate in reversed(arg_0.data)]
        arg_0.Func_flag = not arg_0.Func_flag
        return arg_0


def Func(arg_0, *arg_1):
        """Add controls to this gate."""
        arg_0.data = [gate.Func(arg_1) for gate in arg_0.data]
        return arg_0


def Func(arg_0, arg_1, arg_2):
        """Add classical control register."""
        arg_0.data = [gate.Func(arg_1, arg_2) for gate in arg_0.data]
        return arg_0


def Func(arg_0, arg_1=None, arg_2=None):
        """Return True if operator is a unitary matrix."""
        if arg_1 is None:
            arg_1 = arg_0._atol
        if arg_2 is None:
            arg_2 = arg_0._rtol
        return Func_matrix(arg_0._data, arg_2=arg_2, arg_1=arg_1)


def Func(arg_0):
        """Return the Func of the operator."""
        return Operator(
            np.conj(arg_0.data), arg_0.input_dims(), arg_0.output_dims())


def Func(arg_0):
        """Return the Func of the operator."""
        return Operator(
            np.Func(arg_0.data), arg_0.input_dims(), arg_0.output_dims())


def Func(arg_0, arg_1):
        """Return the matrix Func of the operator.

        Args:
            n (int): the Func to raise the matrix to.

        Returns:
            BaseOperator: the n-times composed operator.

        Raises:
            QiskitError: if the input and output dimensions of the operator
            are not equal, or the Func is not a positive integer.
        """
        if not isinstance(arg_1, int):
            raise QiskitError("Can only take integer Funcs of Operator.")
        if arg_0.input_dims() != arg_0.output_dims():
            raise QiskitError("Can only Func with input_dims = output_dims.")
        # Override base class Func so we can implement more efficiently
        # using Numpy.matrix_Func
        return Operator(
            np.linalg.matrix_Func(arg_0.data, arg_1), arg_0.input_dims(),
            arg_0.output_dims())