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

Issue:
Plotting bug in some documentation examples
I am not sure if this is related to the recent merge of #2738  or not, but some examples have weird outputs like [this one](https://7647-1235740-gh.circle-artifacts.com/0/dev/auto_examples/01_plotting/plot_demo_plotting.html#sphx-glr-auto-examples-01-plotting-plot-demo-plotting-py) or [this one](https://7647-1235740-gh.circle-artifacts.com/0/dev/auto_examples/plot_3d_and_4d_niimg.html#sphx-glr-auto-examples-plot-3d-and-4d-niimg-py):

![issue](https://user-images.githubusercontent.com/2639645/123773016-a0584700-d8cc-11eb-9938-03dbb1af8ce8.png)



Discussion:

Resolving patch:
diff --git a/nilearn/plotting/img_plotting.py b/nilearn/plotting/img_plotting.py
--- a/nilearn/plotting/img_plotting.py
+++ b/nilearn/plotting/img_plotting.py
@@ -402,7 +402,8 @@ def load(self):
             anat_img = reorder_img(anat_img)
             data = get_data(anat_img)
             data = data.astype(np.float64)
-            anat_mask = ndimage.morphology.binary_fill_holes(data > 0)
+            anat_mask = ndimage.morphology.binary_fill_holes(
+                data > np.finfo(float).eps)
             data = np.ma.masked_array(data, np.logical_not(anat_mask))
             self._affine = anat_img.affine
             self.data = data


Test patch:
Repository: nilearn/nilearn

Issue:
syntax error in glm
<!--Provide a brief description of the bug.-->

#2532 introduced a syntax error that is breaking the MNE-Python CIs.  Specifically:

https://github.com/nilearn/nilearn/blob/f9deafe828dc21d5d4dd54b772da820ee1f4cac5/nilearn/glm/first_level/first_level.py#L147

leads to this in our documentation CI build:

```
Traceback (most recent call last):
  File "/home/circleci/project/tutorials/inverse/20_dipole_fit.py", line 24, in <module>
    from nilearn.plotting import plot_anat
  File "/home/circleci/.local/lib/python3.8/site-packages/nilearn/plotting/__init__.py", line 51, in <module>
    from .matrix_plotting import (plot_matrix, plot_contrast_matrix,
  File "/home/circleci/.local/lib/python3.8/site-packages/nilearn/plotting/matrix_plotting.py", line 13, in <module>
    from nilearn.glm.contrasts import expression_to_contrast_vector
  File "/home/circleci/.local/lib/python3.8/site-packages/nilearn/glm/__init__.py", line 31, in <module>
    from nilearn.glm import first_level
  File "/home/circleci/.local/lib/python3.8/site-packages/nilearn/glm/first_level/__init__.py", line 6, in <module>
    from nilearn.glm.first_level.first_level import (
  File "/home/circleci/.local/lib/python3.8/site-packages/nilearn/glm/first_level/first_level.py", line 147
    if ((noise_model[:2] != 'ar') and (noise_model is not 'ols')):
                                       ^
SyntaxError: "is not" with a literal. Did you mean "!="?
```

Nilearn version: looks like our CI installs 0.8.0

cc @rob-luke 



Discussion:

Resolving patch:
diff --git a/nilearn/glm/first_level/first_level.py b/nilearn/glm/first_level/first_level.py
--- a/nilearn/glm/first_level/first_level.py
+++ b/nilearn/glm/first_level/first_level.py
@@ -144,7 +144,7 @@ def run_glm(Y, X, noise_model='ar1', bins=100, n_jobs=1, verbose=0):
 
     """
     acceptable_noise_models = ['ols', 'arN']
-    if ((noise_model[:2] != 'ar') and (noise_model is not 'ols')):
+    if ((noise_model[:2] != 'ar') and (noise_model != 'ols')):
         raise ValueError(
             "Acceptable noise models are {0}. You provided "
             "'noise_model={1}'".format(acceptable_noise_models,


Test patch:
Repository: nilearn/nilearn

Issue:
Sphinx-gallery duplicating report images
<!--Describe your proposed enhancement in detail.-->

Recent updates to sphinx-gallery seem to have inserted duplicate images of the report output just above the report object itself, for example [here](https://nilearn.github.io/auto_examples/06_manipulating_images/plot_mask_computation.html#computing-a-mask-from-the-background).

Fixing this may be as simple as not calling the report on its own line, but to be confirmed !

<!--List any pages that would be impacted by the enhancement.-->
### Affected pages

Any page that includes a NiftiMasker report object.


Discussion:

Resolving patch:
diff --git a/nilearn/input_data/nifti_labels_masker.py b/nilearn/input_data/nifti_labels_masker.py
--- a/nilearn/input_data/nifti_labels_masker.py
+++ b/nilearn/input_data/nifti_labels_masker.py
@@ -221,6 +221,7 @@ def _reporting(self):
 
         """
         try:
+            import matplotlib.pyplot as plt
             from nilearn import plotting
         except ImportError:
             with warnings.catch_warnings():
@@ -288,6 +289,7 @@ def _reporting(self):
                 display = plotting.plot_img(img,
                                             black_bg=False,
                                             cmap='CMRmap_r')
+                plt.close()
                 display.add_contours(labels_image,
                                      filled=False,
                                      linewidths=3)
@@ -301,6 +303,7 @@ def _reporting(self):
                 warnings.warn(msg)
                 self._report_content['warning_message'] = msg
                 display = plotting.plot_roi(labels_image)
+                plt.close()
 
             # If we have a mask, show its contours
             if self._reporting_data['mask'] is not None:
diff --git a/nilearn/input_data/nifti_masker.py b/nilearn/input_data/nifti_masker.py
--- a/nilearn/input_data/nifti_masker.py
+++ b/nilearn/input_data/nifti_masker.py
@@ -301,6 +301,7 @@ def _reporting(self):
         """
         try:
             from nilearn import plotting
+            import matplotlib.pyplot as plt
         except ImportError:
             with warnings.catch_warnings():
                 mpl_unavail_msg = ('Matplotlib is not imported! '
@@ -335,6 +336,7 @@ def _reporting(self):
         init_display = plotting.plot_img(img,
                                          black_bg=False,
                                          cmap='CMRmap_r')
+        plt.close()
         if mask is not None:
             init_display.add_contours(mask, levels=[.5], colors='g',
                                       linewidths=2.5)
@@ -358,6 +360,7 @@ def _reporting(self):
             final_display = plotting.plot_img(resampl_img,
                                               black_bg=False,
                                               cmap='CMRmap_r')
+            plt.close()
             final_display.add_contours(resampl_mask, levels=[.5],
                                        colors='g', linewidths=2.5)
 


Test patch:
Repository: nilearn/nilearn

Issue:
Modification of dictionary returned by locals()
This code from https://github.com/nilearn/nilearn/blob/ac1a934/nilearn/plotting/cm.py#L221-L222:
```python
# Save colormaps in the scope of the module
locals().update(_cmap_d)
```
raises an [LGTM alert](https://lgtm.com/projects/g/nilearn/nilearn/snapshot/d520eb8468e57b591fe97798f038a56ab134679b/files/nilearn/plotting/cm.py#x63244eecb7d9ea77:1):
> Modification of dictionary returned by locals()
> 
> Modification of the locals() dictionary will have no effect on the local variables.

And indeed, after reading:
* [Update locals from inside a function](https://stackoverflow.com/questions/30295163/update-locals-from-inside-a-function#67367191)
* [Built-in Functions](https://docs.python.org/3/library/functions.html#locals)
  >Update and return a dictionary representing the current local symbol table. Free variables are returned by [`locals()`](https://docs.python.org/3/library/functions.html#locals) when it is called in function blocks, but not in class blocks. Note that at the module level, [`locals()`](https://docs.python.org/3/library/functions.html#locals) and [`globals()`](https://docs.python.org/3/library/functions.html#globals) are the same dictionary.

I suggest changing `locals()` → `globals()` to make the intent clear, since this happens at module level.

### Expected behavior

No LGTM warning.

### Actual behavior

Raises an LGTM warning:
https://lgtm.com/projects/g/nilearn/nilearn/snapshot/d520eb8468e57b591fe97798f038a56ab134679b/files/nilearn/plotting/cm.py#x63244eecb7d9ea77:1


Discussion:

Resolving patch:
diff --git a/nilearn/plotting/cm.py b/nilearn/plotting/cm.py
--- a/nilearn/plotting/cm.py
+++ b/nilearn/plotting/cm.py
@@ -219,7 +219,7 @@ def _revcmap(data):
     'videen_style', videen_style)
 
 # Save colormaps in the scope of the module
-locals().update(_cmap_d)
+globals().update(_cmap_d)
 # Register cmaps in matplotlib too
 for k, v in _cmap_d.items():
     try:  # "bwr" is in latest matplotlib


Test patch:
Repository: nilearn/nilearn

Issue:
Variable defined multiple times
This code from [`nilearn/_utils/numpy_conversions.py`](https://github.com/nilearn/nilearn/blob/ac1a934/nilearn/_utils/numpy_conversions.py#L106-L107) sets `ret` twice:
```python
                ret = np.array(arr, copy=True)
                ret = _asarray(arr, dtype=dtype, order=order)
```
Perhaps the intent was::
```python
                ret = np.array(arr, copy=True)
                ret = _asarray(ret, dtype=dtype, order=order)
```



Discussion:

Resolving patch:
diff --git a/nilearn/_utils/numpy_conversions.py b/nilearn/_utils/numpy_conversions.py
--- a/nilearn/_utils/numpy_conversions.py
+++ b/nilearn/_utils/numpy_conversions.py
@@ -104,7 +104,7 @@ def as_ndarray(arr, copy=False, dtype=None, order='K'):
                 # Changing order while reading through a memmap is incredibly
                 # inefficient.
                 ret = np.array(arr, copy=True)
-                ret = _asarray(arr, dtype=dtype, order=order)
+                ret = _asarray(ret, dtype=dtype, order=order)
 
     elif isinstance(arr, np.ndarray):
         ret = _asarray(arr, dtype=dtype, order=order)


Test patch:
Repository: nilearn/nilearn

Issue:
LGTM.com recommendation: `masking._load_mask_img()`
### Expected behavior

See LGTM.com recommendation:
https://lgtm.com/projects/g/nilearn/nilearn/snapshot/b08a3f3e20dc2ff1608d8d556496ab56bbf3f63a/files/nilearn/input_data/nifti_labels_masker.py#xa8f5a03b806d5a87:1

Either remove the call to `masking._load_mask_img()`, or do not store the return values in variables (or add a `noqa` but unfortunately LGTM.com fails to interpret `noqa` correctly as can be seen in github/codeql#6528):
https://github.com/nilearn/nilearn/blob/60d6746671a36f7538ff59e23b0378253ccd8c10/nilearn/input_data/nifti_labels_masker.py#L370

Also, the documentation of `masking._load_mask_img()` should describe the second item of the returned pair **`mask, mask_img.affine`**:
https://github.com/nilearn/nilearn/blob/60d6746671a36f7538ff59e23b0378253ccd8c10/nilearn/masking.py#L42-L46

### Actual behavior

It's not clear why `masking._load_mask_img()` is called, if the resulting mask is not used. My guess is that the idea is to check the mask is valid (a `ValueError` is raised if it is not valid). If so, it would be nice to document that. Can you confirm?
https://github.com/nilearn/nilearn/blob/60d6746671a36f7538ff59e23b0378253ccd8c10/nilearn/masking.py#L30-L31




Discussion:
Thanks for opening this @DimitriPapadopoulos 
I think you're right, `_load_mask_img` is "only" called in order to perform some checks making sure the mask is valid.
Since we don't need the return values, we can assign them to "_" or not assign them at all.
We can add a small comment but I don't think we need to add a lot of explanations since the docstring of `_load_mask_img` is already explicit enough:

https://github.com/nilearn/nilearn/blob/60d6746671a36f7538ff59e23b0378253ccd8c10/nilearn/masking.py#L30-L32

I agree that we should fix the return values in the docstring though, even if it is a private function.

Resolving patch:
diff --git a/nilearn/input_data/nifti_labels_masker.py b/nilearn/input_data/nifti_labels_masker.py
--- a/nilearn/input_data/nifti_labels_masker.py
+++ b/nilearn/input_data/nifti_labels_masker.py
@@ -367,7 +367,8 @@ def fit(self, imgs=None, y=None):
                 raise ValueError("Invalid value for resampling_target: " +
                                  str(self.resampling_target))
 
-            mask_data, mask_affine = masking._load_mask_img(self.mask_img_)
+            # Just check that the mask is valid
+            masking._load_mask_img(self.mask_img_)
 
         if not hasattr(self,
                        '_resampled_labels_img_'):
diff --git a/nilearn/masking.py b/nilearn/masking.py
--- a/nilearn/masking.py
+++ b/nilearn/masking.py
@@ -43,6 +43,9 @@ def _load_mask_img(mask_img, allow_empty=False):
     -------
     mask: numpy.ndarray
         boolean version of the mask
+
+    mask_affine: None or (4,4) array-like
+        affine of the mask
     """
     mask_img = _utils.check_niimg_3d(mask_img)
     mask = _safe_get_data(mask_img, ensure_finite=True)


Test patch:
Repository: nilearn/nilearn

Issue:
Address deprecations in joblib
<pre>
/home/circleci/project/nilearn/_utils/cache_mixin.py:232: DeprecationWarning: The 'cachedir' attribute has been deprecated in version 0.12 and will be removed in version 0.14.
Use os.path.join(memory.location, 'joblib') attribute instead.
</pre>
The right solution is to test on the version of scikit-learn: for versions >= 0.20 we should use memory.location, and for versions below we should use memory.cachedir.


Discussion:
Related to #2090 

Resolving patch:
diff --git a/nilearn/regions/rena_clustering.py b/nilearn/regions/rena_clustering.py
--- a/nilearn/regions/rena_clustering.py
+++ b/nilearn/regions/rena_clustering.py
@@ -495,7 +495,7 @@ def fit(self, X, y=None):
                              % type(self.mask_img))
 
         if self.memory is None or isinstance(self.memory, str):
-            self.memory_ = Memory(cachedir=self.memory,
+            self.memory_ = Memory(location=self.memory,
                                   verbose=max(0, self.verbose - 1))
         else:
             self.memory_ = self.memory


Test patch:
diff --git a/nilearn/regions/tests/test_rena_clustering.py b/nilearn/regions/tests/test_rena_clustering.py
--- a/nilearn/regions/tests/test_rena_clustering.py
+++ b/nilearn/regions/tests/test_rena_clustering.py
@@ -32,7 +32,7 @@ def test_rena_clustering():
     assert 10 == rena.n_clusters_
     assert X.shape == X_compress.shape
 
-    memory = Memory(cachedir=None)
+    memory = Memory(location=None)
     rena = ReNA(mask_img, n_clusters=-2, memory=memory)
     pytest.raises(ValueError, rena.fit, X)
Repository: nilearn/nilearn

Issue:
[MAINT] Test with Python 3.10



Discussion:

Resolving patch:
diff --git a/nilearn/surface/surface.py b/nilearn/surface/surface.py
--- a/nilearn/surface/surface.py
+++ b/nilearn/surface/surface.py
@@ -4,7 +4,8 @@
 import os
 import warnings
 import gzip
-from collections import (namedtuple, Mapping)
+from collections import namedtuple
+from collections.abc import Mapping
 
 import numpy as np
 from scipy import sparse, interpolate


Test patch:
diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml
--- a/.github/workflows/testing.yml
+++ b/.github/workflows/testing.yml
@@ -63,7 +63,7 @@ jobs:
         fail-fast: false
         matrix:
             os: ["ubuntu-latest", "macos-latest"]
-            python-version: ["3.7", "3.8", "3.9"]
+            python-version: ["3.7", "3.8", "3.9", "3.10"]
     name: ${{ matrix.os }} with Python ${{ matrix.python-version }} and latest package versions
     defaults:
       run:
Repository: nilearn/nilearn

Issue:
Timeline for dropping Nibabel 2.x support
With the Nibabel 3.x release series, [`Pathlike`](https://docs.python.org/3/library/os.html#os.PathLike) objects are now directly supported by Nibabel. We currently do not support `Pathlike` objects, however, (for an example, see [`load_niimg`](https://github.com/nilearn/nilearn/blob/927976dad301ff729d3e695aef0aad7a9be53084/nilearn/_utils/niimg.py#L95)) presumably to maintain compatibility with Nibabel 2.x. 

I know there was a lot of discussion about updating Nilearn to handle deprecations that came with the Nibabel 3.x release series (see #2155 and #2172), but I'm unclear on how long we plan to continue supporting older versions of Nibabel. Since we're preparing to cut our own 0.7.x release, I thought it might be a good time to start the discussion !


Discussion:
Nibabel 3.x is till much too recent (nov 2019) for us to drop older versions I'm afraid. 
Yes, sorry, I didn't meant to suggest we should drop it for the 0.7.x release ! Just in thinking about release cycles more generally, I'm wondering if we have a timeline in mind here.

Maybe this is a broader question on when we drop support for older libraries !
I propose to have a 2 years margin, e.g. drop support for nibabel 2.x >= nov 2021 
?

Resolving patch:
diff --git a/nilearn/__init__.py b/nilearn/__init__.py
--- a/nilearn/__init__.py
+++ b/nilearn/__init__.py
@@ -65,32 +65,8 @@ def _python_deprecation_warnings():
         _py36_deprecation_warning()
 
 
-def _nibabel2_deprecation_warning():
-    msg = ('Support for Nibabel 2.x is deprecated and will stop '
-           'in release 0.9.0. Please consider upgrading to '
-           'Nibabel 3.x.')
-    warnings.filterwarnings('once', message=msg)
-    warnings.warn(message=msg,
-                  category=FutureWarning,
-                  stacklevel=3)
-
-
-def _nibabel_deprecation_warnings():
-    """Give a deprecation warning is the version of
-    Nibabel is < 3.0.0.
-    """
-    # Nibabel should be installed or we would
-    # have had an error when calling
-    # _check_module_dependencies
-    dist = pkg_resources.get_distribution('nibabel')
-    nib_version = LooseVersion(dist.version)
-    if nib_version < '3.0':
-        _nibabel2_deprecation_warning()
-
-
 _check_module_dependencies()
 _python_deprecation_warnings()
-_nibabel_deprecation_warnings()
 
 
 # Temporary work around to address formatting issues in doc tests


Test patch:
Repository: nilearn/nilearn

Issue:
Use bibtex in nilearn/regions
Convert references in `nilearn/regions/region_extractor.py` to use footcite / footbibliography.
See #2759 


Discussion:

Resolving patch:
diff --git a/nilearn/regions/region_extractor.py b/nilearn/regions/region_extractor.py
--- a/nilearn/regions/region_extractor.py
+++ b/nilearn/regions/region_extractor.py
@@ -253,7 +253,7 @@ class RegionExtractor(NiftiMapsMasker):
     Particularly, to show that each decomposed brain maps can be
     used to focus on a target specific Regions of Interest analysis.
 
-    See [1]_.
+    See :footcite:`abraham:hal-01093944`.
 
     .. versionadded:: 0.2
 
@@ -353,9 +353,7 @@ class RegionExtractor(NiftiMapsMasker):
 
     References
     ----------
-    .. [1] Abraham et al. "Region segmentation for sparse decompositions:
-       better brain parcellations from rest fMRI", Sparsity Techniques in
-       Medical Imaging, Sep 2014, Boston, United States. pp.8
+    .. footbibliography::
 
     See Also
     --------


Test patch:
Repository: nilearn/nilearn

Issue:
Scipy deprication warning from `RegionExtractor`
Warning message:
```
<decorator-gen-7>:2: DeprecationWarning: scipy.sparse.linalg.cg called without specifying `atol`. 
The default value will be changed in a future release. For compatibility, specify a value for `atol` explicitly, e.g., ``cg(..., atol=0)``, or to retain the old behavior ``cg(..., atol='legacy')``
```
Can trace to this line
https://github.com/nilearn/nilearn/blob/db596cbed3ccba56328453bd15cfd29ba05d7c04/nilearn/_utils/segmentation.py#L343

I am not sure what's the magnitude of impact of this. Can try to have a look.


Discussion:
I would simply use `atol='legacy'`


Resolving patch:
diff --git a/nilearn/_utils/segmentation.py b/nilearn/_utils/segmentation.py
--- a/nilearn/_utils/segmentation.py
+++ b/nilearn/_utils/segmentation.py
@@ -340,7 +340,7 @@ def _solve_cg(lap_sparse, B, tol):
     lap_sparse = lap_sparse.tocsc()
     X = []
     for i in range(len(B)):
-        x0 = cg(lap_sparse, -B[i].todense(), tol=tol)[0]
+        x0 = cg(lap_sparse, -B[i].todense(), tol=tol, atol='legacy')[0]
         X.append(x0)
 
     X = np.array(X)


Test patch:
Repository: nilearn/nilearn

Issue:
Confusing Documentation in new_img_like
I think there is some slightly confusing language in the docstring of `new_img_like`. The Parameters list indicates a copy_header parameter to indicate whether the header is copied, but the Returns section indicates "A loaded image with the same type _(and header)_ as the reference image." (emphasis mine). I think it would be more clear to say "A loaded image with the same _file_ type (and, _optionally_ header) as the reference image."
The reason this is critical is that in nibabel, the header data type will override the data type of the numpy array being held (at least for the common Nifti1Image). Due to a number of changes, this is a little more critical (numpy uses 64-bit by default, whereas previously it was 32-bit, and yet AFNI, FSL, and freesurfer all do not support 64-bit integer data).
Somebody could easily scan the "Returns" field and not the "Parameters" field (certainly not a developer like myself, no, never!) and then mistakenly believe that the header will be copied, and therefore that the output data type of the array will match the original header.

Relevant docstring:
https://github.com/nilearn/nilearn/blob/1607b52458c28953a87bbe6f42448b7b4e30a72f/nilearn/image/image.py#L699-L720


Discussion:

Resolving patch:
diff --git a/nilearn/image/image.py b/nilearn/image/image.py
--- a/nilearn/image/image.py
+++ b/nilearn/image/image.py
@@ -697,7 +697,8 @@ def new_img_like(ref_niimg, data, affine=None, copy_header=False):
     Returns
     -------
     Niimg-like object
-        A loaded image with the same type (and header) as the reference image.
+        A loaded image with the same file type (and, optionally, header)
+        as the reference image.
 
     """
     # Hand-written loading code to avoid too much memory consumption


Test patch:
Repository: nilearn/nilearn

Issue:
get_cluster_table returns inconsistent result depending on `cluster_threshold`
<!--Provide a brief description of the bug.-->


<!--Please fill in the following information, to the best of your ability.-->
Nilearn version: 0.9.0

### Expected behavior
The example below should return identical information for the large clusters (> 10 voxels)

### Actual behavior
I does not

### Steps and code to reproduce bug

```
from nilearn import datasets
motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0]
from nilearn.reporting import get_clusters_table
threshold = 3.0
table1 = get_clusters_table(stat_img, threshold, cluster_threshold=10)
table2 = get_clusters_table(stat_img, threshold, cluster_threshold=0)
print(table1)
print(table2)
```



Discussion:

Resolving patch:
diff --git a/nilearn/image/image.py b/nilearn/image/image.py
--- a/nilearn/image/image.py
+++ b/nilearn/image/image.py
@@ -795,7 +795,7 @@ def _apply_cluster_size_threshold(arr, cluster_threshold, copy=True):
     conn_mat[1, :, 1] = 1
     conn_mat[1, 1, :] = 1
 
-    for sign in np.sign(arr):
+    for sign in np.unique(np.sign(arr)):
         # Binarize using one-sided cluster-defining threshold
         binarized = ((arr * sign) > 0).astype(int)
 


Test patch:
diff --git a/nilearn/image/tests/test_image.py b/nilearn/image/tests/test_image.py
--- a/nilearn/image/tests/test_image.py
+++ b/nilearn/image/tests/test_image.py
@@ -585,7 +585,7 @@ def test_threshold_img_with_cluster_threshold():
         copy=True,
     )
     assert np.array_equal(np.unique(thr_img.get_fdata()), np.array([-4, 0, 4]))
-
+    assert np.sum(thr_img.get_fdata() == 4) == 8
     # With a cluster threshold of 5 we get clusters with |values| > 0.5 and
     # cluster sizes > 5
     thr_img = threshold_img(