internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: jazzband/django-debug-toolbar

Issue:
Appears to be incompatible with sqlparse version 0.2.0.
I get the following exception and stack trace on every page I try to view:

```
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  223.                 response = middleware_method(request, response)
File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/middleware.py" in process_response
  129.                 panel.generate_stats(request, response)
File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/panels/sql/panel.py" in generate_stats
  192.                     query['sql'] = reformat_sql(query['sql'])
File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/panels/sql/utils.py" in reformat_sql
  27.     return swap_fields(''.join(stack.run(sql)))
File "/usr/local/lib/python2.7/dist-packages/sqlparse/engine/filter_stack.py" in run
  29.             stream = filter_.process(stream)

Exception Type: TypeError at /admin/mediasources/document/
Exception Value: process() takes exactly 3 arguments (2 given)

```

I can workaround by forcing the version to 0.1.19 via 
sqlparse==0.1.19
in the requirements file.

sqlparse 0.2.0 was released today



Discussion:
If someone feels like investigating how to update the DDT to work with sqlparse 0.2.0 that would be even better :-)

they changed the api of filters, the stack-parameter does not exist in version 0.2.0, see
https://github.com/django-debug-toolbar/django-debug-toolbar/blob/master/debug_toolbar/panels/sql/utils.py#L12
https://github.com/andialbrecht/sqlparse/commit/5ce225522ba2b2a8af23c7efcbd6261bd9f09528#diff-85ea6f9fed92fa69e276fd208e6d28b4L32

+1. Upgrading my dev site today with DDT enabled made the site suddenly unusable.


Resolving patch:
diff --git a/debug_toolbar/panels/sql/utils.py b/debug_toolbar/panels/sql/utils.py
--- a/debug_toolbar/panels/sql/utils.py
+++ b/debug_toolbar/panels/sql/utils.py
@@ -9,7 +9,7 @@
 
 class BoldKeywordFilter:
     """sqlparse filter to bold SQL keywords"""
-    def process(self, stack, stream):
+    def process(self, stream):
         """Process the token stream"""
         for token_type, value in stream:
             is_keyword = token_type in T.Keyword
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -16,7 +16,7 @@
     packages=find_packages(exclude=('tests.*', 'tests', 'example')),
     install_requires=[
         'Django>=1.8',
-        'sqlparse',
+        'sqlparse>=0.2.0',
     ],
     include_package_data=True,
     zip_safe=False,                 # because we're including static files


Test patch:
Repository: jazzband/django-debug-toolbar

