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

Issue:
MaxLen annotation validator for custom sequences is incorrect
### Initial Checks

- [X] I confirm that I'm using Pydantic V2

### Description

When using an `annotated_type.MaxLen` annotation with a custom sequence it rejects sequences that have precisely the maximum length when it should only reject if they are greater.

I'm pretty sure this is because [the validator function](https://github.com/pydantic/pydantic/blob/6ef959fa69d1ab1aedf2778b6c8f452e0fee37b6/pydantic/_internal/_validators.py#L266C27-L266C27) used for custom sequences currently checks for strict inequality rather than less or equal.

### Example Code

```Python
from typing import Annotated
from annotated_types import MaxLen

from pydantic import BaseModel

class MySequence(BaseModel):

    inner: list[int]

    def __len__(self):
        return len(self.inner)

    def __getitem__(self, __key: int) -> int:
        return self.inner[__key]


class MyModel(BaseModel):
    seq: Annotated[MySequence, MaxLen(3)]


MyModel.model_validate({"seq": {"inner": [1, 2, 3]}})
```


### Python, Pydantic & OS Version

```Text
pydantic version: 2.0.3
pydantic-core version: 2.3.0 release build profile
python version: 3.11.4 | packaged by Anaconda, Inc. | (main, Jul  5 2023, 13:47:18) [MSC v.1916 64 bit (AMD64)]
platform: Windows-10-10.0.19045-SP0
optional deps. installed: ['typing-extensions'];
```


Selected Assignee: @davidhewitt


Discussion:
Thanks @ImogenBits for reporting this 🙏 

Would you like to open a PR? Otherwise I will fix it.

Resolving patch:
diff --git a/pydantic/_internal/_validators.py b/pydantic/_internal/_validators.py
--- a/pydantic/_internal/_validators.py
+++ b/pydantic/_internal/_validators.py
@@ -263,7 +263,7 @@ def min_length_validator(x: Any, min_length: Any) -> Any:
 
 
 def max_length_validator(x: Any, max_length: Any) -> Any:
-    if not (len(x) < max_length):
+    if len(x) > max_length:
         raise PydanticKnownError(
             'too_long',
             {'field_type': 'Value', 'max_length': max_length, 'actual_length': len(x)},


Test patch:
diff --git a/tests/test_types.py b/tests/test_types.py
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -5423,7 +5423,7 @@ class Model(BaseModel):
         lt=CustomType(-1),
         le=CustomType(0),
         min_length=CustomType([1, 2]),
-        max_length=CustomType([]),
+        max_length=CustomType([1]),
         multiple_of=CustomType(4),
         predicate=CustomType(1),
     )
Repository: pydantic/pydantic

Issue:
Advanced Excludes not working on Field level
### Initial Checks

- [X] I confirm that I'm using Pydantic V2

### Description

I found that the `exclude` parameter in `Field()` appears to only accept bool or None type values. 
According to the [documentation](https://docs.pydantic.dev/2.1/usage/serialization/#model-and-field-level-include-and-exclude) however, advanced exclude statements (like the one demonstrated in the code example) should be possible.

The example below demonstrates a use case that is common in our projects. There is a one-to-many relationship between the parent and child models. In order to avoid infinite recursion when parsing ORM objects with these models, we exclude the back-referencial attributes with an advanced exclude statement. 

This worked fine on V1, but not on V2.  -  Is this expected behavior or a bug? If it's the former, how can I achieve similar behavior?

### Example Code

```Python
from pydantic import BaseModel
from typing import List

class Child(BaseModel):
    name: str
    parent: "Parent" = Field(
        exclude={"children"}
    )

class Parent(BaseModel):
    name: str
    children: List["Child"] = Field(
        exclude={"__all__": {"parent"}}
    )

Child.model_rebuild()
```


### Python, Pydantic & OS Version

```Text
pydantic version: 2.1.1
        pydantic-core version: 2.4.0
          pydantic-core build: profile=release pgo=true mimalloc=true
                 install path: /home/[redacted]/.cache/pypoetry/[redacted]-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.4 (main, Jun  7 2023, 12:45:48) [GCC 11.3.0]
                     platform: Linux-6.2.0-26-generic-x86_64-with-glibc2.35
     optional deps. installed: ['typing-extensions']
```


Selected Assignee: @adriangb


Discussion:
Thanks for reporting, this is a documentation issue. `Field` only accepts a bool. If you want more complex exclusion, either set it in the nested model, or use the `exclude` argument to `model_dump` etc.

Resolving patch:
diff --git a/pydantic/main.py b/pydantic/main.py
--- a/pydantic/main.py
+++ b/pydantic/main.py
@@ -240,7 +240,9 @@ def model_construct(cls: type[Model], _fields_set: set[str] | None = None, **val
         return m
 
     def model_copy(self: Model, *, update: dict[str, Any] | None = None, deep: bool = False) -> Model:
-        """Returns a copy of the model.
+        """Usage docs: https://docs.pydantic.dev/2.2/usage/serialization/#model_copy
+
+        Returns a copy of the model.
 
         Args:
             update: Values to change/add in the new model. Note: the data is not validated


Test patch:
Repository: pydantic/pydantic

Issue:
Documentation showing use of deprecated conlist function
### Initial Checks

- [X] I confirm that I'm using Pydantic V2

### Description

Documentation cites the use of conlist https://docs.pydantic.dev/dev/api/types/#pydantic.types.conlist

This function has however been deprecated, referencing an open github issue in the exception.


### Example Code

```Python
from pydantic import BaseModel, conlist

class Foo(BaseModel):
    bar: conlist(str, unique_items=True)
```


### Python, Pydantic & OS Version
```
python -c "import pydantic.version; print(pydantic.version.version_info())"
             pydantic version: 2.4.2
        pydantic-core version: 2.10.1
          pydantic-core build: profile=release pgo=true
               python version: 3.11.2 (main, Feb 22 2023, 16:37:15) [GCC 11.3.0]
                     platform: Linux-6.2.0-36-generic-x86_64-with-glibc2.35
             related packages: pydantic-settings-2.0.3 typing_extensions-4.8.0 fastapi-0.104.0
```


Discussion:
Hi @calswbin,

Thanks for catching this. I'll make an update to the docs today 👍. We appreciate the report :).
My pleasure :) thanks for the speedy response!
Hey @calswbin,

Taking a closer look at this, it looks like the `unique_items` field has been deprecated, but not the `conlist` type. I'll add a deprecation warning for that field specifically in the docs.

Resolving patch:
diff --git a/pydantic/types.py b/pydantic/types.py
--- a/pydantic/types.py
+++ b/pydantic/types.py
@@ -843,6 +843,9 @@ def conlist(
         min_length: The minimum length of the list. Defaults to None.
         max_length: The maximum length of the list. Defaults to None.
         unique_items: Whether the items in the list must be unique. Defaults to None.
+            !!! warning Deprecated
+                The `unique_items` parameter is deprecated, use `Set` instead.
+                See [this issue](https://github.com/pydantic/pydantic-core/issues/296) for more details.
 
     Returns:
         The wrapped list type.


Test patch:
Repository: pydantic/pydantic

Issue:
`CallableDiscriminator` isn't in the docs -- note in release notes (it's `Discriminator`)
### Initial Checks

- [X] I have searched Google & GitHub for similar requests and couldn't find anything
- [X] I have read and followed [the docs](https://docs.pydantic.dev) and still think this feature is missing

### Description

It's a trap!

The release notes for 2.5.0 say `CallableDiscriminator`, but the class was renamed to `Discriminator` before release - so searching the docs for "CallableDiscriminator" doesn't find it.

Maybe worth a note in the line of the release notes to indicate it is now called `Discriminator` to direct users to this cool new feature.

### Affected Components

- [ ] [Compatibility between releases](https://docs.pydantic.dev/changelog/)
- [ ] [Data validation/parsing](https://docs.pydantic.dev/concepts/models/#basic-model-usage)
- [ ] [Data serialization](https://docs.pydantic.dev/concepts/serialization/) - `.model_dump()` and `.model_dump_json()`
- [ ] [JSON Schema](https://docs.pydantic.dev/concepts/json_schema/)
- [ ] [Dataclasses](https://docs.pydantic.dev/concepts/dataclasses/)
- [ ] [Model Config](https://docs.pydantic.dev/concepts/config/)
- [ ] [Field Types](https://docs.pydantic.dev/api/types/) - adding or changing a particular data type
- [ ] [Function validation decorator](https://docs.pydantic.dev/concepts/validation_decorator/)
- [ ] [Generic Models](https://docs.pydantic.dev/concepts/models/#generic-models)
- [ ] [Other Model behaviour](https://docs.pydantic.dev/concepts/models/) - `model_construct()`, pickling, private attributes, ORM mode
- [ ] [Plugins](https://docs.pydantic.dev/) and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.


Discussion:
Hi @psychedelicious,

Thanks for bringing this up. I'll have a fix up for this tomorrow!

Resolving patch:
diff --git a/pydantic/_internal/_validate_call.py b/pydantic/_internal/_validate_call.py
--- a/pydantic/_internal/_validate_call.py
+++ b/pydantic/_internal/_validate_call.py
@@ -145,5 +145,12 @@ def __set_name__(self, owner: Any, name: str) -> None:
     def __repr__(self) -> str:
         return f'ValidateCallWrapper({self.raw_function})'
 
-    def __eq__(self, other):
-        return self.raw_function == other.raw_function
+    def __eq__(self, other) -> bool:
+        return (
+            (self.raw_function == other.raw_function)
+            and (self._config == other._config)
+            and (self._validate_return == other._validate_return)
+        )
+
+    def __hash__(self):
+        return hash(self.raw_function)


Test patch:
Repository: pydantic/pydantic

Issue:
`BaseModel` in JSON Schema is really ugly
```py
from pydantic import BaseModel


class MyModel(BaseModel):
    x: BaseModel

print(MyModel.model_json_schema())
```

Shows the full docstring for `BaseModel` in the JSON Schema, I think we should specifically omit the description here


Discussion:

Resolving patch:
diff --git a/pydantic/_internal/_generate_schema.py b/pydantic/_internal/_generate_schema.py
--- a/pydantic/_internal/_generate_schema.py
+++ b/pydantic/_internal/_generate_schema.py
@@ -212,6 +212,8 @@ def modify_model_json_schema(
     Returns:
         JsonSchemaValue: The updated JSON schema.
     """
+    from ..main import BaseModel
+
     json_schema = handler(schema_or_field)
     original_schema = handler.resolve_ref_schema(json_schema)
     # Preserve the fact that definitions schemas should never have sibling keys:
@@ -221,7 +223,8 @@ def modify_model_json_schema(
         original_schema['allOf'] = [{'$ref': ref}]
     if 'title' not in original_schema:
         original_schema['title'] = cls.__name__
-    docstring = cls.__doc__
+    # BaseModel; don't use cls.__doc__ as it will contain the verbose class signature by default
+    docstring = None if cls is BaseModel else cls.__doc__
     if docstring and 'description' not in original_schema:
         original_schema['description'] = inspect.cleandoc(docstring)
     return json_schema


Test patch:
diff --git a/tests/test_json_schema.py b/tests/test_json_schema.py
--- a/tests/test_json_schema.py
+++ b/tests/test_json_schema.py
@@ -5812,3 +5812,10 @@ class OuterModel(pydantic.BaseModel):
 
     with pytest.raises(ValidationError):
         OuterModel(x=2, y=-1, z=-1)
+
+
+def test_description_not_included_for_basemodel() -> None:
+    class Model(BaseModel):
+        x: BaseModel
+
+    assert 'description' not in Model.model_json_schema()['$defs']['BaseModel']
Repository: pydantic/pydantic

Issue:
`frozen` description equates it to `allow_mutation`, but it is the inverse
### Initial Checks

- [X] I confirm that I'm using Pydantic V2

### Description

Thanks for the awesome library! I recently migrated to v2 and am loving it. I did notice a very minor, though potentially important issue in the description of `frozen` config argument:

https://github.com/pydantic/pydantic/blob/c067c1b9d0e5ffdf5b0fd53bf0e138cb5924f750/pydantic/config.py#L128

Though the names are clear, one could potentially assume that they are equivalent based on this description. The docs clearly indicate that `frozen` is the invers of `allow_mutation`, perhaps could also indicate that on this line as well.

Something like "On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default."

Let me know what you think, and then I can open a PR.

### Example Code

_No response_

### Python, Pydantic & OS Version

```Text
pydantic version: 2.5.3
        pydantic-core version: 2.14.6
          pydantic-core build: profile=release pgo=true
               python version: 3.12.0 (main, Nov 29 2023, 03:32:06) [GCC 10.2.1 20210110]
                     platform: Linux-5.15.133.1-microsoft-standard-WSL2-x86_64-with-glibc2.31
             related packages: typing_extensions-4.9.0
```



Discussion:
@themattmorris,

Sounds like a great change. Please open a PR and I'd be happy to review!

Resolving patch:
diff --git a/pydantic/config.py b/pydantic/config.py
--- a/pydantic/config.py
+++ b/pydantic/config.py
@@ -125,7 +125,7 @@ class User(BaseModel):
     attributes are hashable. Defaults to `False`.
 
     Note:
-        On V1, this setting was called `allow_mutation`, and was `True` by default.
+        On V1, the inverse of this setting was called `allow_mutation`, and was `True` by default.
     """
 
     populate_by_name: bool


Test patch:
Repository: pydantic/pydantic

Issue:
Clarify documentation of strip_whitespace
### Initial Checks

- [X] I confirm that I'm using Pydantic V2

### Description

The doc for `StringConstraints` `strip_whitespace` says "Whether to strip whitespace from the string." - to me that's unclear if it's stripping all whitespace or only leading/trailing (it's the latter I think).

I think it'd be clearer if it said "Whether to remove leading and trailing whitespace." which I think is the actual behaviour, and aligns with the doc for constr - https://docs.pydantic.dev/latest/api/types/#pydantic.types.constr

https://docs.pydantic.dev/latest/api/types/#pydantic.types.StringConstraints

Maybe this unit test should be updated to include a space inside of ABC to assert on that behaviour? https://github.com/pydantic/pydantic/commit/8bc104f47e52719b157d1be30b4635a5038cb3d1#diff-bd467a363c9f155a2e6a7716aeca0c351089135a53d09a66138cea4f16506ebdR5574

### Example Code

_No response_

### Python, Pydantic & OS Version

```Text
pydantic version: 2.7.0
        pydantic-core version: 2.18.1
          pydantic-core build: profile=release pgo=true
                 install path: /home/johnc/.cache/pypoetry/virtualenvs/gweb-play-points-perks-apac-DXkUH1xo-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.4 (main, Feb 21 2024, 14:32:06) [GCC 11.4.0]
                     platform: Linux-6.5.0-28-generic-x86_64-with-glibc2.35
             related packages: typing_extensions-4.11.0
                       commit: unknown
```



Discussion:
@johncarter-phntm,

Feel free to open a PR with these changes - that sounds great!
@sydney-runkle I'll be happy to take this one

Resolving patch:
diff --git a/pydantic/types.py b/pydantic/types.py
--- a/pydantic/types.py
+++ b/pydantic/types.py
@@ -682,7 +682,7 @@ class StringConstraints(annotated_types.GroupedMetadata):
     Apply constraints to `str` types.
 
     Attributes:
-        strip_whitespace: Whether to strip whitespace from the string.
+        strip_whitespace: Whether to remove leading and trailing whitespace.
         to_upper: Whether to convert the string to uppercase.
         to_lower: Whether to convert the string to lowercase.
         strict: Whether to validate the string in strict mode.


Test patch:
diff --git a/tests/test_types.py b/tests/test_types.py
--- a/tests/test_types.py
+++ b/tests/test_types.py
@@ -1278,6 +1278,8 @@ def __bool__(self) -> bool:
         ('bool_check', BoolCastable(), ValidationError),
         ('str_check', 's', 's'),
         ('str_check', '  s  ', 's'),
+        ('str_check', ' leading', 'leading'),
+        ('str_check', 'trailing ', 'trailing'),
         ('str_check', b's', 's'),
         ('str_check', b'  s  ', 's'),
         ('str_check', bytearray(b's' * 5), 'sssss'),
Repository: armada-ths/ais

Issue:
Disable debug in production
https://app.asana.com/0/1204005227675382/1204038385197069/f

Currently the Django debug flag is true in the production environment, leading to security issues.


Discussion:

Resolving patch:
diff --git a/ais/common/settings.py b/ais/common/settings.py
--- a/ais/common/settings.py
+++ b/ais/common/settings.py
@@ -18,6 +18,7 @@
 CRISPY_TEMPLATE_PACK = 'bootstrap3'
 
 INSTALLED_APPS = (
+    'whitenoise.runserver_nostatic',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
@@ -55,6 +56,8 @@
 
 MIDDLEWARE = [
     'corsheaders.middleware.CorsMiddleware',
+    "django.middleware.security.SecurityMiddleware",
+    "whitenoise.middleware.WhiteNoiseMiddleware",
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
diff --git a/ais/production/settings.py b/ais/production/settings.py
--- a/ais/production/settings.py
+++ b/ais/production/settings.py
@@ -12,7 +12,7 @@
 # to point to AIS (which would be a security concern).
 ALLOWED_HOSTS = ['.armada.nu', 'localhost', 'armada.nu']
 
-DEBUG = True
+DEBUG = False
 
 # The URL scheme is slightly different in a production environment
 # since we need to accomodate the KTH OpenID Connect integration.


Test patch:
Repository: cookiecutter/cookiecutter-django

Issue:
Checking if database is set fails
This check will never be True, since it returns a value object and not a dict.

``` Python
    DATABASES = values.DatabaseURLValue()
    if DATABASES == {'default': {}}:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': "awesome-list",
            }
        }
```



Discussion:

Resolving patch:
diff --git a/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py b/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py
--- a/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py
+++ b/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py
@@ -113,15 +113,7 @@ class Common(Configuration):
 
     ########## DATABASE CONFIGURATION
     # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
-
-    DATABASES = values.DatabaseURLValue()
-    if DATABASES == {'default': {}}:
-        DATABASES = {
-            'default': {
-                'ENGINE': 'django.db.backends.postgresql_psycopg2',
-                'NAME': "{{cookiecutter.repo_name}}",
-            }
-        }
+    DATABASES = values.DatabaseURLValue('postgres://localhost/{{cookiecutter.repo_name}}')
     ########## END DATABASE CONFIGURATION
 
     ########## CACHING


Test patch:
Repository: cookiecutter/cookiecutter-django

Issue:
STATIC_ROOT should be absolute path
According to the [Django docs](https://docs.djangoproject.com/en/dev/ref/settings/#static-root), `STATIC_ROOT` should be an absolute path. So I propose to store the static files (collectstatic) in a level up from the BASE_DIR.



Discussion:
I could be wrong but I think I just fixed this in 26b2e9ce6a76a8359b4ca13d8a33fc041ec431a1

No, I think you need to apply Bouke's patch and undo `26b2e9c`. If you do that,
here's what you get:

```
|-- repo_name/
    |-- CONTRIBUTORS.txt
    |-- LICENSE.rst
    |-- Procfile
    |-- README.rst
    |-- repo_name/        <== BASE_DIR.
    |   |-- config/
    |   |-- manage.py
    |   |-- static/       <== STATICFILES_DIRS. collectstatic looks here.
    |   |-- templates/
    |   `-- users/
    |-- docs/
    |-- requirements/
    |-- requirements.txt
    `-- staticfiles/      <== STATIC_ROOT. Serve static files from here.
```

#### Bouke patch
- STATIC_ROOT is at the same level as BASE_DIR, not in the BASE_DIR.
- STATIC_ROOT is set as an absolute path.

#### Undo `26b2e9c`
- The `26b2e9c` commit results in `OSError: No such file or directory` 
  when you run collectstatic, because collectstatic is looking in 
  `BASE_DIR/../static`, but that directory doesn't exist.
- After reverting, collectstatic will look in `BASE_DIR/static`, as it should.

Also, note that the nesting of the settings file in config/ doesn't matter, since the paths in settings.py are computed using BASE_DIR.


Resolving patch:
diff --git a/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py b/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py
--- a/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py
+++ b/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/config/settings.py
@@ -183,14 +183,14 @@ class Common(Configuration):
 
     ########## STATIC FILE CONFIGURATION
     # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
-    STATIC_ROOT = 'staticfiles'
+    STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles')
 
     # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
     STATIC_URL = '/static/'
 
     # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
     STATICFILES_DIRS = (
-        join(BASE_DIR, '..', 'static'),
+        join(BASE_DIR, 'static'),
     )
 
     # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders


Test patch:
Repository: cookiecutter/cookiecutter-django

Issue:
Error pages need an exception parameter on django 1.9
The test exception pages are no longer working on django 1.9.

Affected pages:
- 400
- 403
- 404

Traceback (404):

```
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python3.5/contextlib.py" in inner
  30.                 return func(*args, **kwds)

File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

Exception Type: TypeError at /404/
Exception Value: page_not_found() missing 1 required positional argument: 'exception'
```



Discussion:

Resolving patch:
diff --git a/{{cookiecutter.repo_name}}/config/urls.py b/{{cookiecutter.repo_name}}/config/urls.py
--- a/{{cookiecutter.repo_name}}/config/urls.py
+++ b/{{cookiecutter.repo_name}}/config/urls.py
@@ -28,8 +28,8 @@
     # This allows the error pages to be debugged during development, just visit
     # these url in browser to see how these error pages look like.
     urlpatterns += [
-        url(r'^400/$', default_views.bad_request),
-        url(r'^403/$', default_views.permission_denied),
-        url(r'^404/$', default_views.page_not_found),
+        url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception("Bad Request!")}),
+        url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception("Permissin Denied")}),
+        url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception("Page not Found")}),
         url(r'^500/$', default_views.server_error),
     ]


Test patch: