internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: agconti/cookiecutter-django-rest

Issue:
Update manage.py with new django 1.10 content. 



Discussion:

Resolving patch:
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
@@ -17,6 +17,7 @@ class Local(Common):
     TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
     NOSE_ARGS = [
         BASE_DIR,
+        '-s',
         '--nologcapture',
         '--with-coverage',
         '--with-progressive',
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/manage.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/manage.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/manage.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/manage.py
@@ -6,6 +6,19 @@
     os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config")
     os.environ.setdefault("DJANGO_CONFIGURATION", "Local")
 
-    from configurations.management import execute_from_command_line
-
+    try:
+        from configurations.management import execute_from_command_line
+    except ImportError:
+        # The above import may fail for some other reason. Ensure that the
+        # issue is really that Django is missing to avoid masking other
+        # exceptions on Python 2.
+        try:
+            import django  # noqa
+        except ImportError:
+            raise ImportError(
+                "Couldn't import Django. Are you sure it's installed and "
+                "available on your PYTHONPATH environment variable? Did you "
+                "forget to activate a virtual environment?"
+            )
+        raise
     execute_from_command_line(sys.argv)


Test patch:
Repository: agconti/cookiecutter-django-rest

Issue:
Add auth password validators



Discussion:

Resolving patch:
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py
@@ -109,6 +109,20 @@ class Common(Configuration):
     for config in TEMPLATES:
         config['OPTIONS']['debug'] = DEBUG
 
+    # Password Validation
+    # https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#module-django.contrib.auth.password_validation
+    AUTH_PASSWORD_VALIDATORS = [
+        {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
+        {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
+        {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
+        {
+            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
+            'OPTIONS': {
+                'min_length': 9,
+            }
+        },
+    ]
+
     # Logging
     LOGGING = {
         'version': 1,
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
@@ -17,6 +17,7 @@ class Local(Common):
     TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
     NOSE_ARGS = [
         BASE_DIR,
+        '-s',
         '--nologcapture',
         '--with-coverage',
         '--with-progressive',


Test patch:
Repository: agconti/cookiecutter-django-rest

Issue:
Update to Django 1.10 logging configuration 
```
'formatters': {
    'django.server': {
        '()': 'django.utils.log.ServerFormatter',
        'format': '[%(server_time)s] %(message)s',
    }
},
'handlers': {
    'django.server': {
        'level': 'INFO',
        'class': 'logging.StreamHandler',
        'formatter': 'django.server',
    },
},
'loggers': {
    'django.server': {
        'handlers': ['django.server'],
        'level': 'INFO',
        'propagate': False,
    }
}
```



Discussion:

Resolving patch:
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/common.py
@@ -114,6 +114,10 @@ class Common(Configuration):
         'version': 1,
         'disable_existing_loggers': False,
         'formatters': {
+            'django.server': {
+                '()': 'django.utils.log.ServerFormatter',
+                'format': '[%(server_time)s] %(message)s',
+            },
             'verbose': {
                 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
             },
@@ -131,6 +135,11 @@ class Common(Configuration):
             },
         },
         'handlers': {
+            'django.server': {
+                'level': 'INFO',
+                'class': 'logging.StreamHandler',
+                'formatter': 'django.server',
+            },
             'console': {
                 'level': 'INFO',
                 'filters': ['require_debug_true'],
@@ -153,6 +162,11 @@ class Common(Configuration):
                 'handlers': ['console'],
                 'propagate': True,
             },
+            'django.server': {
+                'handlers': ['django.server'],
+                'level': 'INFO',
+                'propagate': False,
+            },
             'django.request': {
                 'handlers': ['mail_admins'],
                 'level': 'ERROR',
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/local.py
@@ -17,6 +17,7 @@ class Local(Common):
     TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
     NOSE_ARGS = [
         BASE_DIR,
+        '-s',
         '--nologcapture',
         '--with-coverage',
         '--with-progressive',


Test patch:
Repository: agconti/cookiecutter-django-rest

Issue:
Remove django-secure
As stated on http://django-secure.readthedocs.io/en/latest/

> This project was merged into Django 1.8. It does not provide any additional checks beyond those included in Django 1.8+, so there is no reason to use it with Django 1.8+. Since Django 1.8 is now the lowest supported Django version, this project is now unsupported and un-maintained.



Discussion:
Hi @spoetnik,

Thanks for opening an issue. This makes sense -- I'll remove `django-secure`. Adding this to the current release schedule. 

Resolving patch:
diff --git a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/production.py b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/production.py
--- a/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/production.py
+++ b/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/config/production.py
@@ -20,10 +20,6 @@ class Production(Common):
     INSTALLED_APPS = Common.INSTALLED_APPS
     SECRET_KEY = values.SecretValue()
 
-    # django-secure
-    # http://django-secure.readthedocs.org/en/v0.1.2/settings.html
-    INSTALLED_APPS += ("djangosecure", )
-
     SECURE_HSTS_SECONDS = 60
     SECURE_HSTS_INCLUDE_SUBDOMAINS = values.BooleanValue(True)
     SECURE_FRAME_DENY = values.BooleanValue(True)


Test patch:
Repository: quantumlib/Cirq

Issue:
Should Circuit#append be chainable?
It seems like a common pattern to want to do
circuit = Circuit().append(o1).append([o2, o3])
?


Discussion:
err well
circuit = Circuit().append(op tree)
(easy to combine first and second for op trees)
Making it chainable makes sense to me, but I find chainable APIs in python to be somewhat non-idiomatic because you have to use explicit line-continuation or an ugly brace style if your chain goes longer than a single line.
I think the "give any iterable and its fine" is sufficient to cover this use case, and I agree with Matthew that chaining is kind of ugly in python.

I vote close.
I agree about chainable in python ugh.

Maybe a static method
circuit = Circuit.from_op_tree(...)?

+1 for static method. Factory functions like that are very useful.
I would call it from_operations. OP_TREE is a concept we want to avoid explaining if possible, and instead say "look it just works!".

Resolving patch:
diff --git a/cirq/circuits/circuit.py b/cirq/circuits/circuit.py
--- a/cirq/circuits/circuit.py
+++ b/cirq/circuits/circuit.py
@@ -14,8 +14,6 @@
 
 """The circuit data structure for the sequenced phase."""
 
-import itertools
-
 from typing import Iterable, List, Optional, Set
 
 from cirq import ops
@@ -35,6 +33,23 @@ def __init__(self, moments: Iterable[Moment] = ()):
         """
         self.moments = list(moments)
 
+    @staticmethod
+    def from_ops(*operations: ops.OP_TREE,
+                 strategy: InsertStrategy = InsertStrategy.NEW_THEN_INLINE
+                 ) -> 'Circuit':
+        """Creates an empty circuit and appends the given operations.
+
+        Args:
+            operations: The operations to append to the new circuit.
+            strategy: How to append the operations.
+
+        Returns:
+            The constructed circuit containing the operations.
+        """
+        result = Circuit()
+        result.append(operations, strategy)
+        return result
+
     def __eq__(self, other):
         if not isinstance(other, type(self)):
             return NotImplemented


Test patch:
diff --git a/cirq/circuits/circuit_test.py b/cirq/circuits/circuit_test.py
--- a/cirq/circuits/circuit_test.py
+++ b/cirq/circuits/circuit_test.py
@@ -458,3 +458,24 @@ def test_qubits():
         Moment([ops.X(a)])
     ])
     assert c.qubits() == {a, b}
+
+
+def test_from_ops():
+    a = ops.QubitId()
+    b = ops.QubitId()
+
+    actual = Circuit.from_ops(
+        ops.X(a),
+        [ops.Y(a), ops.Z(b)],
+        ops.CZ(a, b),
+        ops.X(a),
+        [ops.Z(b), ops.Y(a)],
+    )
+
+    assert actual == Circuit([
+        Moment([ops.X(a)]),
+        Moment([ops.Y(a), ops.Z(b)]),
+        Moment([ops.CZ(a, b)]),
+        Moment([ops.X(a), ops.Z(b)]),
+        Moment([ops.Y(a)]),
+    ])
Repository: quantumlib/Cirq

Issue:
mem_manager_test hang observed
I just had a run of pytest hang indefinitely within `mem_manager_test.py`. I ctrl+C'd the test away and the tests continued fine otherwise:

```cirq/google/sim/mem_manager_test.py ....^C...```

When I reran the tests, the hang did not occur.

Looks like we might have some sort of concurrency-based flake?



Discussion:

Resolving patch:
diff --git a/cirq/google/sim/mem_manager.py b/cirq/google/sim/mem_manager.py
--- a/cirq/google/sim/mem_manager.py
+++ b/cirq/google/sim/mem_manager.py
@@ -67,7 +67,6 @@ def _create_array(self, arr: np.ndarray) -> int:
                 'Array has unsupported dtype {}.'.format(arr.dtype))
 
         with self._lock:
-
             if self._count >= len(self._arrays):
                 self._arrays += len(self._arrays) * [None]
 
@@ -82,10 +81,11 @@ def _create_array(self, arr: np.ndarray) -> int:
         return self._current
 
     def _get_next_free(self):
-        previous_current = self._current
+        loop_count = 0
         while self._arrays[self._current] is not None:
             self._current = (self._current + 1) % len(self._arrays)
-            if previous_current == self._current:
+            loop_count += 1
+            if loop_count == len(self._arrays):
                 raise RuntimeError(
                     'Cannot find free space to allocate new array.')
 


Test patch:
Repository: quantumlib/Cirq

Issue:
Don't use Symbol() when name is alphanumeric
I think it will be pretty common to have symbol names like a0, a1, a2, ...  Having them show up as Symbol('a0') in a circuit seems pretty inconvenient.


Discussion:
This is with respect to Symbol's `__str__` being cautious about ambiguity when there are strange characters? Rewriting it to allow digits, as long as it's not *just* digits, seems reasonable. Should we allow leading digits?
Is it possible to have similar rules as for naming variables?
@Ashalynd Yes, that is reasonable. If we can just duplicate python's rules, that would be easy to explain to people.

Resolving patch:
diff --git a/cirq/value/symbol.py b/cirq/value/symbol.py
--- a/cirq/value/symbol.py
+++ b/cirq/value/symbol.py
@@ -12,6 +12,16 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import json
+import re
+
+_identifier_pattern = '[a-zA-Z_][a-zA-Z0-9_]*$'
+
+def _is_valid_identifier(text):
+    return re.match(_identifier_pattern, text)
+
+def _encode(text):
+    return json.JSONEncoder().encode(text)
 
 class Symbol:
     """A constant plus the runtime value of a parameter with a given key.
@@ -31,8 +41,8 @@ def __init__(self, name: str) -> None:
 
     def __str__(self):
         return (self.name
-                if self.name.isalpha()
-                else 'Symbol({!r})'.format(self.name))
+                if _is_valid_identifier(self.name)
+                else 'Symbol({})'.format(_encode(self.name)))
 
     def __repr__(self):
         return 'Symbol({!r})'.format(self.name)


Test patch:
diff --git a/cirq/circuits/circuit_test.py b/cirq/circuits/circuit_test.py
--- a/cirq/circuits/circuit_test.py
+++ b/cirq/circuits/circuit_test.py
@@ -711,11 +711,7 @@ def text_diagram_exponent(self):
         PGate(Symbol('a')).on(q),
         PGate(Symbol('%$&#*(')).on(q),
     )
-    assert str(c).strip() in [
-        "cube: ───P───P^2───P^a───P^Symbol('%$&#*(')───",
-
-        "cube: ───P───P^2───P^a───P^Symbol(u'%$&#*(')───",
-    ]
+    assert str(c).strip() == 'cube: ───P───P^2───P^a───P^Symbol("%$&#*(")───'
 
 
 def test_to_text_diagram_custom_order():
diff --git a/cirq/value/symbol_test.py b/cirq/value/symbol_test.py
--- a/cirq/value/symbol_test.py
+++ b/cirq/value/symbol_test.py
@@ -20,6 +20,12 @@ def test_parameterized_value_init():
     assert Symbol('a').name == 'a'
     assert Symbol('b').name == 'b'
 
+def test_string_representation():
+    assert str(Symbol('a1')) == 'a1'
+    assert str(Symbol('_b23_')) == '_b23_'
+    assert str(Symbol('1a')) == 'Symbol("1a")'
+    assert str(Symbol('&%#')) == 'Symbol("&%#")'
+    assert str(Symbol('')) == 'Symbol("")'
 
 def test_parameterized_value_eq():
     eq = EqualsTester()
Repository: quantumlib/Cirq

Issue:
Engine measurements are bytes but simulator measurements are bools
This causes code that works with the simulator to fail when given engine results. We should make these consistent.

Example code that works with simulator results but not engine results:

```python
a = np.zeros([repetition_count], dtype=np.bool)
a ^= results.measurements['x'][:, 0]
a ^= results.measurements['y'][:, 0]
```


Discussion:

Resolving patch:
diff --git a/cirq/google/programs.py b/cirq/google/programs.py
--- a/cirq/google/programs.py
+++ b/cirq/google/programs.py
@@ -131,7 +131,7 @@ def unpack_results(
     total_bits = repetitions * bits_per_rep
 
     byte_arr = np.frombuffer(data, dtype='uint8').reshape((len(data), 1))
-    bits = np.unpackbits(byte_arr, axis=1)[:, ::-1].reshape(-1)
+    bits = np.unpackbits(byte_arr, axis=1)[:, ::-1].reshape(-1).astype(bool)
     bits = bits[:total_bits].reshape((repetitions, bits_per_rep))
 
     results = {}


Test patch:
diff --git a/cirq/google/programs_test.py b/cirq/google/programs_test.py
--- a/cirq/google/programs_test.py
+++ b/cirq/google/programs_test.py
@@ -131,6 +131,7 @@ def test_unpack_results():
     results = programs.unpack_results(data, 7, [('a', 3), ('b', 2)])
     assert 'a' in results
     assert results['a'].shape == (7, 3)
+    assert results['a'].dtype == bool
     np.testing.assert_array_equal(
         results['a'],
         [[0, 0, 0],
@@ -143,6 +144,7 @@ def test_unpack_results():
 
     assert 'b' in results
     assert results['b'].shape == (7, 2)
+    assert results['b'].dtype == bool
     np.testing.assert_array_equal(
         results['b'],
         [[0, 0],
diff --git a/cirq/google/sim/xmon_simulator_test.py b/cirq/google/sim/xmon_simulator_test.py
--- a/cirq/google/sim/xmon_simulator_test.py
+++ b/cirq/google/sim/xmon_simulator_test.py
@@ -129,6 +129,8 @@ def test_run(scheduler):
 
     simulator = xmon_simulator.XmonSimulator()
     result = run(simulator, circuit, scheduler)
+    assert result.measurements['a'].dtype == bool
+    assert result.measurements['b'].dtype == bool
     np.testing.assert_equal(result.measurements,
                             {'a': [[True]], 'b': [[False]]})
Repository: quantumlib/Cirq

Issue:
Add __repr__ to XmonDevice
See e.g. `TrialResult` or `Circuit` for how these should work.

```python
    def __repr__(self):
        return ('TrialResult(params={!r}, '
                'repetitions={!r}, '
                'measurements={!r})').format(self.params,
                                             self.repetitions,
                                             self.measurements)
```


Discussion:

Resolving patch:
diff --git a/cirq/google/xmon_device.py b/cirq/google/xmon_device.py
--- a/cirq/google/xmon_device.py
+++ b/cirq/google/xmon_device.py
@@ -195,6 +195,15 @@ def col(self, col: int) -> List[GridQubit]:
         """Returns the qubits in the given column, in ascending order."""
         return sorted(q for q in self.qubits if q.col == col)
 
+    def __repr__(self):
+        return ('XmonDevice(measurement_duration={!r}, '
+                'exp_w_duration={!r}, '
+                'exp_11_duration={!r} '
+                'qubits={!r})').format(self._measurement_duration,
+                                       self._exp_w_duration,
+                                       self._exp_z_duration,
+                                       sorted(self.qubits))
+
     def __str__(self):
         diagram = TextDiagramDrawer()
 


Test patch:
diff --git a/cirq/google/xmon_device_test.py b/cirq/google/xmon_device_test.py
--- a/cirq/google/xmon_device_test.py
+++ b/cirq/google/xmon_device_test.py
@@ -55,6 +55,18 @@ def test_init():
         _ = d.duration_of(cirq.Gate().on(q00))
 
 
+@cirq.testing.only_test_in_python3
+def test_repr():
+    d = square_device(2, 2, holes=[])
+
+    assert repr(d) == ("XmonDevice(measurement_duration=Duration(picos=1000), "
+                       "exp_w_duration=Duration(picos=2000), "
+                       "exp_11_duration=Duration(picos=3000) "
+                       "qubits=[cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), "
+                       "cirq.GridQubit(1, 0), "
+                       "cirq.GridQubit(1, 1)])")
+
+
 def test_can_add_operation_into_moment():
     d = square_device(2, 2)
     q00 = cirq.GridQubit(0, 0)
@@ -126,7 +138,8 @@ class MyGate(cirq.Gate):
     d.validate_operation(cirq.GateOperation(cg.ExpZGate(),
                                             [cirq.GridQubit(0, 0)]))
     with pytest.raises(ValueError):
-        d.validate_operation(cirq.GateOperation(MyGate, [cirq.GridQubit(0, 0)]))
+        d.validate_operation(cirq.GateOperation(
+            MyGate, [cirq.GridQubit(0, 0)]))
     with pytest.raises(ValueError):
         d.validate_operation(NotImplementedOperation())
 
@@ -204,7 +217,7 @@ def test_xmon_device_eq():
     eq = cirq.testing.EqualsTester()
     eq.make_equality_group(lambda: square_device(3, 3))
     eq.make_equality_group(
-        lambda: square_device(3, 3,holes=[cirq.GridQubit(1, 1)]))
+        lambda: square_device(3, 3, holes=[cirq.GridQubit(1, 1)]))
     eq.make_equality_group(
         lambda: cg.XmonDevice(cirq.Duration(nanos=1), cirq.Duration(nanos=2),
                               cirq.Duration(nanos=3), []))
Repository: quantumlib/Cirq

Issue:
`Circuit.with_parameters_resolved_by` doesn't preserve layout of circuit
Instead of appending the operations in, which can result in the operations moving around, the method needs to directly construct the moments of the new circuit.


Discussion:
Look into SupportsParameterization now that the magic method protocol is in place
Is there a known example where it happened?

Resolving patch:
diff --git a/cirq/circuits/circuit.py b/cirq/circuits/circuit.py
--- a/cirq/circuits/circuit.py
+++ b/cirq/circuits/circuit.py
@@ -1352,11 +1352,14 @@ def _is_parameterized_(self) -> bool:
 
     def _resolve_parameters_(self,
                              param_resolver: study.ParamResolver) -> 'Circuit':
-        resolved_circuit = Circuit()
+        resolved_moments = []
         for moment in self:
-            resolved_circuit.append(_resolve_operations(
+            resolved_operations = _resolve_operations(
                 moment.operations,
-                param_resolver))
+                param_resolver)
+            new_moment = Moment(resolved_operations)
+            resolved_moments.append(new_moment)
+        resolved_circuit = Circuit(resolved_moments)
         return resolved_circuit
 
     def _qasm_(self) -> str:


Test patch:
diff --git a/cirq/circuits/circuit_test.py b/cirq/circuits/circuit_test.py
--- a/cirq/circuits/circuit_test.py
+++ b/cirq/circuits/circuit_test.py
@@ -1660,7 +1660,7 @@ def test_is_parameterized():
     assert not cirq.is_parameterized(circuit)
 
 
-def test_with_parameters_resolved_by():
+def test_resolve_parameters():
     a, b = cirq.LineQubit.range(2)
     circuit = cirq.Circuit.from_ops(
         cirq.CZ(a, b)**cirq.Symbol('u'),
@@ -1675,6 +1675,23 @@ def test_with_parameters_resolved_by():
       │
 1: ───@^0.1───Y^0.2───
 """)
+    q = cirq.NamedQubit('q')
+    # no-op parameter resolution
+    circuit = cirq.Circuit([
+        cirq.Moment(), cirq.Moment([cirq.X(q)])])
+    resolved_circuit = cirq.resolve_parameters(
+        circuit,
+        cirq.ParamResolver({}))
+    cirq.testing.assert_same_circuits(circuit, resolved_circuit)
+    # actually resolve something
+    circuit = cirq.Circuit([
+        cirq.Moment(), cirq.Moment([cirq.X(q)**cirq.Symbol('x')])])
+    resolved_circuit = cirq.resolve_parameters(
+        circuit,
+        cirq.ParamResolver({'x': 0.2}))
+    expected_circuit = cirq.Circuit([
+        cirq.Moment(), cirq.Moment([cirq.X(q)**0.2])])
+    cirq.testing.assert_same_circuits(expected_circuit, resolved_circuit)
 
 
 def test_items():