Issue:
Middleware compatibility with Django 1.10
Since Django 1.10 introduced [new middleware style](https://docs.djangoproject.com/en/dev/releases/1.10/#new-style-middleware), existing middlewares should be updated. For now I can suggest possible workaround for impatient Django 1.10 users:

``` python
from django.utils.deprecation import MiddlewareMixin
from debug_toolbar.middleware import DebugToolbarMiddleware


class AtopdedTo110DebugMiddleware(MiddlewareMixin, DebugToolbarMiddleware):
    pass
```

And then add it to your `MIDDLEWARE` settings:

`MIDDLEWARE += ['my.middleware.AtopdedTo110DebugMiddleware']`



Discussion:

Resolving patch:
diff --git a/debug_toolbar/middleware.py b/debug_toolbar/middleware.py
--- a/debug_toolbar/middleware.py
+++ b/debug_toolbar/middleware.py
@@ -10,11 +10,19 @@
 from django.conf import settings
 from django.utils import six
 from django.utils.encoding import force_text
+from django.utils.functional import cached_property
 from django.utils.module_loading import import_string
 
 from debug_toolbar import settings as dt_settings
 from debug_toolbar.toolbar import DebugToolbar
 
+try:
+    from django.utils.deprecation import MiddlewareMixin
+except ImportError:  # Django < 1.10
+    # Works perfectly for everyone using MIDDLEWARE_CLASSES
+    MiddlewareMixin = object
+
+
 _HTML_TYPES = ('text/html', 'application/xhtml+xml')
 
 
@@ -31,21 +39,22 @@ def show_toolbar(request):
     return bool(settings.DEBUG)
 
 
-class DebugToolbarMiddleware(object):
+class DebugToolbarMiddleware(MiddlewareMixin):
     """
     Middleware to set up Debug Toolbar on incoming request and render toolbar
     on outgoing response.
     """
     debug_toolbars = {}
 
-    def __init__(self):
+    @cached_property
+    def show_toolbar(self):
         # If SHOW_TOOLBAR_CALLBACK is a string, which is the recommended
         # setup, resolve it to the corresponding callable.
         func_or_path = dt_settings.get_config()['SHOW_TOOLBAR_CALLBACK']
         if isinstance(func_or_path, six.string_types):
-            self.show_toolbar = import_string(func_or_path)
+            return import_string(func_or_path)
         else:
-            self.show_toolbar = func_or_path
+            return func_or_path
 
     def process_request(self, request):
         # Decide whether the toolbar is active for this request.


Test patch:
diff --git a/tests/settings.py b/tests/settings.py
--- a/tests/settings.py
+++ b/tests/settings.py
@@ -32,6 +32,7 @@
 MIDDLEWARE_CLASSES = [
     'debug_toolbar.middleware.DebugToolbarMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
Repository: jazzband/django-debug-toolbar

Issue:
Incorrectly parse versions of some apps
I saw that for `django-celery-beat` and `django-celery-results` it shows extra dots at the end of the version:
```
django_celery_beat	Django_Celery_Beat	1.0.1..
django_celery_results	Django_Celery_Results	1.0.1..
```

This is because both apps use custom `namedtuple`:
```
version_info_t = namedtuple('version_info_t', (
    'major', 'minor', 'micro', 'releaselevel', 'serial',
))
```

When `releaselevel` and `serial` are not set they are empty strings. This will lead to joining dots in the string representation.

I'm preparing a fix and will create a PR.


Discussion:

Resolving patch:
diff --git a/debug_toolbar/panels/versions.py b/debug_toolbar/panels/versions.py
--- a/debug_toolbar/panels/versions.py
+++ b/debug_toolbar/panels/versions.py
@@ -54,5 +54,7 @@ def get_app_version(self, app):
         else:
             return
         if isinstance(version, (list, tuple)):
-            version = '.'.join(str(o) for o in version)
+            # We strip dots from the right because we do not want to show
+            # trailing dots if there are empty elements in the list/tuple
+            version = '.'.join(str(o) for o in version).rstrip('.')
         return version


Test patch:
diff --git a/tests/panels/test_versions.py b/tests/panels/test_versions.py
new file mode 100644
--- /dev/null
+++ b/tests/panels/test_versions.py
@@ -0,0 +1,40 @@
+# coding: utf-8
+
+from __future__ import absolute_import, unicode_literals
+from collections import namedtuple
+
+from ..base import BaseTestCase
+
+
+version_info_t = namedtuple('version_info_t', (
+    'major', 'minor', 'micro', 'releaselevel', 'serial',
+))
+
+
+class VersionsPanelTestCase(BaseTestCase):
+
+    def setUp(self):
+        super(VersionsPanelTestCase, self).setUp()
+        self.panel = self.toolbar.get_panel_by_id('VersionsPanel')
+
+    def test_app_version_from_get_version_fn(self):
+
+        class FakeApp:
+            def get_version(self):
+                return version_info_t(1, 2, 3, '', '')
+
+        self.assertEqual(self.panel.get_app_version(FakeApp()), '1.2.3')
+
+    def test_app_version_from_VERSION(self):
+
+        class FakeApp:
+            VERSION = version_info_t(1, 2, 3, '', '')
+
+        self.assertEqual(self.panel.get_app_version(FakeApp()), '1.2.3')
+
+    def test_app_version_from_underscode_version(self):
+
+        class FakeApp:
+            __version__ = version_info_t(1, 2, 3, '', '')
+
+        self.assertEqual(self.panel.get_app_version(FakeApp()), '1.2.3')
Repository: jazzband/django-debug-toolbar

Issue:
Missing SQL queries
While recently trying to diagnose a slow admin page, I noticed that certain queries were missing from the SQL panel. By looking at the `django.db.backends` log I can see that the missing queries are exactly those that are using named cursors (`DECLARE ... NO SCROLL CURSOR WITH HOLD FOR SELECT `) instead of regular `SELECT` statements. I believe that these are server-side cursors used with PostgreSQL for code that uses `queryset.iterator()` (such as [`ModelChoiceField`](https://github.com/django/django/blob/a38ae914d89809aed6d79337b74a8b31b6d3849a/django/forms/models.py#L1136)).

So my guess is that DJDT is not recording queries that use these cursors, but I'm not sure.

I'm using DJDT version 1.9.1 and Django 2.0.1.


Discussion:
I'm also seeing this behaviour, big queries that use queryset.iterator() that I'd like to analyze are missing.
I also met this problem.How to fix it?

Resolving patch:
diff --git a/debug_toolbar/panels/sql/tracking.py b/debug_toolbar/panels/sql/tracking.py
--- a/debug_toolbar/panels/sql/tracking.py
+++ b/debug_toolbar/panels/sql/tracking.py
@@ -36,6 +36,7 @@ def recording(self, v):
 def wrap_cursor(connection, panel):
     if not hasattr(connection, "_djdt_cursor"):
         connection._djdt_cursor = connection.cursor
+        connection._djdt_chunked_cursor = connection.chunked_cursor
 
         def cursor(*args, **kwargs):
             # Per the DB API cursor() does not accept any arguments. There's
@@ -48,7 +49,13 @@ def cursor(*args, **kwargs):
                 connection._djdt_cursor(*args, **kwargs), connection, panel
             )
 
+        def chunked_cursor(*args, **kwargs):
+            return state.Wrapper(
+                connection._djdt_chunked_cursor(*args, **kwargs), connection, panel
+            )
+
         connection.cursor = cursor
+        connection.chunked_cursor = chunked_cursor
         return cursor
 
 
@@ -56,6 +63,7 @@ def unwrap_cursor(connection):
     if hasattr(connection, "_djdt_cursor"):
         del connection._djdt_cursor
         del connection.cursor
+        del connection.chunked_cursor
 
 
 class ExceptionCursorWrapper:


Test patch:
diff --git a/tests/panels/test_sql.py b/tests/panels/test_sql.py
--- a/tests/panels/test_sql.py
+++ b/tests/panels/test_sql.py
@@ -36,6 +36,17 @@ def test_recording(self):
         # ensure the stacktrace is populated
         self.assertTrue(len(query[1]["stacktrace"]) > 0)
 
+    @unittest.skipUnless(
+        connection.vendor == "postgresql", "Test valid only on PostgreSQL"
+    )
+    def test_recording_chunked_cursor(self):
+        self.assertEqual(len(self.panel._queries), 0)
+
+        list(User.objects.all().iterator())
+
+        # ensure query was logged
+        self.assertEqual(len(self.panel._queries), 1)
+
     def test_generate_server_timing(self):
         self.assertEqual(len(self.panel._queries), 0)
Repository: jazzband/django-debug-toolbar

Issue:
Empty request with json content type fails with a JSONDecodeError when using the history panel
If an API request is made with an empty body and the content type `application/json`, the history panel raises an error and the whole API request fails.

For instance:

```
GET /api/whatever
Content-Type: application/json

Body: 
```

Result in `500 Internal Server Error`, `JSONDecodeError`, `Expecting value: line 1 column 1 (char 0)`

We could argue that an empty body is not a valid `application/json` body (https://greenbytes.de/tech/webdav/rfc7159.html#values), but in this case, I believe it's not the role of django debug toolbar to raise an error if django accepts this kind of requests.


Discussion:

Resolving patch:
diff --git a/debug_toolbar/panels/history/panel.py b/debug_toolbar/panels/history/panel.py
--- a/debug_toolbar/panels/history/panel.py
+++ b/debug_toolbar/panels/history/panel.py
@@ -48,7 +48,11 @@ def generate_stats(self, request, response):
                 data = request.POST.copy()
             # GraphQL tends to not be populated in POST. If the request seems
             # empty, check if it's a JSON request.
-            if not data and request.META.get("CONTENT_TYPE") == "application/json":
+            if (
+                not data
+                and request.body
+                and request.META.get("CONTENT_TYPE") == "application/json"
+            ):
                 # Python <= 3.5's json.loads expects a string.
                 data = json.loads(
                     request.body


Test patch:
diff --git a/tests/panels/test_history.py b/tests/panels/test_history.py
--- a/tests/panels/test_history.py
+++ b/tests/panels/test_history.py
@@ -28,13 +28,21 @@ def test_post(self):
         self.assertEqual(data["foo"], "bar")
 
     def test_post_json(self):
-        self.request = rf.post(
-            "/", data={"foo": "bar"}, content_type="application/json"
-        )
-        response = self.panel.process_request(self.request)
-        self.panel.generate_stats(self.request, response)
-        data = self.panel.get_stats()["data"]
-        self.assertEqual(data["foo"], "bar")
+        for data, expected_stats_data in (
+            ({"foo": "bar"}, {"foo": "bar"}),
+            ("", {}),
+        ):
+            with self.subTest(data=data):
+                self.request = rf.post(
+                    "/",
+                    data=data,
+                    content_type="application/json",
+                    CONTENT_TYPE="application/json",  # Force django test client to add the content-type even if no data
+                )
+                response = self.panel.process_request(self.request)
+                self.panel.generate_stats(self.request, response)
+                data = self.panel.get_stats()["data"]
+                self.assertDictEqual(data, expected_stats_data)
 
     def test_urls(self):
         self.assertEqual(
Repository: jazzband/django-debug-toolbar

Issue:
Remove calls to request.is_ajax?
Following up on the discussion in #1316. Should calls to `HttpRequest.is_ajax` be replaced or just removed?


Discussion:

Resolving patch:
diff --git a/debug_toolbar/middleware.py b/debug_toolbar/middleware.py
--- a/debug_toolbar/middleware.py
+++ b/debug_toolbar/middleware.py
@@ -69,20 +69,18 @@ def __call__(self, request):
 
         response = self.generate_server_timing_header(response, toolbar.enabled_panels)
 
+        # Always render the toolbar for the history panel, even if it is not
+        # included in the response.
+        rendered = toolbar.render_toolbar()
+
         # Check for responses where the toolbar can't be inserted.
         content_encoding = response.get("Content-Encoding", "")
         content_type = response.get("Content-Type", "").split(";")[0]
-        if any(
-            (
-                getattr(response, "streaming", False),
-                "gzip" in content_encoding,
-                content_type not in _HTML_TYPES,
-                request.is_ajax(),
-            )
+        if (
+            getattr(response, "streaming", False)
+            or "gzip" in content_encoding
+            or content_type not in _HTML_TYPES
         ):
-            # If a AJAX or JSON request, render the toolbar for the history.
-            if request.is_ajax() or content_type == "application/json":
-                toolbar.render_toolbar()
             return response
 
         # Insert the toolbar in the response.
@@ -91,7 +89,7 @@ def __call__(self, request):
         pattern = re.escape(insert_before)
         bits = re.split(pattern, content, flags=re.IGNORECASE)
         if len(bits) > 1:
-            bits[-2] += toolbar.render_toolbar()
+            bits[-2] += rendered
             response.content = insert_before.join(bits)
             if "Content-Length" in response:
                 response["Content-Length"] = len(response.content)


Test patch:
Repository: jazzband/django-debug-toolbar

Issue:
Request with invalid json content type fails with a JSONDecodeError when using the history panel
Similar to https://github.com/jazzband/django-debug-toolbar/issues/1330

If an API request is made with _invalid_ json and the content type application/json, the history panel raises an error and the whole API request fails. django-debug-toolbar 3.1.1.

```
>>> Client(enforce_csrf_checks=True).post(
            "some-valid-url", data="invalid-json", content_type="application/json",
        )
/usr/local/lib/python3.8/site-packages/django/test/client.py:742: in post
    response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
/usr/local/lib/python3.8/site-packages/django/test/client.py:404: in post
    return self.generic('POST', path, post_data, content_type,
/usr/local/lib/python3.8/site-packages/django/test/client.py:470: in generic
    return self.request(**r)
/usr/local/lib/python3.8/site-packages/django/test/client.py:710: in request
    self.check_exception(response)
/usr/local/lib/python3.8/site-packages/django/test/client.py:571: in check_exception
    raise exc_value
/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py:47: in inner
    response = get_response(request)
/usr/local/lib/python3.8/site-packages/debug_toolbar/middleware.py:67: in __call__
    panel.generate_stats(request, response)
/usr/local/lib/python3.8/site-packages/debug_toolbar/panels/history/panel.py:57: in generate_stats
    data = json.loads(
/usr/local/lib/python3.8/json/__init__.py:357: in loads
    return _default_decoder.decode(s)
/usr/local/lib/python3.8/json/decoder.py:337: in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
```


Discussion:

Resolving patch:
diff --git a/debug_toolbar/panels/history/panel.py b/debug_toolbar/panels/history/panel.py
--- a/debug_toolbar/panels/history/panel.py
+++ b/debug_toolbar/panels/history/panel.py
@@ -49,7 +49,10 @@ def generate_stats(self, request, response):
                 and request.body
                 and request.META.get("CONTENT_TYPE") == "application/json"
             ):
-                data = json.loads(request.body)
+                try:
+                    data = json.loads(request.body)
+                except ValueError:
+                    pass
         except RawPostDataException:
             # It is not guaranteed that we may read the request data (again).
             data = None


Test patch:
diff --git a/tests/panels/test_history.py b/tests/panels/test_history.py
--- a/tests/panels/test_history.py
+++ b/tests/panels/test_history.py
@@ -30,7 +30,8 @@ def test_post(self):
     def test_post_json(self):
         for data, expected_stats_data in (
             ({"foo": "bar"}, {"foo": "bar"}),
-            ("", {}),
+            ("", {}),  # Empty JSON
+            ("'", {}),  # Invalid JSON
         ):
             with self.subTest(data=data):
                 self.request = rf.post(
Repository: jazzband/django-debug-toolbar

Issue:
Time panel doesn't re-run timer.js for new requests
The Time panel will load the `timer.js` file and run it on the first time accessing the Time panel. After that, when the user switches to a new request via the History panel, any subsequent usages of the Time panel will result in the "Browser timing" section not being shown due to the `timer.js` module not being re-run after loading the panel.


Discussion:

Resolving patch:
diff --git a/debug_toolbar/panels/__init__.py b/debug_toolbar/panels/__init__.py
--- a/debug_toolbar/panels/__init__.py
+++ b/debug_toolbar/panels/__init__.py
@@ -107,6 +107,10 @@ def content(self):
     def scripts(self):
         """
         Scripts used by the HTML content of the panel when it's displayed.
+
+        When a panel is rendered on the frontend, the ``djdt.panel.render``
+        JavaScript event will be dispatched. The scripts can listen for
+        this event to support dynamic functionality.
         """
         return []
 


Test patch:
Repository: jazzband/django-debug-toolbar

Issue:
Slower than necessary start up (import) times
Hi,
I am digging into slow start up times of a Django app at the moment. I used `` to see which imports are slow and the `debug_toolbar` package is among them. But it would not have to be slow if we could get rid of the `pkg_resources` import.

```
$ PYTHONPROFILEIMPORTTIME=1 python -c "import debug_toolbar" 2>&1 | tail -n2
import time:    117915 |     179477 |   pkg_resources
import time:       624 |     180101 | debug_toolbar
```
So, on my machine the import took ~180ms of which ~179ms can be attributed to `pkg_resources`.

Here is an article that details the problem with `pkg_resources` and put me onto this path :-)
https://dev.to/methane/how-to-speed-up-python-application-startup-time-nkf

I am preparing a PR, more details over there...


Discussion:

Resolving patch:
diff --git a/debug_toolbar/__init__.py b/debug_toolbar/__init__.py
--- a/debug_toolbar/__init__.py
+++ b/debug_toolbar/__init__.py
@@ -1,13 +1,9 @@
 __all__ = ["VERSION"]
 
 
-try:
-    import pkg_resources
-
-    VERSION = pkg_resources.get_distribution("django-debug-toolbar").version
-except Exception:
-    VERSION = "unknown"
-
+# Do not use pkg_resources to find the version but set it here directly!
+# see issue #1446
+VERSION = "3.2"
 
 # Code that discovers files or modules in INSTALLED_APPS imports this module.
 


Test patch:
Repository: jazzband/django-debug-toolbar

Issue:
currentThread was deprecated in Python 3.10 in favour of current_thread
Ref : https://github.com/python/cpython/pull/25174

```
rg -t py -w 'currentThread|notifyAll|activeCount|isDaemon|setDaemon' 
debug_toolbar/utils.py
255:            thread = threading.currentThread()
262:            thread = threading.currentThread()

debug_toolbar/panels/logging.py
81:        self._records[threading.currentThread()] = records

debug_toolbar/panels/staticfiles.py
121:        self._paths[threading.currentThread()] = used_paths
```


Discussion:

Resolving patch:
diff --git a/debug_toolbar/panels/logging.py b/debug_toolbar/panels/logging.py
--- a/debug_toolbar/panels/logging.py
+++ b/debug_toolbar/panels/logging.py
@@ -78,6 +78,6 @@ def process_request(self, request):
 
     def generate_stats(self, request, response):
         records = collector.get_collection()
-        self._records[threading.currentThread()] = records
+        self._records[threading.current_thread()] = records
         collector.clear_collection()
         self.record_stats({"records": records})
diff --git a/debug_toolbar/panels/staticfiles.py b/debug_toolbar/panels/staticfiles.py
--- a/debug_toolbar/panels/staticfiles.py
+++ b/debug_toolbar/panels/staticfiles.py
@@ -118,7 +118,7 @@ def process_request(self, request):
 
     def generate_stats(self, request, response):
         used_paths = collector.get_collection()
-        self._paths[threading.currentThread()] = used_paths
+        self._paths[threading.current_thread()] = used_paths
 
         self.record_stats(
             {
diff --git a/debug_toolbar/utils.py b/debug_toolbar/utils.py
--- a/debug_toolbar/utils.py
+++ b/debug_toolbar/utils.py
@@ -252,14 +252,14 @@ def get_collection(self, thread=None):
         is provided, returns a list for the current thread.
         """
         if thread is None:
-            thread = threading.currentThread()
+            thread = threading.current_thread()
         if thread not in self.collections:
             self.collections[thread] = []
         return self.collections[thread]
 
     def clear_collection(self, thread=None):
         if thread is None:
-            thread = threading.currentThread()
+            thread = threading.current_thread()
         if thread in self.collections:
             del self.collections[thread]
 


Test patch: