internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: redis/redis-py

Issue:
redis._compat: global name 'InterruptedError' is not defined
In the [compat module](https://github.com/andymccurdy/redis-py/blob/master/redis/_compat.py), this code is broken:
```python
# For Python older than 3.5, retry EINTR.
if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and
                               sys.version_info[1] < 5):
    # Adapted from https://bugs.python.org/review/23863/patch/14532/54418
    import socket
    import time
    import errno

    from select import select as _select

    def select(rlist, wlist, xlist, timeout):
        while True:
            try:
                return _select(rlist, wlist, xlist, timeout)
            except InterruptedError:
                continue
```

The problem is that it uses `InterruptedError`, but this exception only exists in Python 3, not Python 2.


Discussion:

Resolving patch:
diff --git a/redis/_compat.py b/redis/_compat.py
--- a/redis/_compat.py
+++ b/redis/_compat.py
@@ -1,6 +1,12 @@
 """Internal module for Python 2 backwards compatibility."""
+import errno
 import sys
 
+try:
+    InterruptedError = InterruptedError
+except:
+    InterruptedError = OSError
+
 # For Python older than 3.5, retry EINTR.
 if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and
                                sys.version_info[1] < 5):
@@ -15,8 +21,12 @@ def select(rlist, wlist, xlist, timeout):
         while True:
             try:
                 return _select(rlist, wlist, xlist, timeout)
-            except InterruptedError:
-                continue
+            except InterruptedError as e:
+                # Python 2 does not define InterruptedError, instead
+                # try to catch an OSError with errno == EINTR == 4.
+                if getattr(e, 'errno', None) == getattr(errno, 'EINTR', 4):
+                    continue
+                raise
 
     # Wrapper for handling interruptable system calls.
     def _retryable_call(s, func, *args, **kwargs):


Test patch:
Repository: redis/redis-py

Issue:
Improve if statement throwing KeyError
At line 210, if WITHSCORES is not specified within `execute_command()`, this line used to throw a `KeyError` because the relative key in `options` is not present. Solution: this PR add a check on the key 'withscores' before the key is accessed.


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -207,7 +207,7 @@ def zset_score_pairs(response, **options):
     If ``withscores`` is specified in the options, return the response as
     a list of (value, score) pairs
     """
-    if not response or not options['withscores']:
+    if not response or not options.get('withscores'):
         return response
     score_cast_func = options.get('score_cast_func', float)
     it = iter(response)


Test patch:
Repository: redis/redis-py

Issue:
`sort` raises KeyError exception
Running the following example:

```python
import redis

r = redis.StrictRedis()
print(r.execute_command('SADD', 1, 4))
print(r.execute_command('SORT', 1))
```

Results in:

```
  File "~/src/redis-py/SORT-issue.py", line 5, in <module>
    print(r.execute_command('SORT', 1))
  File "~/src/redis-py/redis/client.py", line 669, in execute_command
    return self.parse_response(connection, command_name, **options)
  File "~/src/redis-py/redis/client.py", line 683, in parse_response
    return self.response_callbacks[command_name](response, **options)
  File "~/src/redis-py/redis/client.py", line 223, in sort_return_tuples
    if not response or not options['groups']:
KeyError: 'groups'
```

The fix appears trivial so I'll make a PR that includes the test case :)

Credit for reporting and all internet points go to @oranagra


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -220,7 +220,7 @@ def sort_return_tuples(response, **options):
     If ``groups`` is specified, return the response as a list of
     n-element tuples with n being the value found in options['groups']
     """
-    if not response or not options['groups']:
+    if not response or not options.get('groups'):
         return response
     n = options['groups']
     return list(izip(*[response[i::n] for i in range(n)]))


Test patch:
diff --git a/tests/test_commands.py b/tests/test_commands.py
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -1375,6 +1375,11 @@ def test_sort_all_options(self, r):
         assert r.lrange('sorted', 0, 10) == \
             [b('vodka'), b('milk'), b('gin'), b('apple juice')]
 
+    def test_sort_issue_924(self, r):
+        # Tests for issue https://github.com/andymccurdy/redis-py/issues/924
+        r.execute_command('SADD', 'issue#924', 1)
+        r.execute_command('SORT', 'issue#924')
+
     def test_cluster_addslots(self, mock_cluster_resp_ok):
         assert mock_cluster_resp_ok.cluster('ADDSLOTS', 1) is True
Repository: redis/redis-py

Issue:
`StrictRedis.from_url` does not document support for `rediss://` scheme
This covers a subset of #780.

The method [`StrictRedis.from_url`](https://github.com/andymccurdy/redis-py/blob/71b69ed31a615305c0af18c34a764eee410586bf/redis/client.py#L462) accepts URLs with protocol `rediss://`. But documentation does not reflect this.


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -532,16 +532,24 @@ class StrictRedis(object):
     @classmethod
     def from_url(cls, url, db=None, **kwargs):
         """
-        Return a Redis client object configured from the given URL, which must
-        use either `the ``redis://`` scheme
-        <https://www.iana.org/assignments/uri-schemes/prov/redis>`_ for RESP
-        connections or the ``unix://`` scheme for Unix domain sockets.
+        Return a Redis client object configured from the given URL
 
         For example::
 
             redis://[:password]@localhost:6379/0
+            rediss://[:password]@localhost:6379/0
             unix://[:password]@/path/to/socket.sock?db=0
 
+        Three URL schemes are supported:
+
+        - ```redis://``
+          <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a
+          normal TCP socket connection
+        - ```rediss://``
+          <http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a
+          SSL wrapped TCP socket connection
+        - ``unix://`` creates a Unix Domain Socket connection
+
         There are several ways to specify a database number. The parse function
         will return the first specified option:
             1. A ``db`` querystring option, e.g. redis://localhost?db=0


Test patch:
Repository: redis/redis-py

Issue:
redis-py ssl support susceptible to MITM attacks by default
**Issue:** redis-py doesn't enforce hostname validation (Common Name nor Subject Alternative Name) by default when accepting a cert from a remote SSL terminator. This default behavior isn't compatible to accepted PEPs/RFCs and provides a dangerous sense of false security.

**Task:** Correct redis-py to validate certificates by default. IMHO this shouldn't be considered a breaking change as it simply reenforces the expected results when initiating a SSL connection.

**Additional research:**
- https://tools.ietf.org/html/rfc6125
- https://www.python.org/dev/peps/pep-0476/
- https://wiki.openssl.org/index.php/Hostname_validation



Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -496,7 +496,7 @@ def __init__(self, host='localhost', port=6379,
                  charset=None, errors=None,
                  decode_responses=False, retry_on_timeout=False,
                  ssl=False, ssl_keyfile=None, ssl_certfile=None,
-                 ssl_cert_reqs=None, ssl_ca_certs=None,
+                 ssl_cert_reqs='required', ssl_ca_certs=None,
                  max_connections=None):
         if not connection_pool:
             if charset is not None:
diff --git a/redis/connection.py b/redis/connection.py
--- a/redis/connection.py
+++ b/redis/connection.py
@@ -687,8 +687,8 @@ def pack_commands(self, commands):
 class SSLConnection(Connection):
     description_format = "SSLConnection<host=%(host)s,port=%(port)s,db=%(db)s>"
 
-    def __init__(self, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs=None,
-                 ssl_ca_certs=None, **kwargs):
+    def __init__(self, ssl_keyfile=None, ssl_certfile=None,
+                 ssl_cert_reqs='required', ssl_ca_certs=None, **kwargs):
         if not ssl_available:
             raise RedisError("Python wasn't built with SSL support")
 


Test patch:
Repository: redis/redis-py

Issue:
command SHUTDOWN missing NOSAVE option
The SHUTDOWN command doesn't implement the NOSAVE option that Redis supports.  This option prevents Redis from saving the current in-memory state to the persistent files before a shutdown.


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -822,10 +822,22 @@ def sentinel_slaves(self, service_name):
         "Returns a list of slaves for ``service_name``"
         return self.execute_command('SENTINEL SLAVES', service_name)
 
-    def shutdown(self):
-        "Shutdown the server"
+    def shutdown(self, save=False, nosave=False):
+        """Shutdown the Redis server.  If Redis has persistence configured,
+        data will be flushed before shutdown.  If the "save" option is set,
+        a data flush will be attempted even if there is no persistence
+        configured.  If the "nosave" option is set, no data flush will be
+        attempted.  The "save" and "nosave" options cannot both be set.
+        """
+        if save and nosave:
+            raise RedisError('SHUTDOWN save and nosave cannot both be set')
+        args = ['SHUTDOWN']
+        if save:
+            args.append('SAVE')
+        if nosave:
+            args.append('NOSAVE')
         try:
-            self.execute_command('SHUTDOWN')
+            self.execute_command(*args)
         except ConnectionError:
             # a ConnectionError here is expected
             return


Test patch:
Repository: redis/redis-py

Issue:
SWAPDB is not supported
New in Redis v4


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -439,7 +439,7 @@ class StrictRedis(object):
         string_keys_to_dict('ZSCORE ZINCRBY', float_or_none),
         string_keys_to_dict(
             'FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE RENAME '
-            'SAVE SELECT SHUTDOWN SLAVEOF WATCH UNWATCH',
+            'SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH',
             bool_ok
         ),
         string_keys_to_dict('BLPOP BRPOP', lambda r: r and tuple(r) or None),
@@ -817,6 +817,10 @@ def flushdb(self):
         "Delete all keys in the current database"
         return self.execute_command('FLUSHDB')
 
+    def swapdb(self, first, second):
+        "Swap two databases"
+        return self.execute_command('SWAPDB', first, second)
+
     def info(self, section=None):
         """
         Returns a dictionary containing information about the Redis server


Test patch:
Repository: redis/redis-py

Issue:
using new command "MEMORY USAGE"
I want to use this command https://redis.io/commands/memory-usage

It doesn't seem to be supported yet. 

I tried circumventing by using 

```python
redis.execute_command("MEMORY USAGE {}".format(key))
```

But in some cases I'm getting a `"None"` response even though it works when directly doing so in the redis-cli.

I suspect that I am perhaps not escaping some character correctly or otherwise.


Discussion:
was able to resolve by doing 

```
execute_command("MEMORY USAGE",key)
```

@andymccurdy This issue can be closed as it was resolved.

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -495,6 +495,8 @@ class StrictRedis(object):
             'HSCAN': parse_hscan,
             'INFO': parse_info,
             'LASTSAVE': timestamp_to_datetime,
+            'MEMORY PURGE': bool_ok,
+            'MEMORY USAGE': int_or_none,
             'OBJECT': parse_object,
             'PING': lambda r: nativestr(r) == 'PONG',
             'PUBSUB NUMSUB': parse_pubsub_numsub,
@@ -895,6 +897,24 @@ def object(self, infotype, key):
         "Return the encoding, idletime, or refcount about the key"
         return self.execute_command('OBJECT', infotype, key, infotype=infotype)
 
+    def memory_usage(self, key, samples=None):
+        """
+        Return the total memory usage for key, its value and associated
+        administrative overheads.
+
+        For nested data structures, ``samples`` is the number of elements to
+        sample. If left unspecified, the server's default is 5. Use 0 to sample
+        all elements.
+        """
+        args = []
+        if isinstance(samples, int):
+            args.extend([Token.get_token('SAMPLES'), samples])
+        return self.execute_command('MEMORY USAGE', key, *args)
+
+    def memory_purge(self):
+        "Attempts to purge dirty pages for reclamation by allocator"
+        return self.execute_command('MEMORY PURGE')
+
     def ping(self):
         "Ping the Redis server"
         return self.execute_command('PING')


Test patch:
diff --git a/tests/test_commands.py b/tests/test_commands.py
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -2177,6 +2177,11 @@ def test_bitfield_operations(self, r):
                 .execute())
         assert resp == [0, None, 255]
 
+    @skip_if_server_version_lt('4.0.0')
+    def test_memory_usage(self, r):
+        r.set('foo', 'bar')
+        assert isinstance(r.memory_usage('foo'), int)
+
 
 class TestStrictCommands(object):
     def test_strict_zadd(self, sr):
Repository: redis/redis-py

Issue:
AttributeError: 'UnixDomainSocketConnection' object has no attribute '_buffer_cutoff'
Since version 3.0, redis client seems broken. I cannot even get, set or keys() anything when connecting to unix socket.
I tried running it in a docker container running centos 7.5.1804 core using python3.6.
Steps to reproduce:
 install redis 3.0
```python
import redis
red = redis.Redis(unix_socket_path = "/path/to/socket")
red.keys()
```
Throws this:
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/redis/client.py", line 1262, in keys
    return self.execute_command('KEYS', pattern)
  File "/usr/lib/python3.6/site-packages/redis/client.py", line 754, in execute_command
    connection.send_command(*args)
  File "/usr/lib/python3.6/site-packages/redis/connection.py", line 619, in send_command
    self.send_packed_command(self.pack_command(*args))
  File "/usr/lib/python3.6/site-packages/redis/connection.py", line 658, in pack_command
    buffer_cutoff = self._buffer_cutoff
AttributeError: 'UnixDomainSocketConnection' object has no attribute '_buffer_cutoff'
```



Discussion:
Same problem for me, on both macOS Mojave 10.14.1 and Ubuntu 16.04.
Spotted the same issue via `pytest-redis`, which uses a session specific directory + socket file under `/tmp`.

Bug was introduced in 2015(!), and just merged recently? 5c07e3d6803

Quick fix might be to add `self._buffer_cutoff` also to `UnixDomainSocketConnection`.

Resolving patch:
diff --git a/redis/connection.py b/redis/connection.py
--- a/redis/connection.py
+++ b/redis/connection.py
@@ -759,6 +759,7 @@ def __init__(self, path='', db=0, password=None,
             'db': self.db,
         }
         self._connect_callbacks = []
+        self._buffer_cutoff = 6000
 
     def _connect(self):
         "Create a Unix domain socket connection"


Test patch:
Repository: redis/redis-py

Issue:
Fix simple typo: recurrsion -> recursion
There is a small typo in redis/connection.py.
Should read recursion rather than recurrsion.




Discussion:

Resolving patch:
diff --git a/redis/connection.py b/redis/connection.py
--- a/redis/connection.py
+++ b/redis/connection.py
@@ -656,7 +656,7 @@ def send_packed_command(self, command, check_health=True):
         "Send an already packed command to the Redis server"
         if not self._sock:
             self.connect()
-        # guard against health check recurrsion
+        # guard against health check recursion
         if check_health:
             self.check_health()
         try:


Test patch:
Repository: redis/redis-py

Issue:
redis lmove
Hello everybody
I have seen that redis-py library is no longer updated since June of 2020, although since then it was regularly updated on a quarterly basis. Considering this, do you perhaps have any idea of when the next release of that library, including the LMove method, will be distributed? 


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -567,8 +567,8 @@ class Redis:
     """
     RESPONSE_CALLBACKS = {
         **string_keys_to_dict(
-            'AUTH COPY EXPIRE EXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST '
-            'PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNX',
+            'AUTH COPY EXPIRE EXPIREAT HEXISTS HMSET LMOVE BLMOVE MOVE '
+            'MSETNX PERSIST PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNX',
             bool
         ),
         **string_keys_to_dict(
@@ -1834,6 +1834,23 @@ def keys(self, pattern='*'):
         "Returns a list of keys matching ``pattern``"
         return self.execute_command('KEYS', pattern)
 
+    def lmove(self, first_list, second_list, src="LEFT", dest="RIGHT"):
+        """
+        Atomically returns and removes the first/last element of a list,
+        pushing it as the first/last element on the destination list.
+        Returns the element being popped and pushed.
+        """
+        params = [first_list, second_list, src, dest]
+        return self.execute_command("LMOVE", *params)
+
+    def blmove(self, first_list, second_list, timeout,
+               src="LEFT", dest="RIGHT"):
+        """
+        Blocking version of lmove.
+        """
+        params = [first_list, second_list, src, dest, timeout]
+        return self.execute_command("BLMOVE", *params)
+
     def mget(self, keys, *args):
         """
         Returns a list of values ordered identically to ``keys``


Test patch:
diff --git a/tests/test_commands.py b/tests/test_commands.py
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -849,6 +849,18 @@ def test_mget(self, r):
         r['c'] = '3'
         assert r.mget('a', 'other', 'b', 'c') == [b'1', None, b'2', b'3']
 
+    @skip_if_server_version_lt('6.2.0')
+    def test_lmove(self, r):
+        r.rpush('a', 'one', 'two', 'three', 'four')
+        assert r.lmove('a', 'b')
+        assert r.lmove('a', 'b', 'right', 'left')
+
+    @skip_if_server_version_lt('6.2.0')
+    def test_blmove(self, r):
+        r.rpush('a', 'one', 'two', 'three', 'four')
+        assert r.blmove('a', 'b', 5)
+        assert r.blmove('a', 'b', 1, 'RIGHT', 'LEFT')
+
     def test_mset(self, r):
         d = {'a': b'1', 'b': b'2', 'c': b'3'}
         assert r.mset(d)
Repository: redis/redis-py

Issue:
Support for CLIENT UNPAUSE
redis-py currently doesn't have support for [CLIENT UNPAUSE](https://redis.io/commands/client-unpause), new in 6.2.0.


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -1292,6 +1292,12 @@ def client_pause(self, timeout):
             raise DataError("CLIENT PAUSE timeout must be an integer")
         return self.execute_command('CLIENT PAUSE', str(timeout))
 
+    def client_unpause(self):
+        """
+        Unpause all redis clients
+        """
+        return self.execute_command('CLIENT UNPAUSE')
+
     def readwrite(self):
         "Disables read queries for a connection to a Redis Cluster slave node"
         return self.execute_command('READWRITE')


Test patch:
diff --git a/tests/test_commands.py b/tests/test_commands.py
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -396,6 +396,10 @@ def test_client_pause(self, r):
         with pytest.raises(exceptions.RedisError):
             r.client_pause(timeout='not an integer')
 
+    @skip_if_server_version_lt('6.2.0')
+    def test_client_unpause(self, r):
+        assert r.client_unpause() == b'OK'
+
     def test_config_get(self, r):
         data = r.config_get()
         assert 'maxmemory' in data
Repository: redis/redis-py

Issue:
getex currently allows exclusive options
ex, px, exat, and pxat are mutually exclusive - we should validate that on input.


Discussion:

Resolving patch:
diff --git a/redis/client.py b/redis/client.py
--- a/redis/client.py
+++ b/redis/client.py
@@ -1737,6 +1737,11 @@ def getex(self, name,
         ``persist`` remove the time to live associated with ``name``.
         """
 
+        opset = set([ex, px, exat, pxat])
+        if len(opset) > 2 or len(opset) > 1 and persist:
+            raise DataError("``ex``, ``px``, ``exat``, ``pxat``",
+                            "and ``persist`` are mutually exclusive.")
+
         pieces = []
         # similar to set command
         if ex is not None:


Test patch: