mteb/SWEbenchLiteRR huggingface dataset:
lambdify does not work with certain MatrixSymbol names even with dummify=True
`lambdify` is happy with curly braces in a symbol name and with `MatrixSymbol`s, but not with both at the same time, even if `dummify` is `True`.

Here is some basic code that gives the error.
```
import sympy as sy
curlyx = sy.symbols("{x}")
v = sy.MatrixSymbol("v", 2, 1)
curlyv = sy.MatrixSymbol("{v}", 2, 1)
```

The following two lines of code work:
```
curlyScalarId = sy.lambdify(curlyx, curlyx)
vectorId = sy.lambdify(v,v)
```

The following two lines of code give a `SyntaxError`:
```
curlyVectorId = sy.lambdify(curlyv, curlyv)
curlyVectorIdDummified = sy.lambdify(curlyv, curlyv, dummify=True)
```
Color mapping fails with boolean data
```python
so.Plot(["a", "b"], [1, 2], color=[True, False]).add(so.Bar())
```
```python-traceback
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
...
File ~/code/seaborn/seaborn/_core/plot.py:841, in Plot._plot(self, pyplot)
    838 plotter._compute_stats(self, layers)
    840 # Process scale spec for semantic variables and coordinates computed by stat
--> 841 plotter._setup_scales(self, common, layers)
    843 # TODO Remove these after updating other methods
    844 # ---- Maybe have debug= param that attaches these when True?
    845 plotter._data = common

File ~/code/seaborn/seaborn/_core/plot.py:1252, in Plotter._setup_scales(self, p, common, layers, variables)
   1250     self._scales[var] = Scale._identity()
   1251 else:
-> 1252     self._scales[var] = scale._setup(var_df[var], prop)
   1254 # Everything below here applies only to coordinate variables
   1255 # We additionally skip it when we're working with a value
   1256 # that is derived from a coordinate we've already processed.
   1257 # e.g., the Stat consumed y and added ymin/ymax. In that case,
   1258 # we've already setup the y scale and ymin/max are in scale space.
   1259 if axis is None or (var != coord and coord in p._variables):

File ~/code/seaborn/seaborn/_core/scales.py:351, in ContinuousBase._setup(self, data, prop, axis)
    349 vmin, vmax = axis.convert_units((vmin, vmax))
    350 a = forward(vmin)
--> 351 b = forward(vmax) - forward(vmin)
    353 def normalize(x):
    354     return (x - a) / b

TypeError: numpy boolean subtract, the `-` operator, is not supported, use the bitwise_xor, the `^` operator, or the logical_xor function instead.
```
Fix handling empty string for If-Modified-Since header
Description
	
Empty string used to be ignored for If-Modified-Since header, but now raises exception since d6aff369ad3.
Fix handling empty string for If-Modified-Since header
Description
	
Empty string used to be ignored for If-Modified-Since header, but now raises exception since d6aff369ad3.
decompose() function in intpoly returns a list of arbitrary order
The decompose() function, with separate=True, returns `list(poly_dict.values())`, which is ordered arbitrarily.  

What is this used for? It should be sorted somehow, or returning a set (in which case, why not just use the returned dictionary and have the caller take the values). This is causing test failures for me after some changes to the core. 

CC @ArifAhmed1995 @certik
ModelForm fields with callable defaults don't correctly propagate default values
Description
	
When creating an object via the admin, if an inline contains an ArrayField in error, the validation will be bypassed (and the inline dismissed) if we submit the form a second time (without modification).
go to /admin/my_app/thing/add/
type anything in plop
submit -> it shows an error on the inline
submit again -> no errors, plop become unfilled
# models.py
class Thing(models.Model):
	pass
class RelatedModel(models.Model):
	thing = models.ForeignKey(Thing, on_delete=models.CASCADE)
	plop = ArrayField(
		models.CharField(max_length=42),
		default=list,
	)
# admin.py
class RelatedModelForm(forms.ModelForm):
	def clean(self):
		raise ValidationError("whatever")
class RelatedModelInline(admin.TabularInline):
	form = RelatedModelForm
	model = RelatedModel
	extra = 1
@admin.register(Thing)
class ThingAdmin(admin.ModelAdmin):
	inlines = [
		RelatedModelInline
	]
It seems related to the hidden input containing the initial value:
<input type="hidden" name="initial-relatedmodel_set-0-plop" value="test" id="initial-relatedmodel_set-0-id_relatedmodel_set-0-plop">
I can fix the issue locally by forcing show_hidden_initial=False on the field (in the form init)
convert_to seems to combine orthogonal units
Tested in sympy 1.4, not presently in a position to install 1.5+.
Simple example. Consider `J = kg*m**2/s**2 => J*s = kg*m**2/s`. The convert_to behavior is odd:
```
>>>convert_to(joule*second,joule)
    joule**(7/9)
```
I would expect the unchanged original expression back, an expression in terms of base units, or an error. It appears that convert_to can only readily handle conversions where the full unit expression is valid.

Note that the following three related examples give sensible results:
```
>>>convert_to(joule*second,joule*second)
    joule*second
```
```
>>>convert_to(J*s, kg*m**2/s)
    kg*m**2/s
```
```
>>>convert_to(J*s,mins)
    J*mins/60
```
urllib3 exceptions passing through requests API
I don't know if it's a design goal of requests to hide urllib3's exceptions and wrap them around requests.exceptions types.

(If it's not IMHO it should be, but that's another discussion)

If it is, I have at least two of them passing through that I have to catch in addition to requests' exceptions. They are requests.packages.urllib3.exceptions.DecodeError and requests.packages.urllib3.exceptions.TimeoutError (this one I get when a proxy timeouts)

Thanks!
Remove "for = ..." from MultiWidget's <label>.
Description
	
The instance from Raw MultiWidget class generate id_for_label like f'{id_}0'
It has not sense.
For example ChoiceWidget has self.add_id_index and I can decide it myself, how I will see label_id - with or without index.
I think, it is better to remove completely id_for_label method from MultiWidget Class.
str() on the pytest.raises context variable doesn't behave same as normal exception catch
Pytest 4.6.2, macOS 10.14.5

```Python
try:
    raise LookupError(
        f"A\n"
        f"B\n"
        f"C"
    )
except LookupError as e:
    print(str(e))
```
prints

> A
> B
> C

But

```Python
with pytest.raises(LookupError) as e:
    raise LookupError(
        f"A\n"
        f"B\n"
        f"C"
    )

print(str(e))
```

prints

> <console>:3: LookupError: A

In order to get the full error message, one must do `str(e.value)`, which is documented, but this is a different interaction. Any chance the behavior could be changed to eliminate this gotcha?

-----

Pip list gives

```
Package            Version  Location
------------------ -------- ------------------------------------------------------
apipkg             1.5
asn1crypto         0.24.0
atomicwrites       1.3.0
attrs              19.1.0
aws-xray-sdk       0.95
boto               2.49.0
boto3              1.9.51
botocore           1.12.144
certifi            2019.3.9
cffi               1.12.3
chardet            3.0.4
Click              7.0
codacy-coverage    1.3.11
colorama           0.4.1
coverage           4.5.3
cryptography       2.6.1
decorator          4.4.0
docker             3.7.2
docker-pycreds     0.4.0
docutils           0.14
ecdsa              0.13.2
execnet            1.6.0
future             0.17.1
idna               2.8
importlib-metadata 0.17
ipaddress          1.0.22
Jinja2             2.10.1
jmespath           0.9.4
jsondiff           1.1.1
jsonpickle         1.1
jsonschema         2.6.0
MarkupSafe         1.1.1
mock               3.0.4
more-itertools     7.0.0
moto               1.3.7
neobolt            1.7.10
neotime            1.7.4
networkx           2.1
numpy              1.15.0
packaging          19.0
pandas             0.24.2
pip                19.1.1
pluggy             0.12.0
prompt-toolkit     2.0.9
py                 1.8.0
py2neo             4.2.0
pyaml              19.4.1
pycodestyle        2.5.0
pycparser          2.19
pycryptodome       3.8.1
Pygments           2.3.1
pyOpenSSL          19.0.0
pyparsing          2.4.0
pytest             4.6.2
pytest-cache       1.0
pytest-codestyle   1.4.0
pytest-cov         2.6.1
pytest-forked      1.0.2
python-dateutil    2.7.3
python-jose        2.0.2
pytz               2018.5
PyYAML             5.1
requests           2.21.0
requests-mock      1.5.2
responses          0.10.6
s3transfer         0.1.13
setuptools         41.0.1
six                1.11.0
sqlite3worker      1.1.7
tabulate           0.8.3
urllib3            1.24.3
wcwidth            0.1.7
websocket-client   0.56.0
Werkzeug           0.15.2
wheel              0.33.1
wrapt              1.11.1
xlrd               1.1.0
xmltodict          0.12.0
zipp               0.5.1
```
Using custom braces in message template does not work
### Bug description

Have any list of errors:

On pylint 1.7 w/ python3.6 - I am able to use this as my message template
```
$ pylint test.py --msg-template='{{ "Category": "{category}" }}'
No config file found, using default configuration
************* Module [redacted].test
{ "Category": "convention" }
{ "Category": "error" }
{ "Category": "error" }
{ "Category": "convention" }
{ "Category": "convention" }
{ "Category": "convention" }
{ "Category": "error" }
```

However, on Python3.9 with Pylint 2.12.2, I get the following:
```
$ pylint test.py --msg-template='{{ "Category": "{category}" }}'
[redacted]/site-packages/pylint/reporters/text.py:206: UserWarning: Don't recognize the argument '{ "Category"' in the --msg-template. Are you sure it is supported on the current version of pylint?
  warnings.warn(
************* Module [redacted].test
" }
" }
" }
" }
" }
" }
```

Is this intentional or a bug?

### Configuration

_No response_

### Command used

```shell
pylint test.py --msg-template='{{ "Category": "{category}" }}'
```


### Pylint output

```shell
[redacted]/site-packages/pylint/reporters/text.py:206: UserWarning: Don't recognize the argument '{ "Category"' in the --msg-template. Are you sure it is supported on the current version of pylint?
  warnings.warn(
************* Module [redacted].test
" }
" }
" }
" }
" }
" }
```


### Expected behavior

Expect the dictionary to print out with `"Category"` as the key.

### Pylint version

```shell
Affected Version:
pylint 2.12.2
astroid 2.9.2
Python 3.9.9+ (heads/3.9-dirty:a2295a4, Dec 21 2021, 22:32:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]


Previously working version:
No config file found, using default configuration
pylint 1.7.4, 
astroid 1.6.6
Python 3.6.8 (default, Nov 16 2020, 16:55:22) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
```


### OS / Environment

_No response_

### Additional dependencies

_No response_
AlterOrderWithRespectTo() with ForeignKey crash when _order is included in Index().
Description
	
	class Meta:
		db_table = 'look_image'
		order_with_respect_to = 'look'
		indexes = [
			models.Index(fields=['look', '_order']),
			models.Index(fields=['created_at']),
			models.Index(fields=['updated_at']),
		]
migrations.CreateModel(
			name='LookImage',
			fields=[
				('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
				('look', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='posts.Look', verbose_name='LOOK')),
				('image_url', models.URLField(blank=True, max_length=10000, null=True)),
				('image', models.ImageField(max_length=2000, upload_to='')),
				('deleted', models.DateTimeField(editable=False, null=True)),
				('created_at', models.DateTimeField(auto_now_add=True)),
				('updated_at', models.DateTimeField(auto_now=True)),
			],
		),
		migrations.AddIndex(
			model_name='lookimage',
			index=models.Index(fields=['look', '_order'], name='look_image_look_id_eaff30_idx'),
		),
		migrations.AddIndex(
			model_name='lookimage',
			index=models.Index(fields=['created_at'], name='look_image_created_f746cf_idx'),
		),
		migrations.AddIndex(
			model_name='lookimage',
			index=models.Index(fields=['updated_at'], name='look_image_updated_aceaf9_idx'),
		),
		migrations.AlterOrderWithRespectTo(
			name='lookimage',
			order_with_respect_to='look',
		),
I added orders_with_respect_to in new model class's Meta class and also made index for '_order' field by combining with other field. And a new migration file based on the model looks like the code above.
The problem is operation AlterOrderWithRespectTo after AddIndex of '_order' raising error because '_order' field had not been created yet.
It seems to be AlterOrderWithRespectTo has to proceed before AddIndex of '_order'.
[Bug]: Attribute Error combining matplotlib 3.7.1 and mplcursor on data selection
### Bug summary

If you combine mplcursor and matplotlib 3.7.1, you'll get an `AttributeError: 'NoneType' object has no attribute 'canvas'` after clicking a few data points. Henceforth, selecting a new data point will trigger the same traceback. Otherwise, it works fine. 

### Code for reproduction

```python
import numpy as np
import matplotlib.pyplot as plt
import mplcursors as mpl

x = np.arange(1, 11)    
y1 = x

plt.scatter(x,y1)

mpl.cursor()
plt.show()
```


### Actual outcome

```
Traceback (most recent call last):
  File "C:\Users\MrAni\Python\miniconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 304, in process
    func(*args, **kwargs)
  File "C:\Users\MrAni\Python\miniconda3\lib\site-packages\matplotlib\offsetbox.py", line 1550, in on_release
    if self._check_still_parented() and self.got_artist:
  File "C:\Users\MrAni\Python\miniconda3\lib\site-packages\matplotlib\offsetbox.py", line 1560, in _check_still_parented
    self.disconnect()
  File "C:\Users\MrAni\Python\miniconda3\lib\site-packages\matplotlib\offsetbox.py", line 1568, in disconnect
    self.canvas.mpl_disconnect(cid)
  File "C:\Users\MrAni\Python\miniconda3\lib\site-packages\matplotlib\offsetbox.py", line 1517, in <lambda>
    canvas = property(lambda self: self.ref_artist.figure.canvas)
AttributeError: 'NoneType' object has no attribute 'canvas'
```

### Expected outcome

No terminal output

### Additional information

Using matplotlib 3.7.0 or lower works fine. Using a conda install or pip install doesn't affect the output. 

### Operating system

Windows 11 and Windwos 10 

### Matplotlib Version

3.7.1

### Matplotlib Backend

QtAgg

### Python version

3.9.16

### Jupyter version

_No response_

### Installation

conda
Should mixture models have a clusterer-compatible interface
Mixture models are currently a bit different. They are basically clusterers, except they are probabilistic, and are applied to inductive problems unlike many clusterers. But they are unlike clusterers in API:
* they have an `n_components` parameter, with identical purpose to `n_clusters`
* they do not store the `labels_` of the training data
* they do not have a `fit_predict` method

And they are almost entirely documented separately.

Should we make the MMs more like clusterers?
Sphinx 3.2 complains about option:: syntax that earlier versions accepted
Sphinx 3.2 complains about use of the option:: directive that earlier versions accepted without complaint.

The QEMU documentation includes this:
```
.. option:: [enable=]PATTERN

   Immediately enable events matching *PATTERN*
```

as part of the documentation of the command line options of one of its programs. Earlier versions of Sphinx were fine with this, but Sphinx 3.2 complains:

```
Warning, treated as error:
../../docs/qemu-option-trace.rst.inc:4:Malformed option description '[enable=]PATTERN', should look like "opt", "-opt args", "--opt args", "/opt args" or "+opt args"
```

Sphinx ideally shouldn't change in ways that break the building of documentation that worked in older versions, because this makes it unworkably difficult to have documentation that builds with whatever the Linux distro's sphinx-build is.

The error message suggests that Sphinx has a very restrictive idea of what option syntax is; it would be better if it just accepted any string, because not all programs and OSes have option syntax that matches the limited list the error message indicates.
@ (__matmul__) should fail if one argument is not a matrix
```
>>> A = Matrix([[1, 2], [3, 4]])
>>> B = Matrix([[2, 3], [1, 2]])
>>> A@B
Matrix([
[ 4,  7],
[10, 17]])
>>> 2@B
Matrix([
[4, 6],
[2, 4]])
```

Right now `@` (`__matmul__`) just copies `__mul__`, but it should actually only work if the multiplication is actually a matrix multiplication. 

This is also how NumPy works

```
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> 2*a
array([[2, 4],
       [6, 8]])
>>> 2@a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Scalar operands are not allowed, use '*' instead
```
Latex printer does not support full inverse trig function names for acsc and asec
For example
`latex(asin(x), inv_trig_style="full")` works as expected returning `'\\arcsin{\\left (x \\right )}'`
But `latex(acsc(x), inv_trig_style="full")` gives `'\\operatorname{acsc}{\\left (x \\right )}'` instead of `'\\operatorname{arccsc}{\\left (x \\right )}'`

A fix seems to be to change line 743 of sympy/printing/latex.py from
`inv_trig_table = ["asin", "acos", "atan", "acot"]` to
`inv_trig_table = ["asin", "acos", "atan", "acsc", "asec", "acot"]`
uniq modifies list argument
When you iterate over a dictionary or set and try to modify it while doing so you get an error from Python:
```python
>>> multiset('THISTLE')
{'T': 2, 'H': 1, 'I': 1, 'S': 1, 'L': 1, 'E': 1}
>>> for i in _:
...   _.pop(i)
...
2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
```
It would be good to do the same thing from within `uniq` because the output will silently be wrong if you modify a passed list:
```python
>>> f=list('THISTLE')
>>> for i in uniq(f):
...   f.remove(i)
...   i
...
'T'
'I'
'L'
```
I think this would entail recording the size at the start and then checking the size and raising a similar RuntimeError if the size changes.
Feature request: show units in dataset overview
Here's a hypothetical dataset:

```
<xarray.Dataset>
Dimensions:  (time: 3, x: 988, y: 822)
Coordinates:
  * x         (x) float64 ...
  * y         (y) float64 ...
  * time      (time) datetime64[ns] ...
Data variables:
    rainfall  (time, y, x) float32 ...
    max_temp  (time, y, x) float32 ...
```

It would be really nice if the units of the coordinates and of the data variables were shown in the `Dataset` repr, for example as:

```
<xarray.Dataset>
Dimensions:  (time: 3, x: 988, y: 822)
Coordinates:
  * x, in metres         (x)            float64 ...
  * y, in metres         (y)            float64 ...
  * time                 (time)         datetime64[ns] ...
Data variables:
    rainfall, in mm      (time, y, x)   float32 ...
    max_temp, in deg C   (time, y, x)   float32 ...
```
Squashing migrations with Meta.index_together -> indexes transition should remove deprecation warnings.
Description
	
Squashing migrations with Meta.index_together -> Meta.indexes transition should remove deprecation warnings. As far as I'm aware, it's a 4.2 release blocker because you cannot get rid of the index_together deprecation warnings without rewriting migrations, see comment.
Dev Server fails to restart after adding BASE_DIR to TEMPLATES[0]['DIRS'] in settings
Description
	
Repro steps:
$ pip install -U django
$ django-admin startproject <name>
Open settings.py, copy the BASE_DIR variable from line 16 and paste it into the empty DIRS list on line 57
$ ./manage.py runserver
Back in your IDE, save a file and watch the dev server *NOT* restart.
Back in settings.py, remove BASE_DIR from the templates DIRS list. Manually CTRL-C your dev server (as it won't restart on its own when you save), restart the dev server. Now return to your settings.py file, re-save it, and notice the development server once again detects changes and restarts.
This bug prevents the dev server from restarting no matter where you make changes - it is not just scoped to edits to settings.py.
LabelEncoder transform fails for empty lists (for certain inputs)
Python 3.6.3, scikit_learn 0.19.1

Depending on which datatypes were used to fit the LabelEncoder, transforming empty lists works or not. Expected behavior would be that empty arrays are returned in both cases.

```python
>>> from sklearn.preprocessing import LabelEncoder
>>> le = LabelEncoder()
>>> le.fit([1,2])
LabelEncoder()
>>> le.transform([])
array([], dtype=int64)
>>> le.fit(["a","b"])
LabelEncoder()
>>> le.transform([])
Traceback (most recent call last):
  File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 57, in _wrapfunc
    return getattr(obj, method)(*args, **kwds)
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[...]\Python36\lib\site-packages\sklearn\preprocessing\label.py", line 134, in transform
    return np.searchsorted(self.classes_, y)
  File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 1075, in searchsorted
    return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
  File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 67, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
  File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 47, in _wrapit
    result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'
```
FileBasedCache has_key is susceptible to race conditions
Description
	 
		(last modified by Marti Raudsepp)
	 
I received the exception from Django's cache framework:
FileNotFoundError: [Errno 2] No such file or directory: '/app/var/cache/d729e4cf4ba88cba5a0f48e0396ec48a.djcache'
[...]
 File "django/core/cache/backends/base.py", line 229, in get_or_set
	self.add(key, default, timeout=timeout, version=version)
 File "django/core/cache/backends/filebased.py", line 26, in add
	if self.has_key(key, version):
 File "django/core/cache/backends/filebased.py", line 94, in has_key
	with open(fname, "rb") as f:
The code is:
	def has_key(self, key, version=None):
		fname = self._key_to_file(key, version)
		if os.path.exists(fname):
			with open(fname, "rb") as f:
				return not self._is_expired(f)
		return False
Between the exists() check and open(), it's possible for the file to be deleted. In fact, the _is_expired() method itself deletes the file if it finds it to be expired. So if many threads race to read an expired cache at once, it's not that unlikely to hit this window.
Trailing whitespace in DatasetGroupBy text representation
When displaying a DatasetGroupBy in an interactive Python session, the first line of output contains a trailing whitespace. The first example in the documentation demonstrate this:

```pycon
>>> import xarray as xr, numpy as np
>>> ds = xr.Dataset(
...     {"foo": (("x", "y"), np.random.rand(4, 3))},
...     coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))},
... )
>>> ds.groupby("letters")
DatasetGroupBy, grouped over 'letters' 
2 groups with labels 'a', 'b'.
```

There is a trailing whitespace in the first line of output which is "DatasetGroupBy, grouped over 'letters' ". This can be seen more clearly by converting the object to a string (note the whitespace before `\n`):

```pycon
>>> str(ds.groupby("letters"))
"DatasetGroupBy, grouped over 'letters' \n2 groups with labels 'a', 'b'."
```


While this isn't a problem in itself, it causes an issue for us because we use flake8 in continuous integration to verify that our code is correctly formatted and we also have doctests that rely on DatasetGroupBy textual representation. Flake8 reports a violation on the trailing whitespaces in our docstrings. If we remove the trailing whitespaces, our doctests fail because the expected output doesn't match the actual output. So we have conflicting constraints coming from our tools which both seem reasonable. Trailing whitespaces are forbidden by flake8 because, among other reasons, they lead to noisy git diffs. Doctest want the expected output to be exactly the same as the actual output and considers a trailing whitespace to be a significant difference. We could configure flake8 to ignore this particular violation for the files in which we have these doctests, but this may cause other trailing whitespaces to creep in our code, which we don't want. Unfortunately it's not possible to just add `# NoQA` comments to get flake8 to ignore the violation only for specific lines because that creates a difference between expected and actual output from doctest point of view. Flake8 doesn't allow to disable checks for blocks of code either.

Is there a reason for having this trailing whitespace in DatasetGroupBy representation? Whould it be OK to remove it? If so please let me know and I can make a pull request.
Fix duplicated *args and **kwargs with autodoc_typehints
Fix duplicated *args and **kwargs with autodoc_typehints

### Bugfix
- Bugfix

### Detail
Consider this
```python
class _ClassWithDocumentedInitAndStarArgs:
    """Class docstring."""

    def __init__(self, x: int, *args: int, **kwargs: int) -> None:
        """Init docstring.

        :param x: Some integer
        :param *args: Some integer
        :param **kwargs: Some integer
        """
```
when using the autodoc extension and the setting `autodoc_typehints = "description"`.

WIth sphinx 4.2.0, the current output is
```
Class docstring.

   Parameters:
      * **x** (*int*) --

      * **args** (*int*) --

      * **kwargs** (*int*) --

   Return type:
      None

   __init__(x, *args, **kwargs)

      Init docstring.

      Parameters:
         * **x** (*int*) -- Some integer

         * ***args** --

           Some integer

         * ****kwargs** --

           Some integer

         * **args** (*int*) --

         * **kwargs** (*int*) --

      Return type:
         None
```
where the *args and **kwargs are duplicated and incomplete.

The expected output is
```
  Class docstring.

   Parameters:
      * **x** (*int*) --

      * ***args** (*int*) --

      * ****kwargs** (*int*) --

   Return type:
      None

   __init__(x, *args, **kwargs)

      Init docstring.

      Parameters:
         * **x** (*int*) -- Some integer

         * ***args** (*int*) --

           Some integer

         * ****kwargs** (*int*) --

           Some integer

      Return type:
         None

```
Error pretty printing MatAdd
```py
>>> pprint(MatrixSymbol('x', n, n) + MatrixSymbol('y*', n, n))
Traceback (most recent call last):
  File "./sympy/core/sympify.py", line 368, in sympify
    expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
  File "./sympy/parsing/sympy_parser.py", line 950, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "./sympy/parsing/sympy_parser.py", line 863, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Symbol ('y' )*
                 ^
SyntaxError: unexpected EOF while parsing

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./sympy/printing/pretty/pretty.py", line 2371, in pretty_print
    use_unicode_sqrt_char=use_unicode_sqrt_char))
  File "./sympy/printing/pretty/pretty.py", line 2331, in pretty
    return pp.doprint(expr)
  File "./sympy/printing/pretty/pretty.py", line 62, in doprint
    return self._print(expr).render(**self._settings)
  File "./sympy/printing/printer.py", line 274, in _print
    return getattr(self, printmethod)(expr, *args, **kwargs)
  File "./sympy/printing/pretty/pretty.py", line 828, in _print_MatAdd
    if S(item.args[0]).is_negative:
  File "./sympy/core/sympify.py", line 370, in sympify
    raise SympifyError('could not parse %r' % a, exc)
sympy.core.sympify.SympifyError: Sympify of expression 'could not parse 'y*'' failed, because of exception being raised:
SyntaxError: unexpected EOF while parsing (<string>, line 1)
```

The code shouldn't be using sympify to handle string arguments from MatrixSymbol.

I don't even understand what the code is doing. Why does it omit the `+` when the first argument is negative? This seems to assume that the arguments of MatAdd have a certain form, and that they will always print a certain way if they are negative.
When DEBUG is True, raising Http404 in a path converter's to_python method does not result in a technical response
Description
	
This is the response I get (plain text): 
A server error occurred. Please contact the administrator.
I understand a ValueError should be raised which tells the URL resolver "this path does not match, try next one" but Http404 is what came to my mind intuitively and the error message was not very helpful.
One could also make a point that raising a Http404 should be valid way to tell the resolver "this is indeed the right path but the current parameter value does not match anything so stop what you are doing and let the handler return the 404 page (including a helpful error message when DEBUG is True instead of the default 'Django tried these URL patterns')".
This would prove useful for example to implement a path converter that uses get_object_or_404.
Add a file mode parameter to flask.Config.from_file()
Python 3.11 introduced native TOML support with the `tomllib` package. This could work nicely with the `flask.Config.from_file()` method as an easy way to load TOML config files:

```python
app.config.from_file("config.toml", tomllib.load)
```

However, `tomllib.load()` takes an object readable in binary mode, while `flask.Config.from_file()` opens a file in text mode, resulting in this error:

```
TypeError: File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`
```

We can get around this with a more verbose expression, like loading from a file opened with the built-in `open()` function and passing the `dict` to `app.Config.from_mapping()`:

```python
# We have to repeat the path joining that from_file() does
with open(os.path.join(app.config.root_path, "config.toml"), "rb") as file:
    app.config.from_mapping(tomllib.load(file))
```

But adding a file mode parameter to `flask.Config.from_file()` would enable the use of a simpler expression. E.g.:

```python
app.config.from_file("config.toml", tomllib.load, mode="b")
```
bell(n).limit(n, oo) should be oo rather than bell(oo)
`bell(n).limit(n,oo)` should take the value infinity, but the current output is `bell(oo)`. As the Bell numbers represent the number of partitions of a set, it seems natural that `bell(oo)` should be able to be evaluated rather than be returned unevaluated. This issue is also in line with the recent fixes to the corresponding limit for the Fibonacci numbers and Lucas numbers.

```
from sympy import *
n = symbols('n')
bell(n).limit(n,oo)

Output:
bell(oo)
```

I'm new to Sympy, so I'd appreciate the opportunity to fix this bug myself if that's alright.
Missing parameter validation in Neighbors estimator for float n_neighbors
```python
from sklearn.neighbors import NearestNeighbors
from sklearn.datasets import make_blobs
X, y = make_blobs()
neighbors = NearestNeighbors(n_neighbors=3.)
neighbors.fit(X)
neighbors.kneighbors(X)
```
```
~/checkout/scikit-learn/sklearn/neighbors/binary_tree.pxi in sklearn.neighbors.kd_tree.NeighborsHeap.__init__()

TypeError: 'float' object cannot be interpreted as an integer
```
This should be caught earlier and a more helpful error message should be raised (or we could be lenient and cast to integer, but I think a better error might be better).

We need to make sure that 
```python
neighbors.kneighbors(X, n_neighbors=3.)
```
also works.
Indexed matrix-expression LaTeX printer is not compilable
```python
i, j, k = symbols("i j k")
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
latex((M*N)[i, j])
```

The LaTeX string produced by the last command is:
```
\sum_{i_{1}=0}^{k - 1} M_{i, _i_1} N_{_i_1, j}
```
LaTeX complains about a double subscript `_`. This expression won't render in MathJax either.
Uncertain about content/text vs iter_content(decode_unicode=True/False)
When requesting an application/json document, I'm seeing `next(r.iter_content(16*1024, decode_unicode=True))` returning bytes, whereas `r.text` returns unicode. My understanding was that both should return a unicode object. In essence, I thought "iter_content" was equivalent to "iter_text" when decode_unicode was True. Have I misunderstood something? I can provide an example if needed.

For reference, I'm using python 3.5.1 and requests 2.10.0.

Thanks!
socket.error exception not caught/wrapped in a requests exception (ConnectionError perhaps?)
I just noticed a case where I had a socket reset on me, and was raised to me as a raw socket error as opposed to something like a requests.exceptions.ConnectionError:

```
  File "/home/rtdean/***/***/***/***/***/***.py", line 67, in dir_parse
    root = ElementTree.fromstring(response.text)
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/models.py", line 721, in text
    if not self.content:
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/models.py", line 694, in content
    self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/models.py", line 627, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/response.py", line 240, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/packages/urllib3/response.py", line 187, in read
    data = self._fp.read(amt)
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/httplib.py", line 543, in read
    return self._read_chunked(amt)
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/httplib.py", line 612, in _read_chunked
    value.append(self._safe_read(chunk_left))
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/httplib.py", line 658, in _safe_read
    chunk = self.fp.read(min(amt, MAXAMOUNT))
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/socket.py", line 380, in read
    data = self._sock.recv(left)
  File "/home/rtdean/.pyenv/versions/2.7.6/lib/python2.7/site-packages/gevent-1.0.1-py2.7-linux-x86_64.egg/gevent/socket.py", line 385, in recv
    return sock.recv(*args)
socket.error: [Errno 104] Connection reset by peer
```

Not sure if this is by accident or design... in general, I guess I'd expect a requests exception when using requests, but I can start looking for socket errors and the like as well.
Unroll the iterable for all/any calls to get better reports
Sometime I need to assert some predicate on all of an iterable, and for that the builtin functions `all`/`any` are great - but the failure messages aren't useful at all!
For example - the same test written in three ways:

- A generator expression
```sh                                                                                                                                                                                                                         
    def test_all_even():
        even_stevens = list(range(1,100,2))
>       assert all(is_even(number) for number in even_stevens)
E       assert False
E        +  where False = all(<generator object test_all_even.<locals>.<genexpr> at 0x101f82ed0>)
```
- A list comprehension
```sh
    def test_all_even():
        even_stevens = list(range(1,100,2))
>       assert all([is_even(number) for number in even_stevens])
E       assert False
E        +  where False = all([False, False, False, False, False, False, ...])
```
- A for loop
```sh
    def test_all_even():
        even_stevens = list(range(1,100,2))
        for number in even_stevens:
>           assert is_even(number)
E           assert False
E            +  where False = is_even(1)

test_all_any.py:7: AssertionError
```
The only one that gives a meaningful report is the for loop - but it's way more wordy, and `all` asserts don't translate to a for loop nicely (I'll have to write a `break` or a helper function - yuck)
I propose the assertion re-writer "unrolls" the iterator to the third form, and then uses the already existing reports.

- [x] Include a detailed description of the bug or suggestion
- [x] `pip list` of the virtual environment you are using
```
Package        Version
-------------- -------
atomicwrites   1.3.0  
attrs          19.1.0 
more-itertools 7.0.0  
pip            19.0.3 
pluggy         0.9.0  
py             1.8.0  
pytest         4.4.0  
setuptools     40.8.0 
six            1.12.0 
```
- [x] pytest and operating system versions
`platform darwin -- Python 3.7.3, pytest-4.4.0, py-1.8.0, pluggy-0.9.0`
- [x] Minimal example if possible
sympy.Array([]) fails, while sympy.Matrix([]) works
SymPy 1.4 does not allow to construct empty Array (see code below). Is this the intended behavior?

```
>>> import sympy
KeyboardInterrupt
>>> import sympy
>>> from sympy import Array
>>> sympy.__version__
'1.4'
>>> a = Array([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/dense_ndim_array.py", line 130, in __new__
    return cls._new(iterable, shape, **kwargs)
  File "/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/dense_ndim_array.py", line 136, in _new
    shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
  File "/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/ndim_array.py", line 142, in _handle_ndarray_creation_inputs
    iterable, shape = cls._scan_iterable_shape(iterable)
  File "/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/ndim_array.py", line 127, in _scan_iterable_shape
    return f(iterable)
  File "/Users/hcui7/miniconda3/envs/a/lib/python3.7/site-packages/sympy/tensor/array/ndim_array.py", line 120, in f
    elems, shapes = zip(*[f(i) for i in pointer])
ValueError: not enough values to unpack (expected 2, got 0)
```

@czgdp1807
Wrong hint about recursive relationship.
Description
	 
		(last modified by Matheus Cunha Motta)
	 
When there's more than 2 ForeignKeys in an intermediary model of a m2m field and no through_fields have been set, Django will show an error with the following hint:
hint=(
	'If you want to create a recursive relationship, '
	'use ForeignKey("%s", symmetrical=False, through="%s").'
But 'symmetrical' and 'through' are m2m keyword arguments, not ForeignKey.
This was probably a small mistake where the developer thought ManyToManyField but typed ForeignKey instead. And the symmetrical=False is an outdated requirement to recursive relationships with intermediary model to self, not required since 3.0. I'll provide a PR with a proposed correction shortly after.
Edit: fixed description.
Autoreloader with StatReloader doesn't track changes in manage.py.
Description
	 
		(last modified by Mariusz Felisiak)
	 
This is a bit convoluted, but here we go.
Environment (OSX 10.11):
$ python -V
Python 3.6.2
$ pip -V
pip 19.1.1
$ pip install Django==2.2.1
Steps to reproduce:
Run a server python manage.py runserver
Edit the manage.py file, e.g. add print(): 
def main():
	print('sth')
	os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ticket_30479.settings')
	...
Under 2.1.8 (and prior), this will trigger the auto-reloading mechanism. Under 2.2.1, it won't. As far as I can tell from the django.utils.autoreload log lines, it never sees the manage.py itself.
Module imported twice under import-mode=importlib
In pmxbot/pmxbot@7f189ad, I'm attempting to switch pmxbot off of pkg_resources style namespace packaging to PEP 420 namespace packages. To do so, I've needed to switch to `importlib` for the `import-mode` and re-organize the tests to avoid import errors on the tests.

Yet even after working around these issues, the tests are failing when the effect of `core.initialize()` doesn't seem to have had any effect.

Investigating deeper, I see that initializer is executed and performs its actions (setting a class variable `pmxbot.logging.Logger.store`), but when that happens, there are two different versions of `pmxbot.logging` present, one in `sys.modules` and another found in `tests.unit.test_commands.logging`:

```
=========================================================================== test session starts ===========================================================================
platform darwin -- Python 3.11.1, pytest-7.2.0, pluggy-1.0.0
cachedir: .tox/python/.pytest_cache
rootdir: /Users/jaraco/code/pmxbot/pmxbot, configfile: pytest.ini
plugins: black-0.3.12, mypy-0.10.3, jaraco.test-5.3.0, checkdocs-2.9.0, flake8-1.1.1, enabler-2.0.0, jaraco.mongodb-11.2.1, pmxbot-1122.14.3.dev13+g7f189ad
collected 421 items / 180 deselected / 241 selected                                                                                                                       
run-last-failure: rerun previous 240 failures (skipped 14 files)

tests/unit/test_commands.py E
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> traceback >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

cls = <class 'tests.unit.test_commands.TestCommands'>

    @classmethod
    def setup_class(cls):
        path = os.path.dirname(os.path.abspath(__file__))
        configfile = os.path.join(path, 'testconf.yaml')
        config = pmxbot.dictlib.ConfigDict.from_yaml(configfile)
        cls.bot = core.initialize(config)
>       logging.Logger.store.message("logged", "testrunner", "some text")
E       AttributeError: type object 'Logger' has no attribute 'store'

tests/unit/test_commands.py:37: AttributeError
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PDB post_mortem (IO-capturing turned off) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> /Users/jaraco/code/pmxbot/pmxbot/tests/unit/test_commands.py(37)setup_class()
-> logging.Logger.store.message("logged", "testrunner", "some text")
(Pdb) logging.Logger
<class 'pmxbot.logging.Logger'>
(Pdb) logging
<module 'pmxbot.logging' from '/Users/jaraco/code/pmxbot/pmxbot/pmxbot/logging.py'>
(Pdb) import sys
(Pdb) sys.modules['pmxbot.logging']
<module 'pmxbot.logging' from '/Users/jaraco/code/pmxbot/pmxbot/pmxbot/logging.py'>
(Pdb) sys.modules['pmxbot.logging'] is logging
False
```

I haven't yet made a minimal reproducer, but I wanted to first capture this condition.
Intersection should remove duplicates
```python
>>> Intersection({1},{1},{x})
EmptySet()
>>> Intersection({1},{x})
{1}
```
The answer should be `Piecewise(({1}, Eq(x, 1)), (S.EmptySet, True))` or remain unevaluated.

The routine should give the same answer if duplicates are present; my initial guess is that duplicates should just be removed at the outset of instantiation. Ordering them will produce canonical processing.
'Poly3DCollection' object has no attribute '_facecolors2d'
The following minimal example demonstrates the issue:

```
import numpy as np
import matplotlib.tri as mtri
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

y,x = np.ogrid[1:10:100j, 1:10:100j]
z2 = np.cos(x)**3 - np.sin(y)**2
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = ax.plot_surface(x,y,z2, cmap='hot')
r.get_facecolors()
```

It fails on the last line with the following traceback:

```
AttributeError                            Traceback (most recent call last)
<ipython-input-13-de0f41d662cd> in <module>()
----> 1 r.get_facecolors()

/home/oliver/.virtualenvs/mpl/local/lib/python2.7/site-packages/mpl_toolkits/mplot3d/art3d.pyc in get_facecolors(self)
    634
    635     def get_facecolors(self):
--> 636         return self._facecolors2d
    637     get_facecolor = get_facecolors
    638

AttributeError: 'Poly3DCollection' object has no attribute '_facecolors2d'
```

Tested with mpl versions 1.3.1 and 1.4.2.

Sent here by Benjamin, from the mpl users mailing list (mail with the same title). Sorry for dumping this without more assistance, I'm not yet at a python level where I can help in debugging, I think (well, it seems daunting).
Confusing assertion rewriting message with byte strings
The comparison with assertion rewriting for byte strings is confusing: 
```
    def test_b():
>       assert b"" == b"42"
E       AssertionError: assert b'' == b'42'
E         Right contains more items, first extra item: 52
E         Full diff:
E         - b''
E         + b'42'
E         ?   ++
```

52 is the ASCII ordinal of "4" here.

It became clear to me when using another example:

```
    def test_b():
>       assert b"" == b"1"
E       AssertionError: assert b'' == b'1'
E         Right contains more items, first extra item: 49
E         Full diff:
E         - b''
E         + b'1'
E         ?   +
```

Not sure what should/could be done here.
vectors break pretty printing
```py
In [1]: from sympy.vector import *

In [2]: e = CoordSysCartesian('e')

In [3]: (x/y)**t*e.j
Out[3]:
⎛   t⎞ e_j
⎜⎛x⎞ e_j ⎟
⎜⎜─⎟ ⎟
⎝⎝y⎠ ⎠
```

Also, when it does print correctly, the baseline is wrong (it should be centered).