internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Qiskit/qiskit

Issue:
from_dict() should be able to handle complex numbers
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 
- **Python version**:
- **Operating system**:

### What is the current behavior?

.from_dict() will error out if (actual) complex numbers are present where complex numbers should be present. It's requiring that complex numbers be specified as lists when it should instead allow them to be specified as lists but also allow them to be complex numbers

### Steps to reproduce the problem

See [these](https://github.com/Qiskit/qiskit-aer/pull/504) currently failing unit tests 

```
qiskit.validation.exceptions.ModelValidationError: "{'results': {0: {'data': {'unitary': {0: {0: ['(1+0j) cannot be parsed as a complex number.'] ...
```

### What is the expected behavior?

There's no reason for it to fail - when serializing things we should change complex to lists but '_deserialization' (from_dict) should be able to handle complex numbers (as well as the list format).

### Suggested solutions

Don't throw an error if the thing we're trying to deserialize is already a complex number [here](https://github.com/Qiskit/qiskit-terra/blob/792e1b7f866b9f3685566341fa6b4b54d5ba33e9/qiskit/validation/fields/custom.py#L50)


Discussion:

Resolving patch:
diff --git a/qiskit/validation/fields/custom.py b/qiskit/validation/fields/custom.py
--- a/qiskit/validation/fields/custom.py
+++ b/qiskit/validation/fields/custom.py
@@ -29,7 +29,7 @@ class Complex(ModelTypeValidator):
     """Field for complex numbers.
 
     Field for parsing complex numbers:
-    * deserializes to Python's `complex`.
+    * deserializes from either a Python `complex` or 2-element collection.
     * serializes to a tuple of 2 decimals `(real, imaginary)`
     """
 
@@ -47,13 +47,15 @@ def _serialize(self, value, attr, obj, **_):
             raise self.make_error_serialize('format', input=value)
 
     def _deserialize(self, value, attr, data, **_):
-        if not is_collection(value) or len(value) != 2:
-            raise self.make_error('invalid', input=value)
+        if is_collection(value) and (len(value) == 2):
+            try:
+                return complex(value[0], value[1])
+            except (ValueError, TypeError):
+                raise self.make_error('invalid', input=value)
+        elif isinstance(value, complex):
+            return value
 
-        try:
-            return complex(*value)
-        except (ValueError, TypeError):
-            raise self.make_error('invalid', input=value)
+        raise self.make_error('invalid', input=value)
 
 
 class InstructionParameter(ModelTypeValidator):


Test patch:
Repository: Qiskit/qiskit

Issue:
MPL drawer does not support controlled gates

### Information

- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: MacOS

### What is the current behavior?

The matplotlib drawer does not print controlled gates correctly.

### Steps to reproduce the problem

```
qr = QuantumRegister(3, 'q')
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[1], qr[2]])
circuit.draw('mpl')
```
![image](https://user-images.githubusercontent.com/766693/73392493-f2480800-42a7-11ea-896b-9b934819924d.png)

### What is the expected behavior?

Something along the text drawer:
```
q_0: |0>──■──
          │  
q_1: |0>──■──
        ┌─┴─┐
q_2: |0>┤ H ├
        └───┘
```





Discussion:

Resolving patch:
diff --git a/qiskit/visualization/matplotlib.py b/qiskit/visualization/matplotlib.py
--- a/qiskit/visualization/matplotlib.py
+++ b/qiskit/visualization/matplotlib.py
@@ -34,6 +34,7 @@
 except ImportError:
     HAS_MATPLOTLIB = False
 
+from qiskit.circuit import ControlledGate
 from qiskit.visualization import exceptions
 from qiskit.visualization.qcstyle import DefaultStyle, BWStyle
 from qiskit import user_config
@@ -839,6 +840,24 @@ def _draw_ops(self, verbose=False):
                     # subtext
                     self._custom_multiqubit_gate(q_xy, wide=_iswide,
                                                  text="Unitary")
+                elif isinstance(op.op, ControlledGate) and op.name not in [
+                        'ccx', 'cx', 'cz', 'cu1', 'ccz', 'cu3', 'crz',
+                        'cswap']:
+                    disp = op.op.base_gate.name
+                    num_ctrl_qubits = op.op.num_ctrl_qubits
+                    num_qargs = len(q_xy) - num_ctrl_qubits
+
+                    for i in range(num_ctrl_qubits):
+                        self._ctrl_qubit(q_xy[i], fc=self._style.dispcol['multi'],
+                                         ec=self._style.dispcol['multi'])
+                    # add qubit-qubit wiring
+                    self._line(qreg_b, qreg_t, lc=self._style.dispcol['multi'])
+                    if num_qargs == 1:
+                        self._gate(q_xy[-1], wide=_iswide, text=disp)
+                    else:
+                        self._custom_multiqubit_gate(
+                            q_xy[num_ctrl_qubits:], wide=_iswide, text=disp)
+
                 #
                 # draw single qubit gates
                 #


Test patch:
Repository: Qiskit/qiskit

Issue:
Cannot += the same circuit twice
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.12.0
- **Python version**: 3.7.5
- **Operating system**: macOS Catalina 10.15.2

### What is the current behavior?

The snippet
```
qc = QuantumCircuit(1)
qc2 = qc
qc2 += qc
```
never terminates.
This problem doesn't occur if different circuit instances are added together, only as soon as the same one is added twice the code seems to be stuck.

### Steps to reproduce the problem

Run the above code snippet.

### What is the expected behavior?

The circuit `qc` should be appended twice to `qc2`.

### Suggested solutions

When calling `_append` the circuit data, `rhs.data`, of the added object is appended to self. Since the elements of `rhs.data` are taken via reference and the circuit was added beforehand, not only `self` is extended by the instructions but also `rhs`. 
This can be fixed by changing
```
for instruction_context in rhs.data:  # line 339
```
to
```
for instruction_context in rhs.data.copy():
```

I would self-assign to this issue, but I cannot. I'll open a PR for this.


Discussion:

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -334,8 +334,12 @@ def extend(self, rhs):
             if element not in self.cregs:
                 self.cregs.append(element)
 
+        # Copy the circuit data if rhs and self are the same, otherwise the data of rhs is
+        # appended to both self and rhs resulting in an infinite loop
+        data = rhs.data.copy() if rhs is self else rhs.data
+
         # Add new gates
-        for instruction_context in rhs.data:
+        for instruction_context in data:
             self._append(*instruction_context)
         return self
 


Test patch:
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -25,6 +25,22 @@
 class TestCircuitOperations(QiskitTestCase):
     """QuantumCircuit Operations tests."""
 
+    def test_adding_self(self):
+        """Test that qc += qc finishes, which can be prone to infinite while-loops.
+
+        This can occur e.g. when a user tries
+        >>> other_qc = qc
+        >>> other_qc += qc  # or qc2.extend(qc)
+        """
+        qc = QuantumCircuit(1)
+        qc.x(0)  # must contain at least one operation to end up in a infinite while-loop
+
+        # attempt addition, times out if qc is added via reference
+        qc += qc
+
+        # finally, qc should contain two X gates
+        self.assertEqual(['x', 'x'], [x[0].name for x in qc.data])
+
     def test_combine_circuit_common(self):
         """Test combining two circuits with same registers.
         """
Repository: Qiskit/qiskit

Issue:
Aer CI failing due to error in BaseJob documentation.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**:

### What is the current behavior?

CI test are failing in Aer due sphinx errors in the inherited doc string from `BaseJob` in #3731 

Since doc build warnings aren't treated as fatal in Terra this can lead to problems in other repos (like Aer) which have stricter CI checks on documentation. This will be an issue for any classes that are intended to be subclassed (ie BaseJob, BaseBackend, BaseProvider).

### Steps to reproduce the problem

Run CI on qiskit-aer. Azure doc build fails with:

```
Warning, treated as error:
/home/vsts/work/1/s/.tox/docs/lib/python3.7/site-packages/qiskit/providers/basejob.py:docstring of qiskit.providers.aer.AerJob.wait_for_final_state:7:Unexpected indentation.
ERROR: InvocationError for command /home/vsts/work/1/s/.tox/docs/bin/sphinx-build -W -b html docs/ docs/_build/html -j auto (exited with code 2)
___________________________________ summary ____________________________________
ERROR:   docs: commands failed
```

### What is the expected behavior?

No error.

### Suggested solutions

Fix the doc string that is raising a warning. 




Discussion:

Resolving patch:
diff --git a/qiskit/providers/basejob.py b/qiskit/providers/basejob.py
--- a/qiskit/providers/basejob.py
+++ b/qiskit/providers/basejob.py
@@ -62,11 +62,13 @@ def wait_for_final_state(
             wait: seconds between queries. Default: 5.
             callback: callback function invoked after each query. Default: None.
                 The following positional arguments are provided to the callback function:
-                    * job_id: job ID
-                    * job_status: status of the job from the last query
-                    * job: this BaseJob instance
+
+                * job_id: job ID
+                * job_status: status of the job from the last query
+                * job: this BaseJob instance
+
                 Note: different subclass might provide different arguments to
-                    the callback function.
+                the callback function.
 
         Raises:
             JobTimeoutError: if the job does not reach a final state before the


Test patch:
Repository: Qiskit/qiskit

Issue:
circ.measure_all gives a creg the name "measure" that is a reserved qasm word.
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: latest
- **Python version**:
- **Operating system**:

### What is the current behavior?
`circ.measure_all()` attaches a creg with the name 'measure'.  However this is a reserved keyword in qasm, and causes conflicts

```
QasmError: "Expected an ID, received 'measure'"
```

### Steps to reproduce the problem



### What is the expected behavior?



### Suggested solutions





Discussion:

Resolving patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -1217,7 +1217,7 @@ def measure_all(self, inplace=True):
         else:
             circ = self.copy()
 
-        new_creg = circ._create_creg(len(circ.qubits), 'measure')
+        new_creg = circ._create_creg(len(circ.qubits), 'meas')
         circ.add_register(new_creg)
         circ.barrier()
         circ.measure(circ.qubits, new_creg)


Test patch:
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -240,7 +240,7 @@ def test_measure_all(self):
         store those measured values.
         """
         qr = QuantumRegister(2)
-        cr = ClassicalRegister(2, 'measure')
+        cr = ClassicalRegister(2, 'meas')
 
         circuit = QuantumCircuit(qr)
         circuit.measure_all()
@@ -255,7 +255,7 @@ def test_measure_all_copy(self):
         """Test measure_all with inplace=False
         """
         qr = QuantumRegister(2)
-        cr = ClassicalRegister(2, 'measure')
+        cr = ClassicalRegister(2, 'meas')
 
         circuit = QuantumCircuit(qr)
         new_circuit = circuit.measure_all(inplace=False)
@@ -286,7 +286,7 @@ def test_remove_final_measurements(self):
         Removes all measurements at end of circuit.
         """
         qr = QuantumRegister(2)
-        cr = ClassicalRegister(2, 'measure')
+        cr = ClassicalRegister(2, 'meas')
 
         circuit = QuantumCircuit(qr, cr)
         circuit.measure(qr, cr)
@@ -301,7 +301,7 @@ def test_remove_final_measurements_copy(self):
         Removes all measurements at end of circuit.
         """
         qr = QuantumRegister(2)
-        cr = ClassicalRegister(2, 'measure')
+        cr = ClassicalRegister(2, 'meas')
 
         circuit = QuantumCircuit(qr, cr)
         circuit.measure(qr, cr)
Repository: Qiskit/qiskit

Issue:
Improve an error message in qiskit.converters.circuit_to_gate()
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected enhancement?

Let's assume we have `QuantumCircuit` object called `qc`, and one tries to convert it into a `Gate` object using `qiskit.converters.circuit_to_gate()`. If `qc` contains some instructions which cannot be converted into `Gate`, the following exception is raised
```
QiskitError: 'One or more instructions in this instruction cannot be converted to a gate'
```
My suggestion is to improve this error message and add some info about the particular instruction preventing the convertion from happening. I believe, something like the instruction name in the error message should be more helpfull, than the current general statement.

Below is a code snippet (for a `qc` containing a measurement operation) which can be used to achieve the error mentioned above
```
from qiskit import QuantumCircuit
from qiskit.converters import circuit_to_gate

qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0, 0)

gate = circuit_to_gate(qc)
```


Discussion:
@hay-k and @kdk, I'm new to qiskit and would like to give this a try.
@hay-k. I got a different error from the code snippet above. 'Circuit with classical bits cannot be converted to gate.' This is trapped above the other one and is because there's a cbit. I used qc.barrier() and that caught the error you had. My plan is to just add the name of the first instruction that fails and let the user iteratively fix things if there are multiple such instructions.
Something like 'One or more instructions cannot be converted to a gate. "barrier" is not a gate instruction'
Does this sound like what you're looking for? Thanks.

Resolving patch:
diff --git a/qiskit/converters/circuit_to_gate.py b/qiskit/converters/circuit_to_gate.py
--- a/qiskit/converters/circuit_to_gate.py
+++ b/qiskit/converters/circuit_to_gate.py
@@ -48,8 +48,9 @@ def circuit_to_gate(circuit, parameter_map=None):
 
     for inst, _, _ in circuit.data:
         if not isinstance(inst, Gate):
-            raise QiskitError('One or more instructions in this instruction '
-                              'cannot be converted to a gate')
+            raise QiskitError(('One or more instructions cannot be converted to'
+                               ' a gate. "{}" is not a gate instruction').format(
+                                   inst.name))
 
     if parameter_map is None:
         parameter_dict = {p: p for p in circuit.parameters}


Test patch:
Repository: Qiskit/qiskit

Issue:
Multiple bugs in mct
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: latest
- **Python version**:
- **Operating system**:

### What is the current behavior?
The `mct` gate has several issues:

1) For one or two controls, the function calls `cx` or `ccx` respectively but still requires `q_ancilla` to be set.  This should default to `None`.

2) For more than two controls the inputs are not consistent with the rest of Qiskit nor `cx` or `ccx`.  `cx` and `ccx` allow for int inputs.  However `mct` requires registers or `Qubit` class.  Yet in the two or one control case ints are accepted because they dispatch to functions that handle them.  `mct` should accept int inputs as well.  Note that the `Qubit` class is not even exposed to users.  Passing an int to `q_target` does not tell the user to pass `qreg` or `Qubit` but instead gives the unhelpful error "'MCT needs a single qubit as target."  Also note that in the one or two control case I can pass any value I want with no checking.  E.g. this works just fine

```python
qc = QuantumCircuit(3)
qc.mct([0,1], [2], 1e6)
```



### Steps to reproduce the problem
Try to use the `mct` gate in the same manner as other gates.


### What is the expected behavior?
The gate should behave the same as other gates.


### Suggested solutions





Discussion:
With the recent merge of #4082 two of your points have been addressed, namely `q_ancilla` defaults to none and one can use integers as indices. However there's still no check on the ancilla input, if no ancilla is required (if one is required, checks are implicitly done on appending the gate). I'll open a PR to fix this.

Resolving patch:
diff --git a/qiskit/extensions/standard/x.py b/qiskit/extensions/standard/x.py
--- a/qiskit/extensions/standard/x.py
+++ b/qiskit/extensions/standard/x.py
@@ -1045,6 +1045,10 @@ def mcx(self, control_qubits, target_qubit, ancilla_qubits=None, mode='noancilla
         'basic-dirty-ancilla': MCXVChain(num_ctrl_qubits, dirty_ancillas=True)
     }
 
+    # check ancilla input
+    if ancilla_qubits:
+        _ = self.qbit_argument_conversion(ancilla_qubits)
+
     try:
         gate = available_implementations[mode]
     except KeyError:


Test patch:
Repository: Qiskit/qiskit

Issue:
Simple Latex typo in u3 gate matrix definition
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**:
- **Python version**:
- **Operating system**:

### What is the current behavior?

Under the u3 gate definition, the 2nd row of the matrix is written (line 48 of u3.py):
                e^{i\phi}\sin(\th) & e^{i(\phi+\lambda)\cos(\th)}
Notice the code(\th) is in the exponent.

### Steps to reproduce the problem

The cos(\th) term should be taken out of the exponent.
### What is the expected behavior?

### Suggested solutions

It should be written
                e^{i\phi}\sin(\th) & e^{i(\phi+\lambda)}\cos(\th)




Discussion:

Resolving patch:
diff --git a/qiskit/circuit/library/standard_gates/u2.py b/qiskit/circuit/library/standard_gates/u2.py
--- a/qiskit/circuit/library/standard_gates/u2.py
+++ b/qiskit/circuit/library/standard_gates/u2.py
@@ -42,7 +42,7 @@ class U2Gate(Gate):
 
         U2(\phi, \lambda) = \frac{1}{\sqrt{2}}
             \begin{pmatrix}
-                1          & e^{-i\lambda} \\
+                1          & -e^{i\lambda} \\
                 e^{i\phi} & e^{i(\phi+\lambda)}
             \end{pmatrix}
 
@@ -50,7 +50,7 @@ class U2Gate(Gate):
 
     .. math::
 
-        U2(\pi, 0) = H
+        U2(0, \pi) = H
 
     .. seealso::
 
diff --git a/qiskit/circuit/library/standard_gates/u3.py b/qiskit/circuit/library/standard_gates/u3.py
--- a/qiskit/circuit/library/standard_gates/u3.py
+++ b/qiskit/circuit/library/standard_gates/u3.py
@@ -26,7 +26,8 @@ class U3Gate(Gate):
     Implemented using two X90 pulses on IBM Quantum systems:
 
     .. math::
-        U2(\phi, \lambda) = RZ(\phi+\pi/2) RX(\frac{\pi}{2}) RZ(\lambda-\pi/2)
+        U3(\theta, \phi, \lambda) =
+            RZ(\phi - \pi/2) RX(\pi/2) RZ(\pi - \theta) RX(\pi/2) RZ(\lambda - \pi/2)
 
     **Circuit symbol:**
 
@@ -44,8 +45,8 @@ class U3Gate(Gate):
 
         U3(\theta, \phi, \lambda) =
             \begin{pmatrix}
-                \cos(\th)          & e^{-i\lambda}\sin(\th) \\
-                e^{i\phi}\sin(\th) & e^{i(\phi+\lambda)\cos(\th)}
+                \cos(\th)          & -e^{i\lambda}\sin(\th) \\
+                e^{i\phi}\sin(\th) & e^{i(\phi+\lambda)}\cos(\th)
             \end{pmatrix}
 
     **Examples:**


Test patch:
Repository: Qiskit/qiskit

Issue:
Backends with pulse parameters but pulse=False do not format dt and dtm correctly
Some IBM Q devices have pulse parameters in their config files but `pulse=False`.  This causes `dt` and `dtm` to be formatted differently depending on if pulse is on for that provider.  Namely because the conversion is done here only: https://github.com/Qiskit/qiskit-terra/blob/f38b617748d855e98f682d259b7cf597ef16b2a8/qiskit/providers/models/backendconfiguration.py#L461

and not for the `QasmBackendConfiguration`.  For example, I see `0.22` vs the correct `2.22e-10` on some devices depending on provider.


Discussion:
This is a result of user-facing objects also being a representation of the transport object. @mtreinish v2.0 provider should hopefully help fix this?
Can it just be patched in the meantime?
One other thing is I don't understand why a backend with `open_pulse=False` has dt? Which one is showing this?
Because pulse may be on for other providers that an user is not a part of. 
Then this parameter shouldn't make it to the user? This may be a cloud issue.

Resolving patch:
diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py
--- a/qiskit/providers/models/backendconfiguration.py
+++ b/qiskit/providers/models/backendconfiguration.py
@@ -278,6 +278,25 @@ def __init__(self, backend_name, backend_version, n_qubits,
             self.description = description
         if tags is not None:
             self.tags = tags
+
+        # Add pulse properties here becuase some backends do not
+        # fit within the Qasm / Pulse backend partitioning in Qiskit
+        if 'dt' in kwargs.keys():
+            kwargs['dt'] *= 1e-9
+        if 'dtm' in kwargs.keys():
+            kwargs['dtm'] *= 1e-9
+
+        if 'qubit_lo_range'in kwargs.keys():
+            kwargs['qubit_lo_range'] = [[min_range * 1e9, max_range * 1e9] for
+                                        (min_range, max_range) in kwargs['qubit_lo_range']]
+
+        if 'meas_lo_range' in kwargs.keys():
+            kwargs['meas_lo_range'] = [[min_range * 1e9, max_range * 1e9] for
+                                       (min_range, max_range) in kwargs['meas_lo_range']]
+
+        if 'rep_times' in kwargs.keys():
+            kwargs['rep_times'] = [_rt * 1e-6 for _rt in kwargs['rep_times']]
+
         self.__dict__.update(kwargs)
 
     def __getstate__(self):


Test patch: