mteb/SWEbenchLiteRR huggingface dataset:
shell command crashes when passing (with -c) the python code with functions.
Description
	
The examples below use Python 3.7 and Django 2.2.16, but I checked that the code is the same on master and works the same in Python 3.8.
Here's how ​python -c works:
$ python -c <<EOF " 
import django
def f():
		print(django.__version__)
f()"
EOF
2.2.16
Here's how ​python -m django shell -c works (paths shortened for clarify):
$ python -m django shell -c <<EOF "
import django
def f():
		print(django.__version__)
f()"
EOF
Traceback (most recent call last):
 File "{sys.base_prefix}/lib/python3.7/runpy.py", line 193, in _run_module_as_main
	"__main__", mod_spec)
 File "{sys.base_prefix}/lib/python3.7/runpy.py", line 85, in _run_code
	exec(code, run_globals)
 File "{sys.prefix}/lib/python3.7/site-packages/django/__main__.py", line 9, in <module>
	management.execute_from_command_line()
 File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
	utility.execute()
 File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
	self.fetch_command(subcommand).run_from_argv(self.argv)
 File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
	self.execute(*args, **cmd_options)
 File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
	output = self.handle(*args, **options)
 File "{sys.prefix}/lib/python3.7/site-packages/django/core/management/commands/shell.py", line 86, in handle
	exec(options['command'])
 File "<string>", line 5, in <module>
 File "<string>", line 4, in f
NameError: name 'django' is not defined
The problem is in the ​usage of ​exec:
	def handle(self, **options):
		# Execute the command and exit.
		if options['command']:
			exec(options['command'])
			return
		# Execute stdin if it has anything to read and exit.
		# Not supported on Windows due to select.select() limitations.
		if sys.platform != 'win32' and not sys.stdin.isatty() and select.select([sys.stdin], [], [], 0)[0]:
			exec(sys.stdin.read())
			return
exec should be passed a dictionary containing a minimal set of globals. This can be done by just passing a new, empty dictionary as the second argument of exec.
QuerySet.only() doesn't work with select_related() on a reverse OneToOneField relation.
Description
	
On Django 4.2 calling only() with select_related() on a query using the reverse lookup for a OneToOne relation does not generate the correct query.
All the fields from the related model are still included in the generated SQL.
Sample models:
class Main(models.Model):
	main_field_1 = models.CharField(blank=True, max_length=45)
	main_field_2 = models.CharField(blank=True, max_length=45)
	main_field_3 = models.CharField(blank=True, max_length=45)
class Secondary(models.Model):
	main = models.OneToOneField(Main, primary_key=True, related_name='secondary', on_delete=models.CASCADE)
	secondary_field_1 = models.CharField(blank=True, max_length=45)
	secondary_field_2 = models.CharField(blank=True, max_length=45)
	secondary_field_3 = models.CharField(blank=True, max_length=45)
Sample code:
Main.objects.select_related('secondary').only('main_field_1', 'secondary__secondary_field_1')
Generated query on Django 4.2.1:
SELECT "bugtest_main"."id", "bugtest_main"."main_field_1", "bugtest_secondary"."main_id", "bugtest_secondary"."secondary_field_1", "bugtest_secondary"."secondary_field_2", "bugtest_secondary"."secondary_field_3" FROM "bugtest_main" LEFT OUTER JOIN "bugtest_secondary" ON ("bugtest_main"."id" = "bugtest_secondary"."main_id")
Generated query on Django 4.1.9:
SELECT "bugtest_main"."id", "bugtest_main"."main_field_1", "bugtest_secondary"."main_id", "bugtest_secondary"."secondary_field_1" FROM "bugtest_main" LEFT OUTER JOIN "bugtest_secondary" ON ("bugtest_main"."id" = "bugtest_secondary"."main_id")
Traceback printed for unrecognized option
### Bug description

A traceback is printed when an unrecognized option is passed to pylint.

### Configuration

_No response_

### Command used

```shell
pylint -Q
```


### Pylint output

```shell
************* Module Command line
Command line:1:0: E0015: Unrecognized option found: Q (unrecognized-option)
Traceback (most recent call last):
  File "/Users/markbyrne/venv310/bin/pylint", line 33, in <module>
    sys.exit(load_entry_point('pylint', 'console_scripts', 'pylint')())
  File "/Users/markbyrne/programming/pylint/pylint/__init__.py", line 24, in run_pylint
    PylintRun(argv or sys.argv[1:])
  File "/Users/markbyrne/programming/pylint/pylint/lint/run.py", line 135, in __init__
    args = _config_initialization(
  File "/Users/markbyrne/programming/pylint/pylint/config/config_initialization.py", line 85, in _config_initialization
    raise _UnrecognizedOptionError(options=unrecognized_options)
pylint.config.exceptions._UnrecognizedOptionError
```


### Expected behavior

The top part of the current output is handy:
`Command line:1:0: E0015: Unrecognized option found: Q (unrecognized-option)`

The traceback I don't think is expected & not user-friendly.
A usage tip, for example:
```python
mypy -Q
usage: mypy [-h] [-v] [-V] [more options; see below]
            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]
mypy: error: unrecognized arguments: -Q
```

### Pylint version

```shell
pylint 2.14.0-dev0
astroid 2.11.3
Python 3.10.0b2 (v3.10.0b2:317314165a, May 31 2021, 10:02:22) [Clang 12.0.5 (clang-1205.0.22.9)]
```


### OS / Environment

_No response_

### Additional dependencies

_No response_
warn_on_dtype with DataFrame
#### Description

``warn_on_dtype`` has no effect when input is a pandas ``DataFrame``

#### Steps/Code to Reproduce
```python
from sklearn.utils.validation import check_array
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [2, 3, 4]], dtype=object)
checked = check_array(df, warn_on_dtype=True)
```

#### Expected result: 

```python-traceback
DataConversionWarning: Data with input dtype object was converted to float64.
```

#### Actual Results
No warning is thrown

#### Versions
Linux-4.4.0-116-generic-x86_64-with-debian-stretch-sid
Python 3.6.3 |Anaconda, Inc.| (default, Nov  3 2017, 19:19:16) 
[GCC 7.2.0]
NumPy 1.13.1
SciPy 0.19.1
Scikit-Learn 0.20.dev0
Pandas 0.21.0

warn_on_dtype with DataFrame
#### Description

``warn_on_dtype`` has no effect when input is a pandas ``DataFrame``

#### Steps/Code to Reproduce
```python
from sklearn.utils.validation import check_array
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [2, 3, 4]], dtype=object)
checked = check_array(df, warn_on_dtype=True)
```

#### Expected result: 

```python-traceback
DataConversionWarning: Data with input dtype object was converted to float64.
```

#### Actual Results
No warning is thrown

#### Versions
Linux-4.4.0-116-generic-x86_64-with-debian-stretch-sid
Python 3.6.3 |Anaconda, Inc.| (default, Nov  3 2017, 19:19:16) 
[GCC 7.2.0]
NumPy 1.13.1
SciPy 0.19.1
Scikit-Learn 0.20.dev0
Pandas 0.21.0
autosummary: The members variable for module template contains imported members
**Describe the bug**
autosummary: The members variable for module template contains imported members even if autosummary_imported_members is False.

**To Reproduce**

```
# _templates/autosummary/module.rst
{{ fullname | escape | underline }}

.. automodule:: {{ fullname }}

   .. autosummary::
   {% for item in members %}
      {{ item }}
   {%- endfor %}

```
```
# example.py
import os
```
```
# index.rst
.. autosummary::
   :toctree: generated

   example
```
```
# conf.py
autosummary_generate = True
autosummary_imported_members = False
```

As a result, I got following output:
```
# generated/example.rst
example
=======

.. automodule:: example

   .. autosummary::

      __builtins__
      __cached__
      __doc__
      __file__
      __loader__
      __name__
      __package__
      __spec__
      os
```

**Expected behavior**
The template variable `members` should not contain imported members when `autosummary_imported_members` is False.

**Your project**
No

**Screenshots**
No

**Environment info**
- OS: Mac
- Python version: 3.8.2
- Sphinx version: 3.1.0dev
- Sphinx extensions:  sphinx.ext.autosummary
- Extra tools: No

**Additional context**
No
Inconsistent behavior for sympify/simplify with ceiling
In sympy v1.5.1:
```python
In [16]: sympy.sympify('4*ceiling(x/4 - 3/4)', evaluate=False).simplify()
Out[16]: 4*ceiling(x/4 - 3/4)

In [17]: sympy.sympify('4*ceiling(x/4 - 3/4)', evaluate=True).simplify()
Out[17]: 4*ceiling(x/4 - 3/4)
```

In sympy v.1.6.2:
```python
In [16]: sympy.sympify('4*ceiling(x/4 - 3/4)', evaluate=False).simplify()
Out[16]: 4*ceiling(x/4) - 3

In [17]: sympy.sympify('4*ceiling(x/4 - 3/4)', evaluate=True).simplify()
Out [17]: 4*ceiling(x/4 - 3/4)
```

Is there a way to ensure that the behavior is consistent, even though evaluate is equal to `False` when parsing?
Issue when passing empty lists/arrays to WCS transformations
The following should not fail but instead should return empty lists/arrays:

```
In [1]: from astropy.wcs import WCS

In [2]: wcs = WCS('2MASS_h.fits')

In [3]: wcs.wcs_pix2world([], [], 0)
---------------------------------------------------------------------------
InconsistentAxisTypesError                Traceback (most recent call last)
<ipython-input-3-e2cc0e97941a> in <module>()
----> 1 wcs.wcs_pix2world([], [], 0)

~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in wcs_pix2world(self, *args, **kwargs)
   1352         return self._array_converter(
   1353             lambda xy, o: self.wcs.p2s(xy, o)['world'],
-> 1354             'output', *args, **kwargs)
   1355     wcs_pix2world.__doc__ = """
   1356         Transforms pixel coordinates to world coordinates by doing

~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in _array_converter(self, func, sky, ra_dec_order, *args)
   1267                     "a 1-D array for each axis, followed by an origin.")
   1268 
-> 1269             return _return_list_of_arrays(axes, origin)
   1270 
   1271         raise TypeError(

~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in _return_list_of_arrays(axes, origin)
   1223             if ra_dec_order and sky == 'input':
   1224                 xy = self._denormalize_sky(xy)
-> 1225             output = func(xy, origin)
   1226             if ra_dec_order and sky == 'output':
   1227                 output = self._normalize_sky(output)

~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in <lambda>(xy, o)
   1351             raise ValueError("No basic WCS settings were created.")
   1352         return self._array_converter(
-> 1353             lambda xy, o: self.wcs.p2s(xy, o)['world'],
   1354             'output', *args, **kwargs)
   1355     wcs_pix2world.__doc__ = """

InconsistentAxisTypesError: ERROR 4 in wcsp2s() at line 2646 of file cextern/wcslib/C/wcs.c:
ncoord and/or nelem inconsistent with the wcsprm.
```
Some issues with idiff
idiff doesn't support Eq, and it also doesn't support f(x) instead of y. Both should be easy to correct.

```
>>> idiff(Eq(y*exp(y), x*exp(x)), y, x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./sympy/geometry/util.py", line 582, in idiff
    yp = solve(eq.diff(x), dydx)[0].subs(derivs)
IndexError: list index out of range
>>> idiff(f(x)*exp(f(x)) - x*exp(x), f(x), x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./sympy/geometry/util.py", line 574, in idiff
    raise ValueError("expecting x-dependent symbol(s) but got: %s" % y)
ValueError: expecting x-dependent symbol(s) but got: f(x)
>>> idiff(y*exp(y)- x*exp(x), y, x)
(x + 1)*exp(x - y)/(y + 1)
```
Differences among the results of KernelPCA with rbf kernel
Hi there,
I met with a problem:

#### Description
When I run KernelPCA for dimension reduction for the same datasets, the results are different in signs.

#### Steps/Code to Reproduce
Just to reduce the dimension to 7 with rbf kernel:
pca = KernelPCA(n_components=7, kernel='rbf', copy_X=False, n_jobs=-1)
pca.fit_transform(X)

#### Expected Results
The same result.

#### Actual Results
The results are the same except for their signs:(
[[-0.44457617 -0.18155886 -0.10873474  0.13548386 -0.1437174  -0.057469	0.18124364]] 

[[ 0.44457617  0.18155886  0.10873474 -0.13548386 -0.1437174  -0.057469 -0.18124364]] 

[[-0.44457617 -0.18155886  0.10873474  0.13548386  0.1437174   0.057469  0.18124364]] 

#### Versions
0.18.1
URLField throws ValueError instead of ValidationError on clean
Description
	
forms.URLField( ).clean('////]@N.AN')
results in:
	ValueError: Invalid IPv6 URL
	Traceback (most recent call last):
	 File "basic_fuzzer.py", line 22, in TestOneInput
	 File "fuzzers.py", line 350, in test_forms_URLField
	 File "django/forms/fields.py", line 151, in clean
	 File "django/forms/fields.py", line 136, in run_validators
	 File "django/core/validators.py", line 130, in __call__
	 File "urllib/parse.py", line 440, in urlsplit
`TransactionTestCase.serialized_rollback` fails to restore objects due to ordering constraints
Description
	
I hit this problem in a fairly complex projet and haven't had the time to write a minimal reproduction case. I think it can be understood just by inspecting the code so I'm going to describe it while I have it in mind.
Setting serialized_rollback = True on a TransactionTestCase triggers ​rollback emulation. In practice, for each database:
BaseDatabaseCreation.create_test_db calls connection._test_serialized_contents = connection.creation.serialize_db_to_string()
TransactionTestCase._fixture_setup calls connection.creation.deserialize_db_from_string(connection._test_serialized_contents)
(The actual code isn't written that way; it's equivalent but the symmetry is less visible.)
serialize_db_to_string orders models with serializers.sort_dependencies and serializes them. The sorting algorithm only deals with natural keys. It doesn't do anything to order models referenced by foreign keys before models containing said foreign keys. That wouldn't be possible in general because circular foreign keys are allowed.
deserialize_db_from_string deserializes and saves models without wrapping in a transaction. This can result in integrity errors if an instance containing a foreign key is saved before the instance it references. I'm suggesting to fix it as follows:
diff --git a/django/db/backends/base/creation.py b/django/db/backends/base/creation.py
index bca8376..7bed2be 100644
--- a/django/db/backends/base/creation.py
+++ b/django/db/backends/base/creation.py
@@ -4,7 +4,7 @@ import time
 from django.apps import apps
 from django.conf import settings
 from django.core import serializers
-from django.db import router
+from django.db import router, transaction
 from django.utils.six import StringIO
 from django.utils.six.moves import input
 
@@ -128,8 +128,9 @@ class BaseDatabaseCreation(object):
		 the serialize_db_to_string method.
		 """
		 data = StringIO(data)
-		for obj in serializers.deserialize("json", data, using=self.connection.alias):
-			obj.save()
+		with transaction.atomic(using=self.connection.alias):
+			for obj in serializers.deserialize("json", data, using=self.connection.alias):
+				obj.save()
 
	 def _get_database_display_str(self, verbosity, database_name):
		 """
Note that loaddata doesn't have this problem because it wraps everything in a transaction:
	def handle(self, *fixture_labels, **options):
		# ...
		with transaction.atomic(using=self.using):
			self.loaddata(fixture_labels)
		# ...
This suggest that the transaction was just forgotten in the implementation of deserialize_db_from_string.
It should be possible to write a deterministic test for this bug because the order in which serialize_db_to_string serializes models depends on the app registry, and the app registry uses OrderedDict to store apps and models in a deterministic order.
Incorrect removal of order_by clause created as multiline RawSQL
Description
	
Hi.
The SQLCompiler is ripping off one of my "order by" clause, because he "thinks" the clause was already "seen" (in SQLCompiler.get_order_by()). I'm using expressions written as multiline RawSQLs, which are similar but not the same. 
The bug is located in SQLCompiler.get_order_by(), somewhere around line computing part of SQL query without ordering:
without_ordering = self.ordering_parts.search(sql).group(1)
The sql variable contains multiline sql. As a result, the self.ordering_parts regular expression is returning just a line containing ASC or DESC words. This line is added to seen set, and because my raw queries have identical last lines, only the first clasue is returing from SQLCompiler.get_order_by().
As a quick/temporal fix I can suggest making sql variable clean of newline characters, like this:
sql_oneline = ' '.join(sql.split('\n'))
without_ordering = self.ordering_parts.search(sql_oneline).group(1)
Note: beware of unicode (Py2.x u'') and EOL dragons (\r).
Example of my query:
	return MyModel.objects.all().order_by(
		RawSQL('''
			case when status in ('accepted', 'verification')
				 then 2 else 1 end''', []).desc(),
		RawSQL('''
			case when status in ('accepted', 'verification')
				 then (accepted_datetime, preferred_datetime)
				 else null end''', []).asc(),
		RawSQL('''
			case when status not in ('accepted', 'verification')
				 then (accepted_datetime, preferred_datetime, created_at)
				 else null end''', []).desc())
The ordering_parts.search is returing accordingly:
'				 then 2 else 1 end)'
'				 else null end'
'				 else null end'
Second RawSQL with a				 else null end part is removed from query.
The fun thing is that the issue can be solved by workaround by adding a space or any other char to the last line. 
So in case of RawSQL I can just say, that current implementation of avoiding duplicates in order by clause works only for special/rare cases (or does not work in all cases). 
The bug filed here is about wrong identification of duplicates (because it compares only last line of SQL passed to order by clause).
Hope my notes will help you fixing the issue. Sorry for my english.
is_upper() raises IndexError for tall matrices
The function Matrix.is_upper raises an IndexError for a 4x2 matrix of zeros.
```
>>> sympy.zeros(4,2).is_upper
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sympy/matrices/matrices.py", line 1112, in is_upper
    for i in range(1, self.rows)
  File "sympy/matrices/matrices.py", line 1113, in <genexpr>
    for j in range(i))
  File "sympy/matrices/dense.py", line 119, in __getitem__
    return self.extract(i, j)
  File "sympy/matrices/matrices.py", line 352, in extract
    colsList = [a2idx(k, self.cols) for k in colsList]
  File "sympy/matrices/matrices.py", line 5261, in a2idx
    raise IndexError("Index out of range: a[%s]" % (j,))
IndexError: Index out of range: a[2]
```
The code for is_upper() is
```
        return all(self[i, j].is_zero
                   for i in range(1, self.rows)
                   for j in range(i))
```
For a 4x2 matrix, is_upper iterates over the indices:
```
>>> A = sympy.zeros(4, 2)
>>> print tuple([i, j] for i in range(1, A.rows) for j in range(i))
([1, 0], [2, 0], [2, 1], [3, 0], [3, 1], [3, 2])
```
The attempt to index the (3,2) entry appears to be the source of the error.
OneHotEncoder ignore unknown error when categories are strings 
#### Description

This bug is very specific, but it happens when you set OneHotEncoder to ignore unknown entries.
and your labels are strings. The memory of the arrays is not handled safely and it can lead to a ValueError

Basically, when you call the transform method it will sets all the unknown strings on your array to OneHotEncoder.categories_[i][0] which is the first category alphabetically sorted given for fit
If this OneHotEncoder.categories_[i][0] is a long string, and the array that you want to transform has small strings, then it is impossible to fit the whole  OneHotEncoder.categories_[i][0] into the entries of the array we want to transform. So  OneHotEncoder.categories_[i][0]  is truncated and this raise the ValueError.



#### Steps/Code to Reproduce
```

import numpy as np
from sklearn.preprocessing import OneHotEncoder


# It needs to be numpy arrays, the error does not appear 
# is you have lists of lists because it gets treated like an array of objects.
train  = np.array([ '22','333','4444','11111111' ]).reshape((-1,1))
test   = np.array([ '55555',  '22' ]).reshape((-1,1))

ohe = OneHotEncoder(dtype=bool,handle_unknown='ignore')

ohe.fit( train )
enc_test = ohe.transform( test )

```


#### Expected Results
Here we should get an sparse matrix 2x4 false everywhere except at (1,1) the '22' that is known

#### Actual Results

> ValueError: y contains previously unseen labels: ['111111']


#### Versions
System:
    python: 2.7.12 (default, Dec  4 2017, 14:50:18)  [GCC 5.4.0 20160609]
   machine: Linux-4.4.0-138-generic-x86_64-with-Ubuntu-16.04-xenial
executable: /usr/bin/python

BLAS:
    macros: HAVE_CBLAS=None
cblas_libs: openblas, openblas
  lib_dirs: /usr/lib

Python deps:
    Cython: 0.25.2
     scipy: 0.18.1
setuptools: 36.7.0
       pip: 9.0.1
     numpy: 1.15.2
    pandas: 0.19.1
   sklearn: 0.21.dev0



#### Comments

I already implemented a fix for this issue, where I check the size of the elements in the array before, and I cast them into objects if necessary.
Sympy incorrectly attempts to eval reprs in its __eq__ method
Passing strings produced by unknown objects into eval is **very bad**. It is especially surprising for an equality check to trigger that kind of behavior. This should be fixed ASAP.

Repro code:

```
import sympy
class C:
    def __repr__(self):
        return 'x.y'
_ = sympy.Symbol('x') == C()
```

Results in:

```
E   AttributeError: 'Symbol' object has no attribute 'y'
```

On the line:

```
    expr = eval(
        code, global_dict, local_dict)  # take local objects in preference
```

Where code is:

```
Symbol ('x' ).y
```

Full trace:

```
FAILED                   [100%]
        class C:
            def __repr__(self):
                return 'x.y'
    
>       _ = sympy.Symbol('x') == C()

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
sympy/core/expr.py:124: in __eq__
    other = sympify(other)
sympy/core/sympify.py:385: in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
sympy/parsing/sympy_parser.py:1011: in parse_expr
    return eval_expr(code, local_dict, global_dict)
sympy/parsing/sympy_parser.py:906: in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

>   ???
E   AttributeError: 'Symbol' object has no attribute 'y'

<string>:1: AttributeError
```

Related issue: an unknown object whose repr is `x` will incorrectly compare as equal to a sympy symbol x:

```
    class C:
        def __repr__(self):
            return 'x'

    assert sympy.Symbol('x') != C()  # fails
```
Bad centering for Sum pretty print
```
>>> pprint(Sum(x, (x, 1, oo)) + 3)
  ∞
 ___
 ╲
  ╲   x
  ╱     + 3
 ╱
 ‾‾‾
x = 1
```

The `x` and the `+ 3` should be aligned. I'm not sure if the `x` should be lower of if the `+ 3` should be higher.
Raise error when blueprint name contains a dot
This is required since every dot is now significant since blueprints can be nested. An error was already added for endpoint names in 1.0, but should have been added for this as well.
Allow FilePathField path to accept a callable.
Description
	
I have a special case where I want to create a model containing the path to some local files on the server/dev machine. Seeing as the place where these files are stored is different on different machines I have the following:
import os
from django.conf import settings
from django.db import models
class LocalFiles(models.Model):
	name = models.CharField(max_length=255)
	file = models.FilePathField(path=os.path.join(settings.LOCAL_FILE_DIR, 'example_dir'))
Now when running manage.py makemigrations it will resolve the path based on the machine it is being run on. Eg: /home/<username>/server_files/example_dir
I had to manually change the migration to include the os.path.join() part to not break this when running the migration on production/other machine.
inherited-members should support more than one class
**Is your feature request related to a problem? Please describe.**
I have two situations:
- A class inherits from multiple other classes. I want to document members from some of the base classes but ignore some of the base classes
- A module contains several class definitions that inherit from different classes that should all be ignored (e.g., classes that inherit from list or set or tuple). I want to ignore members from list, set, and tuple while documenting all other inherited members in classes in the module.

**Describe the solution you'd like**
The :inherited-members: option to automodule should accept a list of classes. If any of these classes are encountered as base classes when instantiating autoclass documentation, they should be ignored.

**Describe alternatives you've considered**
The alternative is to not use automodule, but instead manually enumerate several autoclass blocks for a module. This only addresses the second bullet in the problem description and not the first. It is also tedious for modules containing many class definitions.
bug in print_changed_only in new repr: vector values
```python
import sklearn
import numpy as np
from sklearn.linear_model import LogisticRegressionCV
sklearn.set_config(print_changed_only=True)
print(LogisticRegressionCV(Cs=np.array([0.1, 1])))
```
> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

ping @NicolasHug
sqlmigrate wraps it's outpout in BEGIN/COMMIT even if the database doesn't support transactional DDL
Description
	 
		(last modified by Simon Charette)
	 
The migration executor only adds the outer BEGIN/COMMIT ​if the migration is atomic and ​the schema editor can rollback DDL but the current sqlmigrate logic only takes migration.atomic into consideration.
The issue can be addressed by
Changing sqlmigrate ​assignment of self.output_transaction to consider connection.features.can_rollback_ddl as well.
Adding a test in tests/migrations/test_commands.py based on ​an existing test for non-atomic migrations that mocks connection.features.can_rollback_ddl to False instead of overdidding MIGRATION_MODULES to point to a non-atomic migration.
I marked the ticket as easy picking because I included the above guidelines but feel free to uncheck it if you deem it inappropriate.
Union queryset should raise on distinct().
Description
	 
		(last modified by Sielc Technologies)
	 
After using
.annotate() on 2 different querysets
and then .union()
.distinct() will not affect the queryset
	def setUp(self) -> None:
		user = self.get_or_create_admin_user()
		Sample.h.create(user, name="Sam1")
		Sample.h.create(user, name="Sam2 acid")
		Sample.h.create(user, name="Sam3")
		Sample.h.create(user, name="Sam4 acid")
		Sample.h.create(user, name="Dub")
		Sample.h.create(user, name="Dub")
		Sample.h.create(user, name="Dub")
		self.user = user
	def test_union_annotated_diff_distinct(self):
		qs = Sample.objects.filter(user=self.user)
		qs1 = qs.filter(name='Dub').annotate(rank=Value(0, IntegerField()))
		qs2 = qs.filter(name='Sam1').annotate(rank=Value(1, IntegerField()))
		qs = qs1.union(qs2)
		qs = qs.order_by('name').distinct('name') # THIS DISTINCT DOESN'T WORK
		self.assertEqual(qs.count(), 2)
expected to get wrapped union
	SELECT DISTINCT ON (siebox_sample.name) * FROM (SELECT ... UNION SELECT ...) AS siebox_sample
inspectdb should generate related_name on same relation links.
Description
	
Hi!
After models generation with inspectdb command we have issue with relations to same enities
module.Model.field1: (fields.E304) Reverse accessor for 'module.Model.field1' clashes with reverse accessor for 'module.Model.field2'.
HINT: Add or change a related_name argument to the definition for 'module.Model.field1' or 'module.Model.field2'.
*
Maybe we can autogenerate
related_name='attribute_name'
to all fields in model if related Model was used for this table
"TypeError: cannot pickle" when applying | operator to a Q object
Description
	 
		(last modified by Daniel Izquierdo)
	 
Using a reference to a non-pickleable type of object such as dict_keys in a Q object makes the | operator fail:
>>> from django.db.models import Q
>>> Q(x__in={}.keys())
<Q: (AND: ('x__in', dict_keys([])))>
>>> Q() | Q(x__in={}.keys())
Traceback (most recent call last):
...
TypeError: cannot pickle 'dict_keys' object
Even though this particular example could be solved by doing Q() | Q(x__in={}) it still feels like using .keys() should work.
I can work on a patch if there's agreement that this should not crash.
Models migration with change field foreign to many and deleting unique together.
Description
	 
		(last modified by Simon Charette)
	 
I have models like
class Authors(models.Model):
	project_data_set = models.ForeignKey(
		ProjectDataSet,
		on_delete=models.PROTECT
	)
	state = models.IntegerField()
	start_date = models.DateField()
	class Meta:
		 unique_together = (('project_data_set', 'state', 'start_date'),)
and
class DataSet(models.Model):
	name = models.TextField(max_length=50)
class Project(models.Model):
	data_sets = models.ManyToManyField(
		DataSet,
		through='ProjectDataSet',
	)
	name = models.TextField(max_length=50)
class ProjectDataSet(models.Model):
	"""
	Cross table of data set and project
	"""
	data_set = models.ForeignKey(DataSet, on_delete=models.PROTECT)
	project = models.ForeignKey(Project, on_delete=models.PROTECT)
	class Meta:
		unique_together = (('data_set', 'project'),)
when i want to change field project_data_set in Authors model from foreign key field to many to many field I must delete a unique_together, cause it can't be on many to many field.
Then my model should be like:
class Authors(models.Model):
	project_data_set = models.ManyToManyField(
		ProjectDataSet,
	)
	state = models.IntegerField()
	start_date = models.DateField()
But when I want to do a migrations.
python3 manage.py makemigrations
python3 manage.py migrate
I have error:
ValueError: Found wrong number (0) of constraints for app_authors(project_data_set, state, start_date)
The database is on production, so I can't delete previous initial migrations, and this error isn't depending on database, cause I delete it and error is still the same.
My solve is to first delete unique_together, then do a makemigrations and then migrate. After that change the field from foreign key to many to many field, then do a makemigrations and then migrate.
But in this way I have 2 migrations instead of one.
I added attachment with this project, download it and then do makemigrations and then migrate to see this error.
Prevent using __isnull lookup with non-boolean value.
Description
	 
		(last modified by Mariusz Felisiak)
	 
__isnull should not allow for non-boolean values. Using truthy/falsey doesn't promote INNER JOIN to an OUTER JOIN but works fine for a simple queries. Using non-boolean values is ​undocumented and untested. IMO we should raise an error for non-boolean values to avoid confusion and for consistency.
Merging 3 or more media objects can throw unnecessary MediaOrderConflictWarnings
Description
	
Consider the following form definition, where text-editor-extras.js depends on text-editor.js but all other JS files are independent:
from django import forms
class ColorPicker(forms.Widget):
	class Media:
		js = ['color-picker.js']
class SimpleTextWidget(forms.Widget):
	class Media:
		js = ['text-editor.js']
class FancyTextWidget(forms.Widget):
	class Media:
		js = ['text-editor.js', 'text-editor-extras.js', 'color-picker.js']
class MyForm(forms.Form):
	background_color = forms.CharField(widget=ColorPicker())
	intro = forms.CharField(widget=SimpleTextWidget())
	body = forms.CharField(widget=FancyTextWidget())
Django should be able to resolve the JS files for the final form into the order text-editor.js, text-editor-extras.js, color-picker.js. However, accessing MyForm().media results in:
/projects/django/django/forms/widgets.py:145: MediaOrderConflictWarning: Detected duplicate Media files in an opposite order:
text-editor-extras.js
text-editor.js
 MediaOrderConflictWarning,
Media(css={}, js=['text-editor-extras.js', 'color-picker.js', 'text-editor.js'])
The MediaOrderConflictWarning is a result of the order that the additions happen in: ColorPicker().media + SimpleTextWidget().media produces Media(css={}, js=['color-picker.js', 'text-editor.js']), which (wrongly) imposes the constraint that color-picker.js must appear before text-editor.js.
The final result is particularly unintuitive here, as it's worse than the "naïve" result produced by Django 1.11 before order-checking was added (color-picker.js, text-editor.js, text-editor-extras.js), and the pair of files reported in the warning message seems wrong too (aren't color-picker.js and text-editor.js the wrong-ordered ones?)
overescaped trailing underscore on attribute with napoleon
**Describe the bug**
Attribute name `hello_` shows up as `hello\_` in the html (visible backslash) with napoleon.

**To Reproduce**
Steps to reproduce the behavior:

empty `__init__.py`
`a.py` contains
```python
class A:
    """
    Attributes
    ----------
    hello_: int
        hi
    """
    pass
```
run `sphinx-quickstart`
add `'sphinx.ext.autodoc', 'sphinx.ext.napoleon'` to extensions in conf.py.
add `.. autoclass:: a.A` to index.rst
PYTHONPATH=. make clean html
open _build/html/index.html in web browser and see the ugly backslash.

**Expected behavior**
No backslash, a similar output to what I get for
```rst
    .. attribute:: hello_
        :type: int

        hi
```
(the type shows up differently as well, but that's not the point here)
Older versions like 2.4.3 look ok to me.

**Environment info**
- OS: Linux debian testing
- Python version: 3.8.3
- Sphinx version: 3.0.4
- Sphinx extensions:  sphinx.ext.autodoc, sphinx.ext.napoleon
- Extra tools:
Python 2->3 pickle fails with float-containing expressions
Dumping a pickled sympy expression containing a float in Python 2, then loading it in Python 3 generates an error.

Here is a minimum working example, verified with sympy git commit 3546ac7 (master at time of writing), Python 2.7 and Python 3.6:

```python
python2 -c 'import pickle; import sympy; x = sympy.symbols("x"); print pickle.dumps(x + 1.0, 2)' | python3 -c 'import pickle; import sys; print(pickle.loads(sys.stdin.buffer.read()))'
```

and the result:

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/alex/git/VU/sympy/sympy/core/numbers.py", line 1045, in __new__
    num[1] = long(num[1], 16)
ValueError: invalid literal for int() with base 16: '1L'
```
Use Admin Inline verbose_name as default for Inline verbose_name_plural
Description
	
Django allows specification of a verbose_name and a verbose_name_plural for Inline classes in admin views. However, verbose_name_plural for an Inline is not currently based on a specified verbose_name. Instead, it continues to be based on the model name, or an a verbose_name specified in the model's Meta class. This was confusing to me initially (I didn't understand why I had to specify both name forms for an Inline if I wanted to overrule the default name), and seems inconsistent with the approach for a model's Meta class (which does automatically base the plural form on a specified verbose_name). I propose that verbose_name_plural for an Inline class should by default be based on the verbose_name for an Inline if that is specified.
I have written a patch to implement this, including tests. Would be happy to submit that.
[ENH]: Axes.set_xticks/Axis.set_ticks only validates kwargs if ticklabels are set, but they should
### Problem

Per the doc of `Axis.set_ticks`:
```
        **kwargs
            `.Text` properties for the labels. These take effect only if you
            pass *labels*. In other cases, please use `~.Axes.tick_params`.
```
This means that in e.g. `ax.set_xticks([0, 1], xticklabels=["a", "b"])`, the incorrect `xticklabels` silently do nothing; they are not even validated (because `labels` has not been passed).

### Proposed solution

We should at least check that `kwargs` are valid Text properties in all cases; we could even consider making any kwargs an error if `labels` is not set.
Exponent doesn't fully simplify
Say I have code like this:

```
import sympy
from sympy import *
x=Symbol('x')
expr1 = S(1)/2*x**2.5
expr2 = S(1)*x**(S(5)/2)/2
res = expr1-expr2
res= simplify(res.evalf(5))
print res
```

The output is
`-0.5*x**2.5 + 0.5*x**2.5`
How do I simplify it to 0?
Prevent developers from defining a related_name on symmetrical ManyToManyFields
Description
	
In ManyToManyField, if the symmetrical argument is passed, or if it's a self-referential ManyToMany relationship, the related field on the target model is not created. However, if a developer passes in the related_name not understanding this fact, they may be confused until they find the information about symmetrical relationship. Thus, it is proposed to raise an error when the user defines a ManyToManyField in this condition.
expr.atoms() should return objects with no args instead of subclasses of Atom
`expr.atoms()` with no arguments returns subclasses of `Atom` in `expr`. But the correct definition of a leaf node should be that it has no `.args`. 

This should be easy to fix, but one needs to check that this doesn't affect the performance.
Add an encoder parameter to django.utils.html.json_script().
Description
	
I have a use case where I want to customize the JSON encoding of some values to output to the template layer. It looks like django.utils.html.json_script is a good utility for that, however the JSON encoder is hardcoded to DjangoJSONEncoder. I think it would be nice to be able to pass a custom encoder class.
By the way, django.utils.html.json_script is not documented (only its template filter counterpart is), would it be a good thing to add to the docs?
Linting fails if module contains module of the same name
### Steps to reproduce

Given multiple files:
```
.
`-- a/
    |-- a.py
    `-- b.py
```
Which are all empty, running `pylint a` fails:

```
$ pylint a
************* Module a
a/__init__.py:1:0: F0010: error while code parsing: Unable to load file a/__init__.py:
[Errno 2] No such file or directory: 'a/__init__.py' (parse-error)
$
```

However, if I rename `a.py`, `pylint a` succeeds:

```
$ mv a/a.py a/c.py
$ pylint a
$
```
Alternatively, I can also `touch a/__init__.py`, but that shouldn't be necessary anymore.

### Current behavior

Running `pylint a` if `a/a.py` is present fails while searching for an `__init__.py` file.

### Expected behavior

Running `pylint a` if `a/a.py` is present should succeed.

### pylint --version output

Result of `pylint --version` output:

```
pylint 3.0.0a3
astroid 2.5.6
Python 3.8.5 (default, Jan 27 2021, 15:41:15) 
[GCC 9.3.0]
```

### Additional info

This also has some side-effects in module resolution. For example, if I create another file `r.py`:

```
.
|-- a
|   |-- a.py
|   `-- b.py
`-- r.py
```

With the content:

```
from a import b
```

Running `pylint -E r` will run fine, but `pylint -E r a` will fail. Not just for module a, but for module r as well.

```
************* Module r
r.py:1:0: E0611: No name 'b' in module 'a' (no-name-in-module)
************* Module a
a/__init__.py:1:0: F0010: error while code parsing: Unable to load file a/__init__.py:
[Errno 2] No such file or directory: 'a/__init__.py' (parse-error)
```

Again, if I rename `a.py` to `c.py`, `pylint -E r a` will work perfectly.
Django 3.0: "GROUP BY" clauses error with tricky field annotation
Description
	
Let's pretend that we have next model structure with next model's relations:
class A(models.Model):
	bs = models.ManyToManyField('B',
								related_name="a",
								through="AB")
class B(models.Model):
	pass
class AB(models.Model):
	a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="ab_a")
	b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="ab_b")
	status = models.IntegerField()
class C(models.Model):
	a = models.ForeignKey(
		A,
		null=True,
		blank=True,
		on_delete=models.SET_NULL,
		related_name="c",
		verbose_name=_("a")
	)
	status = models.IntegerField()
Let's try to evaluate next query
ab_query = AB.objects.filter(a=OuterRef("pk"), b=1)
filter_conditions = Q(pk=1) | Q(ab_a__b=1)
query = A.objects.\
	filter(filter_conditions).\
	annotate(
		status=Subquery(ab_query.values("status")),
		c_count=Count("c"),
)
answer = query.values("status").annotate(total_count=Count("status"))
print(answer.query)
print(answer)
On Django 3.0.4 we have an error
django.db.utils.ProgrammingError: column reference "status" is ambiguous
and query is next:
SELECT (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = "test_app_a"."id" AND U0."b_id" = 1)) AS "status", COUNT((SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = "test_app_a"."id" AND U0."b_id" = 1))) AS "total_count" FROM "test_app_a" LEFT OUTER JOIN "test_app_ab" ON ("test_app_a"."id" = "test_app_ab"."a_id") LEFT OUTER JOIN "test_app_c" ON ("test_app_a"."id" = "test_app_c"."a_id") WHERE ("test_app_a"."id" = 1 OR "test_app_ab"."b_id" = 1) GROUP BY "status"
However, Django 2.2.11 processed this query properly with the next query:
SELECT (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1)) AS "status", COUNT((SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1))) AS "total_count" FROM "test_app_a" LEFT OUTER JOIN "test_app_ab" ON ("test_app_a"."id" = "test_app_ab"."a_id") LEFT OUTER JOIN "test_app_c" ON ("test_app_a"."id" = "test_app_c"."a_id") WHERE ("test_app_a"."id" = 1 OR "test_app_ab"."b_id" = 1) GROUP BY (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1))
so, the difference in "GROUP BY" clauses
(as DB provider uses "django.db.backends.postgresql", postgresql 11)
Settings are cleaned insufficiently.
Description
	
Posting publicly after checking with the rest of the security team.
I just ran into a case where django.views.debug.SafeExceptionReporterFilter.get_safe_settings() would return several un-cleansed values. Looking at cleanse_setting() I realized that we ​only take care of `dict`s but don't take other types of iterables into account but ​return them as-is.
Example:
In my settings.py I have this:
MY_SETTING = {
	"foo": "value",
	"secret": "value",
	"token": "value",
	"something": [
		{"foo": "value"},
		{"secret": "value"},
		{"token": "value"},
	],
	"else": [
		[
			{"foo": "value"},
			{"secret": "value"},
			{"token": "value"},
		],
		[
			{"foo": "value"},
			{"secret": "value"},
			{"token": "value"},
		],
	]
}
On Django 3.0 and below:
>>> import pprint
>>> from django.views.debug import get_safe_settings
>>> pprint.pprint(get_safe_settings()["MY_SETTING"])
{'else': [[{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],
		 [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}]],
 'foo': 'value',
 'secret': '********************',
 'something': [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],
 'token': '********************'}
On Django 3.1 and up:
>>> from django.views.debug import SafeExceptionReporterFilter
>>> import pprint
>>> pprint.pprint(SafeExceptionReporterFilter().get_safe_settings()["MY_SETTING"])
{'else': [[{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],
		 [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}]],
 'foo': 'value',
 'secret': '********************',
 'something': [{'foo': 'value'}, {'secret': 'value'}, {'token': 'value'}],
 'token': '********************'}
Support nullable pandas dtypes in `unique_labels`
### Describe the workflow you want to enable

I would like to be able to pass the nullable pandas dtypes ("Int64", "Float64", "boolean") into sklearn's `unique_labels` function. Because the dtypes become `object` dtype when converted to numpy arrays we get `ValueError: Mix type of y not allowed, got types {'binary', 'unknown'}`:

Repro with sklearn 1.2.1
```py 
    import pandas as pd
    import pytest
    from sklearn.utils.multiclass import unique_labels
    
    for dtype in ["Int64", "Float64", "boolean"]:
        y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype)
        y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64")

        with pytest.raises(ValueError, match="Mix type of y not allowed, got types"):
            unique_labels(y_true, y_predicted)
