internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: kovidgoyal/kitty

Issue:
Missing `f` prefix on f-strings
Some strings looks like they're meant to be f-strings but are missing the `f` prefix meaning variable interpolation won't happen.

https://github.com/kovidgoyal/kitty/blob/714461de76cd557451c6428a70a51e42cc3e7228/kitty/file_transmission.py#L979
https://github.com/kovidgoyal/kitty/blob/714461de76cd557451c6428a70a51e42cc3e7228/kitty/window.py#L835

I found this issue automatically. I'm a bot. Beep Boop 🦊. See other issues I found in your repo [here](https://codereview.doctor/kovidgoyal/kitty)


Discussion:

Resolving patch:
diff --git a/kitty/file_transmission.py b/kitty/file_transmission.py
--- a/kitty/file_transmission.py
+++ b/kitty/file_transmission.py
@@ -976,7 +976,7 @@ def handle_receive_cmd(self, cmd: FileTransmissionCommand) -> None:
             finally:
                 self.drop_receive(ar.id)
         else:
-            log_error('Transmission receive command with unknown action: {cmd.action}, ignoring')
+            log_error(f'Transmission receive command with unknown action: {cmd.action}, ignoring')
 
     def transmit_rsync_signature(
         self, fs: Iterator[memoryview],
diff --git a/kitty/window.py b/kitty/window.py
--- a/kitty/window.py
+++ b/kitty/window.py
@@ -832,7 +832,7 @@ def handle_remote_file(self, netloc: str, remote_path: str) -> None:
         args = self.child.foreground_cmdline
         conn_data = get_connection_data(args, self.child.foreground_cwd or self.child.current_cwd or '')
         if conn_data is None:
-            get_boss().show_error('Could not handle remote file', 'No SSH connection data found in: {args}')
+            get_boss().show_error('Could not handle remote file', f'No SSH connection data found in: {args}')
             return
         get_boss().run_kitten(
             'remote_file', '--hostname', netloc.partition(':')[0], '--path', remote_path,


Test patch:
Repository: django-extensions/django-extensions

Issue:
find_template management command does not work
I believe this is caused by a django issue:

https://code.djangoproject.com/ticket/17199

Django versions tested: 1.3, 1.4



Discussion:

Resolving patch:
diff --git a/django_extensions/management/commands/find_template.py b/django_extensions/management/commands/find_template.py
--- a/django_extensions/management/commands/find_template.py
+++ b/django_extensions/management/commands/find_template.py
@@ -1,13 +1,22 @@
 from django.core.management.base import LabelCommand
-from django.template.loader import find_template
+from django.template import loader
 from django.template import TemplateDoesNotExist
 import sys
 
 
 def get_template_path(path):
     try:
-        template = find_template(path)
-        return template[1].name
+        template = loader.find_template(path)
+        if template[1]:
+            return template[1].name
+        # work arround https://code.djangoproject.com/ticket/17199 issue
+        for template_loader in loader.template_source_loaders:
+            try:
+                source, origin = template_loader.load_template_source(path)
+                return origin
+            except TemplateDoesNotExist:
+                pass
+        raise TemplateDoesNotExist(path)
     except TemplateDoesNotExist:
         return None
 


Test patch:
Repository: django-extensions/django-extensions

Issue:
EncryptedCharField returns empty string
This one has been a real pain to track down, and now that I have, I'm not sure how to fix it.  

Using django 1.3.1, pycrypto==2.6, keyczar==0.71b and django-extensions from master.

EncryptedCharField seems to work, except that it never successfully decrypts the data.  In fact, it _is_ decrypting the data, but it is getting munged in Keyczar.

Eg:

from keyczar import keyczar
crypt = keyczar.Crypter.Read('~/keyczar')
cyphertext = crypt.Encrypt('Testing')
crypt.Decrypt(cyphertext)
Out[22]: 'Testing'

Now, with Unicode:
ciphertext = crypt.Encrypt(u'Testing')
crypt.Decrypt(ciphertext)
Out[25]: ''

In the second example, you see that we're getting back an empty string.  I tracked this down to the Keyczar module.  For reasons I'm not yet able to explain, the AES decrypter returns a byte string that looks like this:
'T\u0000e\u0000s\u0000t\u0000i\u0000n\u0000g\u0000\u0000\u0000\u0000\u0000\u0000'

Then, the _UnPad function lops off all the characters, because it's PKCS5 code has been lost.

My first thought was to just smash all unicode strings into plain byte strings before encrypting / decrypting them, but I suspect that there's a better way to fix this?



Discussion:

Resolving patch:
diff --git a/django_extensions/db/fields/encrypted.py b/django_extensions/db/fields/encrypted.py
--- a/django_extensions/db/fields/encrypted.py
+++ b/django_extensions/db/fields/encrypted.py
@@ -25,6 +25,8 @@ def __init__(self, *args, **kwargs):
         if max_length:
             max_length = len(self.prefix) + \
                 len(self.crypt.Encrypt('x'*max_length))
+            # TODO: Re-examine if this logic will actually make a large-enough
+            # max-length for unicode strings that have non-ascii characters in them.
             kwargs['max_length'] = max_length
 
         super(BaseEncryptedField, self).__init__(*args, **kwargs)
@@ -32,13 +34,18 @@ def __init__(self, *args, **kwargs):
     def to_python(self, value):
         if value and (value.startswith(self.prefix)):
             retval = self.crypt.Decrypt(value[len(self.prefix):])
+            if retval:
+                retval = retval.decode('utf-8')
         else:
             retval = value
         return retval
 
     def get_db_prep_value(self, value, connection, prepared=False):
         if value and not value.startswith(self.prefix):
-
+            # We need to encode a unicode string into a byte string, first.
+            # keyczar expects a bytestring, not a unicode string.
+            if type(value) == unicode:
+                value = value.encode('utf-8')
             # Truncated encrypted content is unreadable,
             # so truncate before encryption
             max_length = self.unencrypted_length


Test patch:
Repository: django-extensions/django-extensions

Issue:
JSONField default= doesn't accept a dict
Dicts can be assigned to JSONFields in model instances, but default values must currently be specified as JSON strings in model definitions.

In other words, instead of this:

```
myfield = JSONField(default=simplejson.dumps(mydict))
```

if would be nice to just say:

```
myfield = JSONField(default=mydict)
```



Discussion:
Great issue!


Resolving patch:
diff --git a/django_extensions/db/fields/json.py b/django_extensions/db/fields/json.py
--- a/django_extensions/db/fields/json.py
+++ b/django_extensions/db/fields/json.py
@@ -69,7 +69,7 @@ def __init__(self, *args, **kwargs):
         if not default:
             kwargs['default'] = '{}'
         elif isinstance(default, (list, dict)):
-            kwargs['default'] = dump(value)
+            kwargs['default'] = dumps(default)
         models.TextField.__init__(self, *args, **kwargs)
 
     def to_python(self, value):


Test patch:
Repository: django-extensions/django-extensions

Issue:
AutoSlugField bug
There is error in case of model inheritance. For example:

```
class A(models.Model):
   slug = AutoSlugField(populate_from='title', max_length=100, unique = True)
   title = models.CharField(max_length=100)

class B(A):
   pass

A(title = 'Foo').save()
B(title = 'Foo').save()    # this will generate IntegriryError
```

There is a patch. Possibly, it has problems in case of unique_together fields using.

```
# determines base model class with respect to inheritance
queryset = model_instance.__class__._default_manager.all()
for field, model in model_instance._meta.get_fields_with_model():
   if model and field == slug_field:
       queryset = model._default_manager.all()
       break
```



Discussion:

Resolving patch:
diff --git a/django_extensions/db/fields/__init__.py b/django_extensions/db/fields/__init__.py
--- a/django_extensions/db/fields/__init__.py
+++ b/django_extensions/db/fields/__init__.py
@@ -67,6 +67,12 @@ def _slug_strip(self, value):
         value = re.sub('%s+' % re_sep, self.separator, value)
         return re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
 
+    def get_queryset(self, model_cls, slug_field):
+        for field, model in model_cls._meta.get_fields_with_model():
+            if model and field == slug_field:
+                return model._default_manager.all()
+        return model_cls._default_manager.all()
+
     def slugify_func(self, content):
         if content:
             return slugify(content)
@@ -103,7 +109,7 @@ def create_slug(self, model_instance, add):
 
         # exclude the current model instance from the queryset used in finding
         # the next valid slug
-        queryset = model_instance.__class__._default_manager.all()
+        queryset = self.get_queryset(model_instance.__class__, slug_field)
         if model_instance.pk:
             queryset = queryset.exclude(pk=model_instance.pk)
 


Test patch:
diff --git a/django_extensions/tests/fields.py b/django_extensions/tests/fields.py
--- a/django_extensions/tests/fields.py
+++ b/django_extensions/tests/fields.py
@@ -12,6 +12,10 @@ class SluggedTestModel(models.Model):
     slug = AutoSlugField(populate_from='title')
 
 
+class ChildSluggedTestModel(SluggedTestModel):
+    pass
+
+
 class AutoSlugFieldTest(unittest.TestCase):
     def setUp(self):
         self.old_installed_apps = settings.INSTALLED_APPS
@@ -87,3 +91,15 @@ def testEmptySlugSource(self):
 
         n.save()
         self.assertEqual(n.slug, '-3')
+
+    def testInheritanceCreatesNextSlug(self):
+        m = SluggedTestModel(title='foo')
+        m.save()
+
+        n = ChildSluggedTestModel(title='foo')
+        n.save()
+        self.assertEqual(n.slug, 'foo-2')
+
+        o = SluggedTestModel(title='foo')
+        o.save()
+        self.assertEqual(o.slug, 'foo-3')
Repository: django-extensions/django-extensions

Issue:
Auto populating UUID field to existing object throws exception
Reproduction Steps:
1. Create model without UUID field
2. Create instance of that model
3. Add automatic UUID field and sync DB
4. Modify existing instance

Error:
TypeError: coercing to Unicode: need string or buffer, UUID found



Discussion:

Resolving patch:
diff --git a/django_extensions/db/fields/__init__.py b/django_extensions/db/fields/__init__.py
--- a/django_extensions/db/fields/__init__.py
+++ b/django_extensions/db/fields/__init__.py
@@ -268,7 +268,7 @@ def pre_save(self, model_instance, add):
             return value
         else:
             if self.auto and not value:
-                value = six.u(self.create_uuid())
+                value = force_unicode(self.create_uuid())
                 setattr(model_instance, self.attname, value)
         return value
 


Test patch:
Repository: django-extensions/django-extensions

Issue:
JSONEncoder cannot encode dates
Bundled `JSONEncoder` cannot handle `datetime.date` data, as it explicitly supports `datetime.datetime` only.
Using `django.core.serializers.json.DjangoJSONEncoder` will solve this



Discussion:

Resolving patch:
diff --git a/django_extensions/db/fields/json.py b/django_extensions/db/fields/json.py
--- a/django_extensions/db/fields/json.py
+++ b/django_extensions/db/fields/json.py
@@ -11,29 +11,25 @@ class LOL(models.Model):
 """
 
 import six
-import datetime
 from decimal import Decimal
 from django.db import models
 from django.conf import settings
-from django.utils import simplejson
+from django.core.serializers.json import DjangoJSONEncoder
 
-
-class JSONEncoder(simplejson.JSONEncoder):
-    def default(self, obj):
-        if isinstance(obj, Decimal):
-            return str(obj)
-        elif isinstance(obj, datetime.datetime):
-            assert settings.TIME_ZONE == 'UTC'
-            return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
-        return simplejson.JSONEncoder.default(self, obj)
+try:
+    # Django <= 1.6 backwards compatibility
+    from django.utils import simplejson as json
+except ImportError:
+    # Django >= 1.7
+    import json
 
 
 def dumps(value):
-    return JSONEncoder().encode(value)
+    return DjangoJSONEncoder().encode(value)
 
 
 def loads(txt):
-    value = simplejson.loads(
+    value = json.loads(
         txt,
         parse_float=Decimal,
         encoding=settings.DEFAULT_CHARSET


Test patch:
Repository: django-extensions/django-extensions

Issue:
JSONField does not accept an empty list as default
[Here](https://github.com/django-extensions/django-extensions/blob/8cbec9ca3174ba9c4af28ff4c0740ffd24375bb3/django_extensions/db/fields/json.py#L67) default is tested if it's "truthy". `[]` happens to be "falsy" and it ends up using `'{}'` as default. So it is impossible to set `[]` as default.



Discussion:

Resolving patch:
diff --git a/django_extensions/db/fields/json.py b/django_extensions/db/fields/json.py
--- a/django_extensions/db/fields/json.py
+++ b/django_extensions/db/fields/json.py
@@ -63,8 +63,8 @@ class JSONField(six.with_metaclass(models.SubfieldBase, models.TextField)):
     JSON objects seamlessly.  Main thingy must be a dict object."""
 
     def __init__(self, *args, **kwargs):
-        default = kwargs.get('default')
-        if not default:
+        default = kwargs.get('default', None)
+        if default is None:
             kwargs['default'] = '{}'
         elif isinstance(default, (list, dict)):
             kwargs['default'] = dumps(default)


Test patch:
Repository: django-extensions/django-extensions

Issue:
print_user_for_session doesn't look for USERNAME_FIELD attr on custom User models
Throws following error when using custom user model.

```
AttributeError: 'ProfileUser' object has no attribute 'username'
```

(django>=1.5 issue)



Discussion:

Resolving patch:
diff --git a/django_extensions/management/commands/print_user_for_session.py b/django_extensions/management/commands/print_user_for_session.py
--- a/django_extensions/management/commands/print_user_for_session.py
+++ b/django_extensions/management/commands/print_user_for_session.py
@@ -62,5 +62,10 @@ def handle(self, *args, **options):
             print("No user associated with that id.")
             return
 
-        for key in ['username', 'email', 'first_name', 'last_name']:
+        username_field = 'username'
+
+        if hasattr(User, 'USERNAME_FIELD') and User.USERNAME_FIELD is not None:
+            username_field = User.USERNAME_FIELD
+
+        for key in [username_field, 'email', 'first_name', 'last_name']:
             print("%s: %s" % (key, getattr(user, key)))


Test patch:
Repository: django-extensions/django-extensions

Issue:
reset_db breaks with PostGIS without a template_postgis
https://github.com/django-extensions/django-extensions/blob/73376f3e246c2523b9929c48eb74c9a7ad6788ce/django_extensions/management/commands/reset_db.py#L146 assumes that a template database exists, and is called `template_postgis`. Both assumptions are bad, as the template database can be [changed](https://docs.djangoproject.com/en/dev/ref/contrib/gis/testing/#postgis-template). With PostGIS 2.0 and PostgreSQL 9.1, a template database is [not necessary](https://docs.djangoproject.com/en/dev/ref/contrib/gis/install/postgis/#post-installation) anymore.

The correct fix is probably to use `template_postgis` from `django.contrib.gis.db.backends.postgis.creation` and only append the `TEMPLATE` to the SQL if it is not `None`. As it stands, I can't use `reset_db` with a modern PostGIS setup.



Discussion:
@maikhoepfel Can you make a pull request? Also I'm not sure how is going to deal with backwards compatibility.

@maikhoepfel any updates?

@camilonova I unfortunately won't have time to work on this beyond filing the issue. 


Resolving patch:
diff --git a/django_extensions/management/commands/reset_db.py b/django_extensions/management/commands/reset_db.py
--- a/django_extensions/management/commands/reset_db.py
+++ b/django_extensions/management/commands/reset_db.py
@@ -143,7 +143,11 @@ def handle(self, *args, **options):
             create_query += " ENCODING = 'UTF8'"
 
             if engine == 'postgis':
-                create_query += ' TEMPLATE = template_postgis'
+                # fetch postgis template name if it exists
+                from django.contrib.gis.db.backends.postgis.creation import PostGISCreation
+                postgis_template = PostGISCreation(connection).template_postgis
+                if postgis_template is not None:
+                    create_query += ' TEMPLATE = %s' % postgis_template
 
             if settings.DEFAULT_TABLESPACE:
                 create_query += ' TABLESPACE = %s;' % settings.DEFAULT_TABLESPACE


Test patch:
Repository: django-extensions/django-extensions

Issue:
Django 1.7 JSONField migrations broken
BUG: adding a new JSONField to an existing Model sets the default value for existing Model instances incorrectly - the value stored in the DB is `"{}"` instead of just `{}`. Steps below:

**1. Create a migration for the following model:**

```
class JSONTest(models.Model):
    settings = JSONField(blank=True)
```

**2. Run `./manage.py migrate`**
**3. Run `./manage.py shell` and create a new `JSONTest` object:**

```
JSONTest.objects.create()
```

**4. Change the model to add another `JSONField` (like below) and create another migration:**

```
class JSONTest(models.Model):
    settings = JSONField(blank=True)
    settings2 = JSONField(blank=True)
```

**5. Run `./manage migrate`**
**6. Run `./manage.py shell` and get the `JSONTest` instance you created in step 3 above:**

```
o = JSONTest.objects.get(pk=1)
o.settings2
```

BUG: note that the default value of the newly added `settings2` field is `"{}"` instead of `{}`. Will be submitting a pull request for this.



Discussion:

Resolving patch:
diff --git a/django_extensions/db/fields/json.py b/django_extensions/db/fields/json.py
--- a/django_extensions/db/fields/json.py
+++ b/django_extensions/db/fields/json.py
@@ -94,7 +94,11 @@ def get_db_prep_save(self, value, connection, **kwargs):
         """Convert our JSON object to a string before we save"""
         if value is None and self.null:
             return None
-        return super(JSONField, self).get_db_prep_save(dumps(value), connection=connection)
+        # default values come in as strings; only non-strings should be
+        # run through `dumps`
+        if not isinstance(value, six.string_types):
+            value = dumps(value)
+        return super(JSONField, self).get_db_prep_save(value, connection=connection)
 
     def south_field_triple(self):
         """Returns a suitable description of this field for South."""


Test patch:
Repository: django-extensions/django-extensions

Issue:
sync_s3 broken with py3
```
  File "/home/kondou/git/project/lib/python3.4/site-packages/django_extensions/management/commands/sync_s3.py", line 261, in sync_s3
    os.path.walk(directory, self.upload_s3, (bucket, key, self.AWS_BUCKET_NAME, directory))
AttributeError: 'module' object has no attribute 'walk'
```

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/sync_s3.py#L261

https://docs.python.org/2/library/os.path.html#os.path.walk

> This function is deprecated and has been removed in Python 3 in favor of os.walk().

In #45 there was a version that used `os.walk()` but it got rejected.



Discussion:
#45 was not so much rejected as it was old and there was no activity on that ticket.

Happy to accept PR's to fix this.


Resolving patch:
diff --git a/django_extensions/management/commands/sync_s3.py b/django_extensions/management/commands/sync_s3.py
--- a/django_extensions/management/commands/sync_s3.py
+++ b/django_extensions/management/commands/sync_s3.py
@@ -258,7 +258,8 @@ def sync_s3(self):
         """
         bucket, key = self.open_s3()
         for directory in self.DIRECTORIES:
-            os.path.walk(directory, self.upload_s3, (bucket, key, self.AWS_BUCKET_NAME, directory))
+            for root, dirs, files in os.walk(directory):
+                self.upload_s3((bucket, key, self.AWS_BUCKET_NAME, directory), root, files)
 
     def compress_string(self, s):
         """Gzip a given string."""


Test patch:
Repository: django-extensions/django-extensions

Issue:
runserver plus is not showing migration warnings
for runserver command, it shows warning 

```
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
```

but for runserver plus  they are not showing up



Discussion:

Resolving patch:
diff --git a/django_extensions/management/commands/runserver_plus.py b/django_extensions/management/commands/runserver_plus.py
--- a/django_extensions/management/commands/runserver_plus.py
+++ b/django_extensions/management/commands/runserver_plus.py
@@ -8,6 +8,9 @@
 
 from django.conf import settings
 from django.core.management.base import BaseCommand, CommandError
+from django.db import connections, DEFAULT_DB_ALIAS
+from django.db.migrations.executor import MigrationExecutor
+from django.core.exceptions import ImproperlyConfigured
 
 from django_extensions.management.technical_response import \
     null_technical_500_response
@@ -235,8 +238,12 @@ def postmortem(request, exc_type, exc_value, tb):
         reloader_interval = options.get('reloader_interval', 1)
 
         def inner_run():
-            print("Validating models...")
+            print("Performing system checks...\n")
             self.validate(display_num_errors=True)
+            try:
+                self.check_migrations()
+            except ImproperlyConfigured:
+                pass
             print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE))
             print("Development server is running at %s" % (bind_url,))
             print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)")
@@ -318,6 +325,17 @@ def inner_run():
             )
         inner_run()
 
+    def check_migrations(self):
+        """
+        Checks to see if the set of migrations on disk matches the
+        migrations in the database. Prints a warning if they don't match.
+        """
+        executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
+        plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
+        if plan:
+            self.stdout.write(self.style.NOTICE("\nYou have unapplied migrations; your app may not work properly until they are applied."))
+            self.stdout.write(self.style.NOTICE("Run 'python manage.py migrate' to apply them.\n"))
+
 
 def set_werkzeug_log_color():
     """Try to set color to the werkzeug log.


Test patch:
Repository: django-extensions/django-extensions

Issue:
graph_models fails with relations with unicode names
This is a followup to #737. Looks like relations are affected as well. Working with the testcase in #737, if you a model like:

```
class MyRelatedModel(models.Model):
    related = models.ForeignKey(MyTestModel, verbose_name=u"Relación")
```

It fails similarly. The fix is the same as in #737.



Discussion:

Resolving patch:
diff --git a/django_extensions/management/modelviz.py b/django_extensions/management/modelviz.py
--- a/django_extensions/management/modelviz.py
+++ b/django_extensions/management/modelviz.py
@@ -198,7 +198,7 @@ def add_attributes(field):
             # relations
             def add_relation(field, extras=""):
                 if verbose_names and field.verbose_name:
-                    label = field.verbose_name.decode("utf8")
+                    label = force_bytes(field.verbose_name)
                     if label.islower():
                         label = label.capitalize()
                 else:


Test patch: