nebius/SWE-bench-extra huggingface dataset:
Repository: dirty-cat/dirty_cat

Issue:
MinHashEncoder does not understand "None" as missing value
The following raises an error because the None is not captured as a NaN:
```python
import numpy as np

a = np.array([['a', 'b', None, 'c']], dtype=object).T

from dirty_cat import MinHashEncoder

enc = MinHashEncoder()
enc.fit_transform(a)
```


Comments:

Patch:
diff --git a/CHANGES.rst b/CHANGES.rst
index f774809..49769fe 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -3,12 +3,21 @@
 Release 0.4.0
 =============
 
-Minor changes
+Major changes
 -------------
 
 * Unnecessary API has been made private: everything (files, functions, classes)
   starting with an underscore shouldn't be imported in your code.
 
+Minor changes
+-------------
+
+Bug fixes
+---------
+
+* :class:`MinHashEncoder` now considers `None` as missing values, rather
+  than raising an error.
+
 Release 0.3.0
 =============
 
@@ -55,7 +64,7 @@ Notes
 Release 0.2.2
 =============
 
-Bug-fixes
+Bug fixes
 ---------
 
 * Fixed a bug in the :class:`SuperVectorizer` causing a `FutureWarning`
diff --git a/dirty_cat/_minhash_encoder.py b/dirty_cat/_minhash_encoder.py
index 96a9a6e..8c6c86c 100644
--- a/dirty_cat/_minhash_encoder.py
+++ b/dirty_cat/_minhash_encoder.py
@@ -26,6 +26,7 @@ from ._fast_hash import ngram_min_hash
 from ._string_distances import get_unique_ngrams
 from ._utils import LRUDict, check_input
 
+NoneType = type(None)
 
 class MinHashEncoder(BaseEstimator, TransformerMixin):
     """
@@ -208,7 +209,8 @@ class MinHashEncoder(BaseEstimator, TransformerMixin):
             for k in range(X.shape[1]):
                 X_in = X[:, k].reshape(-1)
                 for i, x in enumerate(X_in):
-                    if isinstance(x, float):  # true if x is a missing value
+                    if (isinstance(x, float)  # true if x is a missing value
+                        or x is None):
                         is_nan_idx = True
                     elif x not in self.hash_dict_:
                         X_out[i, k * self.n_components : counter] = self.hash_dict_[


Test patch:
diff --git a/dirty_cat/tests/test_minhash_encoder.py b/dirty_cat/tests/test_minhash_encoder.py
index b55f56d..c640fb0 100644
--- a/dirty_cat/tests/test_minhash_encoder.py
+++ b/dirty_cat/tests/test_minhash_encoder.py
@@ -133,6 +133,15 @@ def test_missing_values(input_type: str, missing: str, hashing: str) -> None:
     return
 
 
+def test_missing_values_none():
+    # Test that "None" is also understood as a missing value
+    a = np.array([['a', 'b', None, 'c']], dtype=object).T
+
+    enc = MinHashEncoder()
+    d = enc.fit_transform(a)
+    np.testing.assert_array_equal(d[2], 0)
+
+
 def test_cache_overflow() -> None:
     # Regression test for cache overflow resulting in -1s in encoding
     def get_random_string(length):
Repository: django-money/django-money

Issue:
Money should not override `__rsub__` method
As [reported](https://github.com/py-moneyed/py-moneyed/issues/144) in pymoneyed the following test case fails:

```python
from moneyed import Money as PyMoney
from djmoney.money import Money


def test_sub_negative():
    total = PyMoney(0, "EUR")
    bills = (Money(8, "EUR"), Money(25, "EUR"))
    for bill in bills:
        total -= bill
    assert total == Money(-33, "EUR")

# AssertionError: assert <Money: -17 EUR> == <Money: -33 EUR>
```

This is caused by `djmoney.money.Money` overriding `__rsub__`.

Comments:

Patch:
diff --git a/djmoney/money.py b/djmoney/money.py
index 70bea0b..b744c66 100644
--- a/djmoney/money.py
+++ b/djmoney/money.py
@@ -106,7 +106,6 @@ class Money(DefaultMoney):
     # we overwrite the 'targets' so the wrong synonyms are called
     # Example: we overwrite __add__; __radd__ calls __add__ on DefaultMoney...
     __radd__ = __add__
-    __rsub__ = __sub__
     __rmul__ = __mul__
 
 
diff --git a/docs/changes.rst b/docs/changes.rst
index 2643b4d..8c0b272 100644
--- a/docs/changes.rst
+++ b/docs/changes.rst
@@ -15,6 +15,7 @@ Changelog
 **Fixed**
 
 - Pin ``pymoneyed<1.0`` as it changed the ``repr`` output of the ``Money`` class.
+- Subtracting ``Money`` from ``moneyed.Money``. Regression, introduced in ``1.2``. `#593`_
 
 `1.2.2`_ - 2020-12-29
 ---------------------
@@ -694,6 +695,7 @@ wrapping with ``money_manager``.
 .. _0.3: https://github.com/django-money/django-money/compare/0.2...0.3
 .. _0.2: https://github.com/django-money/django-money/compare/0.2...a6d90348085332a393abb40b86b5dd9505489b04
 
+.. _#593: https://github.com/django-money/django-money/issues/593
 .. _#586: https://github.com/django-money/django-money/issues/586
 .. _#585: https://github.com/django-money/django-money/pull/585
 .. _#583: https://github.com/django-money/django-money/issues/583


Test patch:
diff --git a/tests/test_money.py b/tests/test_money.py
index 65199c4..bb7ea79 100644
--- a/tests/test_money.py
+++ b/tests/test_money.py
@@ -2,7 +2,7 @@ from django.utils.translation import override
 
 import pytest
 
-from djmoney.money import Money, get_current_locale
+from djmoney.money import DefaultMoney, Money, get_current_locale
 
 
 def test_repr():
@@ -114,3 +114,12 @@ def test_decimal_places_display_overwrite():
     assert str(number) == "$1.23457"
     number.decimal_places_display = None
     assert str(number) == "$1.23"
+
+
+def test_sub_negative():
+    # See GH-593
+    total = DefaultMoney(0, "EUR")
+    bills = (Money(8, "EUR"), Money(25, "EUR"))
+    for bill in bills:
+        total -= bill
+    assert total == Money(-33, "EUR")
Repository: django-money/django-money

Issue:
default_currency=None keeps detecting migration changes
Based on the comment in the discussion found here: https://github.com/django-money/django-money/issues/530#issuecomment-650166087

If `MoneyField(..., default_currency=None)` is added to an already existing model, so that the field is triggering migration operations `AddField` or `AlterField`. Django keeps detecting changes on the field/model when running `python manage.py makemigrations`.

Comments:

Patch:
diff --git a/djmoney/models/fields.py b/djmoney/models/fields.py
index 9b7195e..9d42575 100644
--- a/djmoney/models/fields.py
+++ b/djmoney/models/fields.py
@@ -298,8 +298,11 @@ class MoneyField(models.DecimalField):
 
         if self._has_default:
             kwargs["default"] = self.default.amount
-        if self.default_currency is not None and self.default_currency != DEFAULT_CURRENCY:
-            kwargs["default_currency"] = str(self.default_currency)
+        if self.default_currency != DEFAULT_CURRENCY:
+            if self.default_currency is not None:
+                kwargs["default_currency"] = str(self.default_currency)
+            else:
+                kwargs["default_currency"] = None
         if self.currency_choices != CURRENCY_CHOICES:
             kwargs["currency_choices"] = self.currency_choices
         if self.currency_field_name:


Test patch:
diff --git a/tests/test_models.py b/tests/test_models.py
index f573ed3..506fac4 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -787,3 +787,11 @@ def test_mixer_blend():
         instance = mixer.blend(ModelWithTwoMoneyFields)
         assert isinstance(instance.amount1, Money)
         assert isinstance(instance.amount2, Money)
+
+
+def test_deconstruct_includes_default_currency_as_none():
+    instance = ModelWithNullableCurrency()._meta.get_field("money")
+    __, ___, args, kwargs = instance.deconstruct()
+    new = MoneyField(*args, **kwargs)
+    assert new.default_currency == instance.default_currency
+    assert new.default_currency is None
Repository: django-money/django-money

Issue:
calling get_rate with identical source and target currency should be a noop
- it is always exactly 1
- that doesn't even have to hit the cache ;)

Comments:

Patch:
diff --git a/djmoney/contrib/exchange/models.py b/djmoney/contrib/exchange/models.py
index 4d97846..7963967 100644
--- a/djmoney/contrib/exchange/models.py
+++ b/djmoney/contrib/exchange/models.py
@@ -40,6 +40,8 @@ def get_rate(source, target, backend=None):
     Converts exchange rate on the DB side if there is no backends with given base currency.
     Uses data from the default backend if the backend is not specified.
     """
+    if str(source) == str(target):
+        return 1
     if backend is None:
         backend = get_default_backend_name()
     key = f"djmoney:get_rate:{source}:{target}:{backend}"
@@ -53,8 +55,6 @@ def get_rate(source, target, backend=None):
 
 def _get_rate(source, target, backend):
     source, target = str(source), str(target)
-    if str(source) == target:
-        return 1
     rates = Rate.objects.filter(currency__in=(source, target), backend=backend).select_related("backend")
     if not rates:
         raise MissingRate(f"Rate {source} -> {target} does not exist")


Test patch:
diff --git a/tests/contrib/exchange/test_model.py b/tests/contrib/exchange/test_model.py
index 4bd6b75..4d37c78 100644
--- a/tests/contrib/exchange/test_model.py
+++ b/tests/contrib/exchange/test_model.py
@@ -64,8 +64,10 @@ def test_string_representation(backend):
 def test_cache():
     with patch("djmoney.contrib.exchange.models._get_rate", wraps=_get_rate) as original:
         assert get_rate("USD", "USD") == 1
+        assert original.call_count == 0
+        assert get_rate("USD", "EUR") == 2
         assert original.call_count == 1
-        assert get_rate("USD", "USD") == 1
+        assert get_rate("USD", "EUR") == 2
         assert original.call_count == 1
 
 
diff --git a/tests/contrib/test_django_rest_framework.py b/tests/contrib/test_django_rest_framework.py
index 4a7e4a2..5372a91 100644
--- a/tests/contrib/test_django_rest_framework.py
+++ b/tests/contrib/test_django_rest_framework.py
@@ -106,7 +106,7 @@ class TestMoneyField:
 
     def test_serializer_with_fields(self):
         serializer = self.get_serializer(ModelWithVanillaMoneyField, data={"money": "10.00"}, fields_=("money",))
-        serializer.is_valid(True)
+        serializer.is_valid(raise_exception=True)
         assert serializer.data == {"money": "10.00"}
 
     @pytest.mark.parametrize(
Repository: django/asgiref

Issue:
WSGI Error in non-ascii path
https://github.com/encode/starlette/issues/997

I noticed that the ASGI document clearly states that utf8 encoding is required, but WSGI seems to require latin-1 encoding.

https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types
https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope

Comments:

Patch:
diff --git a/asgiref/wsgi.py b/asgiref/wsgi.py
index 7155ab2..8811118 100644
--- a/asgiref/wsgi.py
+++ b/asgiref/wsgi.py
@@ -55,8 +55,8 @@ class WsgiToAsgiInstance:
         """
         environ = {
             "REQUEST_METHOD": scope["method"],
-            "SCRIPT_NAME": scope.get("root_path", ""),
-            "PATH_INFO": scope["path"],
+            "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
+            "PATH_INFO": scope["path"].encode("utf8").decode("latin1"),
             "QUERY_STRING": scope["query_string"].decode("ascii"),
             "SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
             "wsgi.version": (1, 0),


Test patch:
diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py
index 647f465..3490573 100644
--- a/tests/test_wsgi.py
+++ b/tests/test_wsgi.py
@@ -50,6 +50,48 @@ async def test_basic_wsgi():
     assert (await instance.receive_output(1)) == {"type": "http.response.body"}
 
 
+@pytest.mark.asyncio
+async def test_wsgi_path_encoding():
+    """
+    Makes sure the WSGI wrapper has basic functionality.
+    """
+    # Define WSGI app
+    def wsgi_application(environ, start_response):
+        assert environ["SCRIPT_NAME"] == "/中国".encode("utf8").decode("latin-1")
+        assert environ["PATH_INFO"] == "/中文".encode("utf8").decode("latin-1")
+        start_response("200 OK", [])
+        yield b""
+
+    # Wrap it
+    application = WsgiToAsgi(wsgi_application)
+    # Launch it as a test application
+    instance = ApplicationCommunicator(
+        application,
+        {
+            "type": "http",
+            "http_version": "1.0",
+            "method": "GET",
+            "path": "/中文",
+            "root_path": "/中国",
+            "query_string": b"bar=baz",
+            "headers": [],
+        },
+    )
+    await instance.send_input({"type": "http.request"})
+    # Check they send stuff
+    assert (await instance.receive_output(1)) == {
+        "type": "http.response.start",
+        "status": 200,
+        "headers": [],
+    }
+    assert (await instance.receive_output(1)) == {
+        "type": "http.response.body",
+        "body": b"",
+        "more_body": True,
+    }
+    assert (await instance.receive_output(1)) == {"type": "http.response.body"}
+
+
 @pytest.mark.asyncio
 async def test_wsgi_empty_body():
     """
Repository: django/asgiref

Issue:
Has StatelessServer been updated to the ASGI 3.0 spec? 
I'm currently trying to upgrade my app from Channels 2.4.0 to Channels 3.0.0 and I'm having issues with running my worker.

After some investigation, I'm under the impression that the `StatelessServer` provided in `asgiref` hasn't been updated to the new Application specifications in ASGI 3.0.

Part of StatelessServer that is trying to instantiate an application with a scope, then call it using the receive and send arguments:
https://github.com/django/asgiref/blob/5c249e818bd5e7acef957e236535098c3aff7b42/asgiref/server.py#L87-L94

Specification for the new Application format:
https://asgi.readthedocs.io/en/latest/specs/main.html#applications

That is: `coroutine application(scope, receive, send)`

Since the Worker in Channels is based on `StatelessServer`, this is breaking the worker functionality in Channels 3.0.0.
Is this something that is in the works? Anything I can do to help with this?

Comments:

Patch:
diff --git a/asgiref/server.py b/asgiref/server.py
index 9fd2e0c..a83b7bf 100644
--- a/asgiref/server.py
+++ b/asgiref/server.py
@@ -3,6 +3,8 @@ import logging
 import time
 import traceback
 
+from .compatibility import guarantee_single_callable
+
 logger = logging.getLogger(__name__)
 
 
@@ -84,10 +86,11 @@ class StatelessServer:
             self.delete_oldest_application_instance()
         # Make an instance of the application
         input_queue = asyncio.Queue()
-        application_instance = self.application(scope=scope)
+        application_instance = guarantee_single_callable(self.application)
         # Run it, and stash the future for later checking
         future = asyncio.ensure_future(
             application_instance(
+                scope=scope,
                 receive=input_queue.get,
                 send=lambda message: self.application_send(scope, message),
             )


Test patch:
diff --git a/tests/test_server.py b/tests/test_server.py
new file mode 100644
index 0000000..77bbd4d
--- /dev/null
+++ b/tests/test_server.py
@@ -0,0 +1,11 @@
+from asgiref.server import StatelessServer
+
+
+def test_stateless_server():
+    """StatlessServer can be instantiated with an ASGI 3 application."""
+
+    async def app(scope, receive, send):
+        pass
+
+    server = StatelessServer(app)
+    server.get_or_create_application_instance("scope_id", {})
Repository: django/asgiref

Issue:
`sync.async_to_sync` incorrectly warns "a non-async-marked callable" for async callable class instance
Repro

```python
from asgiref.sync import async_to_sync


class CallableClass:
    async def __call__(self):
        return None
        
async_to_sync(CallableClass())
```

Yields the `UserWarning`

```
UserWarning: async_to_sync was passed a non-async-marked callable
```

Though the code works at runtime.

Comments:

Patch:
diff --git a/asgiref/sync.py b/asgiref/sync.py
index a70dac1..d02bd4a 100644
--- a/asgiref/sync.py
+++ b/asgiref/sync.py
@@ -107,7 +107,12 @@ class AsyncToSync:
     loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {}
 
     def __init__(self, awaitable, force_new_loop=False):
-        if not callable(awaitable) or not _iscoroutinefunction_or_partial(awaitable):
+        if not callable(awaitable) or (
+            not _iscoroutinefunction_or_partial(awaitable)
+            and not _iscoroutinefunction_or_partial(
+                getattr(awaitable, "__call__", awaitable)
+            )
+        ):
             # Python does not have very reliable detection of async functions
             # (lots of false negatives) so this is just a warning.
             warnings.warn(


Test patch:
diff --git a/tests/test_sync.py b/tests/test_sync.py
index 2837423..c5677fc 100644
--- a/tests/test_sync.py
+++ b/tests/test_sync.py
@@ -3,6 +3,7 @@ import functools
 import multiprocessing
 import threading
 import time
+import warnings
 from concurrent.futures import ThreadPoolExecutor
 from functools import wraps
 from unittest import TestCase
@@ -365,6 +366,29 @@ def test_async_to_sync_partial():
     assert result["worked"]
 
 
+def test_async_to_sync_on_callable_object():
+    """
+    Tests async_to_sync on a callable class instance
+    """
+
+    result = {}
+
+    class CallableClass:
+        async def __call__(self, value):
+            await asyncio.sleep(0)
+            result["worked"] = True
+            return value
+
+    # Run it (without warnings)
+    with warnings.catch_warnings():
+        warnings.simplefilter("error")
+        sync_function = async_to_sync(CallableClass())
+        out = sync_function(42)
+
+    assert out == 42
+    assert result["worked"] is True
+
+
 def test_async_to_sync_method_self_attribute():
     """
     Tests async_to_sync on a method copies __self__.