```

### Describe your proposed solution

We should get the same behavior as when `int64`, `float64`, and `bool` dtypes are used, which is no error:  

```python
    import pandas as pd
    from sklearn.utils.multiclass import unique_labels
    
    for dtype in ["int64", "float64", "bool"]:
        y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype)
        y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64")

        unique_labels(y_true, y_predicted)
```

### Describe alternatives you've considered, if relevant

Our current workaround is to convert the data to numpy arrays with the corresponding dtype that works prior to passing it into `unique_labels`.

### Additional context

_No response_
Flask routes to return domain/sub-domains information
Currently when checking **flask routes** it provides all routes but **it is no way to see which routes are assigned to which subdomain**.

**Default server name:**
SERVER_NAME: 'test.local'

**Domains (sub-domains):**
test.test.local
admin.test.local
test.local

**Adding blueprints:**
app.register_blueprint(admin_blueprint,url_prefix='',subdomain='admin')
app.register_blueprint(test_subdomain_blueprint,url_prefix='',subdomain='test')


```
$ flask routes
 * Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them.
Endpoint                                                 Methods    Rule
-------------------------------------------------------  ---------  ------------------------------------------------
admin_blueprint.home                                      GET        /home
test_subdomain_blueprint.home                             GET        /home
static                                                    GET        /static/<path:filename>
...
```


**Feature request**
It will be good to see something like below (that will make more clear which route for which subdomain, because now need to go and check configuration).
**If it is not possible to fix routes**, can you add or tell which method(s) should be used to get below information from flask? 

```
$ flask routes
 * Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them.
Domain                Endpoint                                             Methods    Rule
-----------------   ----------------------------------------------------  ----------  ------------------------------------------------
admin.test.local     admin_blueprint.home                                  GET        /home
test.test.local      test_subdomain_blueprint.home                         GET        /home
test.local           static                                                GET        /static/<path:filename>
...
```
Make django.utils.text.slugify() strip dashes and underscores
Description
	 
		(last modified by Elinaldo do Nascimento Monteiro)
	 
Bug generation slug
Example:
from django.utils import text
text.slugify("___This is a test ---")
output: ___this-is-a-test-
Improvement after correction
from django.utils import text
text.slugify("___This is a test ---")
output: this-is-a-test
​PR