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

Issue:
non-conda-installed python packages can have missing version information
When reading up metadata out of site-packages, non-conda-installed python packages can sometime be missing version information. When this is the case, we should default to a hard-codes `0.0.0` version. I believe this behavior is consistent with python’s own `python setup.py —version` when no version is actually given in the `setup()` function. 


Discussion:

Resolving patch:
diff --git a/conda/core/prefix_data.py b/conda/core/prefix_data.py
--- a/conda/core/prefix_data.py
+++ b/conda/core/prefix_data.py
@@ -8,6 +8,7 @@
 from os import listdir
 from os.path import basename, isdir, isfile, join, lexists
 
+from .._vendor.auxlib.exceptions import ValidationError
 from ..base.constants import CONDA_TARBALL_EXTENSION, PREFIX_MAGIC_FILE
 from ..base.context import context
 from ..common.compat import JSONDecodeError, itervalues, odict, string_types, with_metaclass
@@ -257,6 +258,16 @@ def _load_site_packages(self):
                 python_record = read_python_record(self.prefix_path, af, python_pkg_record.version)
             except EnvironmentError:
                 continue
+            except ValidationError:
+                import sys
+                exc_type, exc_value, exc_traceback = sys.exc_info()
+                import traceback
+                tb = traceback.format_exception(exc_type, exc_value, exc_traceback)
+                log.warn("Problem reading non-conda package record at %s. Please verify that you "
+                         "still need this, and if so, that this is still installed correctly. "
+                         "Reinstalling this package may help.", af)
+                log.debug("ValidationError: \n%s\n", "\n".join(tb))
+                continue
             if not python_record:
                 continue
             self.__prefix_records[python_record.name] = python_record


Test patch:
Repository: conda/conda

Issue:
Conda Init Bug in v4.6.0b1
While exploring #7881 , I found a small bug in the regex pattern matching at: https://github.com/conda/conda/blob/7a93664267488adc5052efef38614fab537da446/conda/core/initialize.py#L1157-L1166

The regex pattern assumes that I would not have quotes in my already existing value in the registry key. For example, if I have the current value set as...

```
"\path\to\custom\startup.bat" & "\path\to\prev_installation\condabin\conda_hook.bat"
```

... upon `conda init`, it will change the value to:
```
"\path\to\new_installation\condabin\conda_hook.bat"
```

Instead of:
```
"\path\to\custom\startup.bat" & "\path\to\new_installation\condabin\conda_hook.bat"
```


Discussion:

Resolving patch:
diff --git a/conda/core/initialize.py b/conda/core/initialize.py
--- a/conda/core/initialize.py
+++ b/conda/core/initialize.py
@@ -1157,7 +1157,7 @@ def init_cmd_exe_registry(target_path, conda_prefix):
     hook_path = '"%s"' % join(conda_prefix, 'condabin', 'conda_hook.bat')
     replace_str = "__CONDA_REPLACE_ME_123__"
     new_value = re.sub(
-        r'(\".*?conda[-_]hook\.bat\")',
+        r'(\"[^\"]*?conda[-_]hook\.bat\")',
         replace_str,
         prev_value,
         count=1,


Test patch:
Repository: conda/conda

Issue:
nomkl tests running on Windows fail
Appears some `nomkl` feature tests are being run on Windows and [failing on CI]( https://ci.appveyor.com/project/ContinuumAnalyticsFOSS/conda/builds/20408292/job/q40u301c397wpyji?fullLog=true#L1181 ). IIUC `nomkl` does not exist on Windows. So this is as expected. Should these tests be marked as known fails, skipped, or similar?


Discussion:

Resolving patch:
diff --git a/conda/base/context.py b/conda/base/context.py
--- a/conda/base/context.py
+++ b/conda/base/context.py
@@ -105,6 +105,7 @@ def ssl_verify_validation(value):
 class Context(Configuration):
 
     add_pip_as_python_dependency = PrimitiveParameter(True)
+    allow_conda_downgrades = PrimitiveParameter(False)
     allow_cycles = PrimitiveParameter(True)  # allow cyclical dependencies, or raise
     allow_softlinks = PrimitiveParameter(False)
     auto_update_conda = PrimitiveParameter(True, aliases=('self_update',))
@@ -590,6 +591,7 @@ def list_parameters(self):
             'bld_path',
             'conda_build',
             'croot',
+            'allow_conda_downgrades',
             'debug',
             'default_python',
             'dry_run',
diff --git a/conda/history.py b/conda/history.py
--- a/conda/history.py
+++ b/conda/history.py
@@ -233,7 +233,7 @@ def get_user_requests(self):
 
         conda_versions_from_history = tuple(x['conda_version'] for x in res
                                             if 'conda_version' in x)
-        if conda_versions_from_history:
+        if conda_versions_from_history and not context.allow_conda_downgrades:
             minimum_conda_version = sorted(conda_versions_from_history, key=VersionOrder)[-1]
             minimum_major_minor = '.'.join(take(2, minimum_conda_version.split('.')))
             current_major_minor = '.'.join(take(2, CONDA_VERSION.split('.')))


Test patch:
diff --git a/tests/test_create.py b/tests/test_create.py
--- a/tests/test_create.py
+++ b/tests/test_create.py
@@ -805,8 +805,7 @@ def test_only_deps_flag(self):
                 assert package_is_installed(prefix, 'openssl')
             assert package_is_installed(prefix, 'itsdangerous')
 
-    @pytest.mark.xfail(on_win and datetime.now() < datetime(2018, 9, 15),
-                       reason="need to talk with @msarahan about blas patches on Windows",
+    @pytest.mark.xfail(on_win, reason="nomkl not present on windows",
                        strict=True)
     def test_install_features(self):
         with make_temp_env("python=2 numpy=1.13 nomkl") as prefix:
Repository: conda/conda

Issue:
[4.6.0] conda init powershell --all-users
With the new `4.6.0rc1` `conda init powershell` puts the below config in your *user* `$PROFILE`
```powershell
C:\> $PROFILE
C:\Users\dhirschfeld\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
C:\> cat $PROFILE

#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
(& C:\Miniconda3\Scripts\conda.exe shell.powershell hook) | Out-String | Invoke-Expression
#endregion

C:\>
```

If you have an AllUsers install of Miniconda  (e.g. in `C:\Miniconda3`) it would be good to be able to initialize powershell for all users i.e. in the `$PROFILE.AllUsersAllHosts`
```powershell
C:\> $PROFILE.AllUsersAllHosts
C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
```


Discussion:
Might be as simple as changing the below:
https://github.com/conda/conda/blob/1bf5787d01e61eb4c418651fcfd328e5cffbd0d5/conda/core/initialize.py#L463-L495

...to:

```python
if 'powershell' in shells:
    if for_user:
        profile = '$PROFILE.CurrentUserAllHosts'

    if for_system:
        profile = '$PROFILE.AllUsersAllHosts'

    config_path = subprocess_call(
        ('powershell.exe', '-NoProfile', '-Command', profile)
    ).stdout.strip()

    if config_path is not None:
        plan.append({
            'function': init_powershell_user.__name__,
            'kwargs': {
                'target_path': config_path,
                'conda_prefix': conda_prefix,
            }
        })
```

Resolving patch:
diff --git a/conda/core/initialize.py b/conda/core/initialize.py
--- a/conda/core/initialize.py
+++ b/conda/core/initialize.py
@@ -468,6 +468,12 @@ def make_initialize_plan(conda_prefix, shells, for_user, for_system, anaconda_pr
             raise NotImplementedError()
 
     if 'powershell' in shells:
+        if for_user:
+            profile = '$PROFILE.CurrentUserAllHosts'
+
+        if for_system:
+            profile = '$PROFILE.AllUsersAllHosts'
+
         # There's several places PowerShell can store its path, depending
         # on if it's Windows PowerShell, PowerShell Core on Windows, or
         # PowerShell Core on macOS/Linux. The easiest way to resolve it is to
@@ -477,12 +483,12 @@ def find_powershell_paths(*exe_names):
             for exe_name in exe_names:
                 try:
                     yield subprocess_call(
-                        (exe_name, '-NoProfile', '-Command', '$PROFILE')
+                        (exe_name, '-NoProfile', '-Command', profile)
                     ).stdout.strip()
                 except Exception:
                     pass
 
-        config_powershell_paths = tuple(
+        config_powershell_paths = set(
             find_powershell_paths('powershell', 'pwsh', 'pwsh-preview')
         )
 
@@ -496,11 +502,6 @@ def find_powershell_paths(*exe_names):
                     }
                 })
 
-        if for_system:
-            raise NotImplementedError(
-                "PowerShell hooks are only implemented for per-user profiles."
-            )
-
     if 'cmd.exe' in shells:
         if for_user:
             plan.append({


Test patch:
Repository: conda/conda

Issue:
conda config --get throws a traceback
```
(/root/dev) [root@21ca1df2ceaa conda]# conda config --set verbosity 1
(/root/dev) [root@21ca1df2ceaa conda]# conda config --get verbosity

# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

    Traceback (most recent call last):
      File "/root/dev/lib/python3.6/site-packages/conda/exceptions.py", line 1001, in __call__
        return func(*args, **kwargs)
      File "/root/dev/lib/python3.6/site-packages/conda/cli/main.py", line 84, in _main
        exit_code = do_call(args, p)
      File "/root/dev/lib/python3.6/site-packages/conda/cli/conda_argparse.py", line 81, in do_call
        exit_code = getattr(module, func_name)(args, parser)
      File "/root/dev/lib/python3.6/site-packages/conda/cli/main_config.py", line 28, in execute
        execute_config(args, parser)
      File "/root/dev/lib/python3.6/site-packages/conda/cli/main_config.py", line 255, in execute_config
        numitems = len(items)
    TypeError: object of type 'int' has no len()

`$ /root/dev/bin/conda config --get verbosity`
```


Discussion:

Resolving patch:
diff --git a/conda/cli/main_config.py b/conda/cli/main_config.py
--- a/conda/cli/main_config.py
+++ b/conda/cli/main_config.py
@@ -252,7 +252,7 @@ def execute_config(args, parser):
                 json_get[key] = rc_config[key]
                 continue
 
-            if isinstance(rc_config[key], (bool, string_types)):
+            if isinstance(rc_config[key], (bool, int, string_types)):
                 stdout_write(" ".join(("--set", key, text_type(rc_config[key]))))
             else:  # assume the key is a list-type
                 # Note, since conda config --add prepends, these are printed in


Test patch:
Repository: conda/conda

Issue:
activate.d scripts not run on windows if prefix contains unicode
activate.d scripts are not run on windows if the path contains unicode characters.  A test for this is to create environments with and without unicode characters with the `_test_set_env_in_activate_d` package in the `jjhelmus` channel.  When activated the `TEST_VAR` variable should be set to "1".  In environments with unicode characters running the activate.d script fails because of an invalid path in the activation script.


Discussion:

Resolving patch:
diff --git a/conda/activate.py b/conda/activate.py
--- a/conda/activate.py
+++ b/conda/activate.py
@@ -532,8 +532,13 @@ def expand(path):
 
 
 def ensure_binary(value):
+    encoding = 'utf-8'
+    if on_win:
+        import ctypes
+        acp = ctypes.cdll.kernel32.GetACP()
+        encoding = str(acp)
     try:
-        return value.encode('utf-8')
+        return value.encode(encoding)
     except AttributeError:  # pragma: no cover
         # AttributeError: '<>' object has no attribute 'encode'
         # In this case assume already binary type and do nothing
diff --git a/conda/common/compat.py b/conda/common/compat.py
--- a/conda/common/compat.py
+++ b/conda/common/compat.py
@@ -215,7 +215,7 @@ def ensure_text_type(value):
             except ImportError:  # pragma: no cover
                 from pip._vendor.requests.packages.chardet import detect
         encoding = detect(value).get('encoding') or 'utf-8'
-        return value.decode(encoding)
+        return value.decode(encoding, errors='replace')
     except UnicodeEncodeError:  # pragma: no cover
         # it's already text_type, so ignore?
         # not sure, surfaced with tests/models/test_match_spec.py test_tarball_match_specs


Test patch:
diff --git a/tests/test_create.py b/tests/test_create.py
--- a/tests/test_create.py
+++ b/tests/test_create.py
@@ -2156,7 +2156,7 @@ def test_post_link_run_in_env(self):
         test_pkg = '_conda_test_env_activated_when_post_link_executed'
         # a non-unicode name must be provided here as activate.d scripts
         # are not execuated on windows, see https://github.com/conda/conda/issues/8241
-        with make_temp_env(test_pkg, '-c conda-test', name='post_link_test') as prefix:
+        with make_temp_env(test_pkg, '-c conda-test') as prefix:
             assert package_is_installed(prefix, test_pkg)
 
     def test_conda_info_python(self):
Repository: conda/conda

Issue:
conda init keeps modifying powershell profile
Repeated calls to conda init keep modifying profile.ps1 each time.

```
(base) wani@lenovo ~/h/conda ❯❯❯ conda init --all
...
modified      /home/wani/.config/powershell/profile.ps1
...


(base) wani@lenovo ~/h/conda ❯❯❯ conda init --all
...
modified      /home/wani/.config/powershell/profile.ps1
...
```


Discussion:

Resolving patch:
diff --git a/conda/core/initialize.py b/conda/core/initialize.py
--- a/conda/core/initialize.py
+++ b/conda/core/initialize.py
@@ -81,6 +81,11 @@
     r"([\s\S]*?)"
     r"# <<< conda initialize <<<(?:\n|\r\n)?")
 
+CONDA_INITIALIZE_PS_RE_BLOCK = (
+    r"^#region conda initialize(?:\n|\r\n)"
+    r"([\s\S]*?)"
+    r"#endregion(?:\n|\r\n)?")
+
 class Result:
     NEEDS_SUDO = "needs sudo"
     MODIFIED = "modified"
@@ -1371,7 +1376,7 @@ def init_powershell_user(target_path, conda_prefix, reverse):
     # TODO: comment out old ipmos and Import-Modules.
 
     if reverse:
-        profile_content = re.sub(r"\s*\#region conda initialize.*\#endregion",
+        profile_content = re.sub(CONDA_INITIALIZE_PS_RE_BLOCK,
                                  "",
                                  profile_content,
                                  count=1,
@@ -1384,7 +1389,7 @@ def init_powershell_user(target_path, conda_prefix, reverse):
         if "#region conda initialize" not in profile_content:
             profile_content += "\n{}\n".format(conda_initialize_content)
         else:
-            profile_content = re.sub(r"\#region conda initialize.*\#endregion",
+            profile_content = re.sub(CONDA_INITIALIZE_PS_RE_BLOCK,
                                      "__CONDA_REPLACE_ME_123__",
                                      profile_content,
                                      count=1,


Test patch:
Repository: conda/conda

Issue:
Avoid text "failed" when solving environment fails
I recommend avoiding the term "failed" when we try `current_repodata.json` and then fall back to `repodata.json`.  I wonder if this might be better replaced with "failed.  Retrying" or something similar that says "we're going to try something else now instead"

```
(base) mrocklin@dgx15:~$ conda install cudatoolkit
Collecting package metadata (current_repodata.json): done
Solving environment: failed    # <<<------ this might scare users
Collecting package metadata (repodata.json): done
Solving environment: /
```

Just a thought, please ignore if this isn't appropriate.


Discussion:
user perception / UX is always appropriate.  Thanks for the feedback.

Resolving patch:
diff --git a/conda/common/io.py b/conda/common/io.py
--- a/conda/common/io.py
+++ b/conda/common/io.py
@@ -385,7 +385,7 @@ class Spinner(object):
     # spinner_cycle = cycle("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
     spinner_cycle = cycle('/-\\|')
 
-    def __init__(self, message, enabled=True, json=False):
+    def __init__(self, message, enabled=True, json=False, fail_message="failed\n"):
         self.message = message
         self.enabled = enabled
         self.json = json
@@ -395,6 +395,7 @@ def __init__(self, message, enabled=True, json=False):
         self._indicator_length = len(next(self.spinner_cycle)) + 1
         self.fh = sys.stdout
         self.show_spin = enabled and not json and hasattr(self.fh, "isatty") and self.fh.isatty()
+        self.fail_message = fail_message
 
     def start(self):
         if self.show_spin:
@@ -434,7 +435,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
         if not self.json:
             with swallow_broken_pipe:
                 if exc_type or exc_val:
-                    sys.stdout.write("failed\n")
+                    sys.stdout.write(self.fail_message)
                 else:
                     sys.stdout.write("done\n")
                 sys.stdout.flush()
diff --git a/conda/core/solve.py b/conda/core/solve.py
--- a/conda/core/solve.py
+++ b/conda/core/solve.py
@@ -239,8 +239,10 @@ def solve_final_state(self, update_modifier=NULL, deps_modifier=NULL, prune=NULL
                      context.json):
             ssc = self._collect_all_metadata(ssc)
 
+        fail_message = ("failed\n" if self._repodata_fn == REPODATA_FN else "failed with %s, "
+                        "will retry with next repodata source.\n" % self._repodata_fn)
         with Spinner("Solving environment", not context.verbosity and not context.quiet,
-                     context.json):
+                     context.json, fail_message=fail_message):
             ssc = self._remove_specs(ssc)
             ssc = self._add_specs(ssc)
             solution_precs = copy.copy(ssc.solution_precs)


Test patch:
Repository: conda/conda

Issue:
Can't downgrade python: "No module named 'distutils.spawn'"
Issue (conda-forge issue: https://github.com/conda-forge/conda-forge.github.io/issues/805)

I'm not sure whether it is a CF or conda issue, but it only occurs after running conda update --all with conda-forge channel added.

Here is a Dockerfile to reproduce:

```
FROM continuumio/miniconda3

RUN conda config --add channels conda-forge && \
    conda config --set channel_priority strict && \
    conda update --all

RUN conda install python=2.7
```

Fails with:

```
Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
ERROR conda.core.link:_execute(637): An error occurred while installing package 'conda-forge::ipaddress-1.0.22-py_1'.
ModuleNotFoundError("No module named 'distutils.spawn'")
Attempting to roll back.

Rolling back transaction: ...working... done

ModuleNotFoundError("No module named 'distutils.spawn'")
()
```
The failing package varies based on the python version downgraded to, with python=3.6:
```
ERROR conda.core.link:_execute(637): An error occurred while installing package 'conda-forge::tqdm-4.32.2-py_0'.
ModuleNotFoundError("No module named 'distutils.spawn'")
Attempting to roll back.

Rolling back transaction: ...working... done

ModuleNotFoundError("No module named 'distutils.spawn'")
()
```

Tried both with and without conda config --set channel_priority strict, same outcome.




Discussion:

Resolving patch:
diff --git a/conda/common/path.py b/conda/common/path.py
--- a/conda/common/path.py
+++ b/conda/common/path.py
@@ -14,6 +14,7 @@
 from .. import CondaError
 from .._vendor.auxlib.decorators import memoize
 from .._vendor.toolz import accumulate, concat, take
+from distutils.spawn import find_executable
 
 try:
     # Python 3
@@ -308,7 +309,6 @@ def _translation(found_path):  # NOQA
 
 
 def which(executable):
-    from distutils.spawn import find_executable
     return find_executable(executable)
 
 


Test patch:
Repository: conda/conda

Issue:
Similar packages in pkgs/main and pkgs/free are considered the same package
If `pkgs/main` and `pkgs/free` contain a package with the same subdir, name, version, build_number and build [conda considers](https://github.com/conda/conda/blob/4.6.6/conda/models/records.py#L253-L266) these packages identical and will not respect the sub-channel priority (main > free).  

A good example of this is the blas=1.0=mkl packages for the linux-64 platform.

Additionally packages in `pkgs/free` and `pkg/main` with the [same name, version and build](https://github.com/conda/conda/blob/4.6.6/conda/models/records.py#L272-L273) will be considered by the [solver](https://github.com/conda/conda/blob/4.6.6/conda/resolve.py#L612-L620) to be the same even if they have a different build_number.  This occurs with the blas=1.0=openblas packages for the linux-ppc64le platform which makes them un-installable.

cf: #8301 #8236 


Discussion:

Resolving patch:
diff --git a/conda/core/index.py b/conda/core/index.py
--- a/conda/core/index.py
+++ b/conda/core/index.py
@@ -90,14 +90,26 @@ def _supplement_index_with_prefix(index, prefix):
     assert prefix
     for prefix_record in PrefixData(prefix).iter_records():
         if prefix_record in index:
-            # The downloaded repodata takes priority, so we do not overwrite.
-            # We do, however, copy the link information so that the solver (i.e. resolve)
-            # knows this package is installed.
             current_record = index[prefix_record]
-            link = prefix_record.get('link') or EMPTY_LINK
-            index[prefix_record] = PrefixRecord.from_objects(
-                current_record, prefix_record, link=link
-            )
+            if current_record.channel == prefix_record.channel:
+                # The downloaded repodata takes priority, so we do not overwrite.
+                # We do, however, copy the link information so that the solver (i.e. resolve)
+                # knows this package is installed.
+                link = prefix_record.get('link') or EMPTY_LINK
+                index[prefix_record] = PrefixRecord.from_objects(
+                    current_record, prefix_record, link=link
+                )
+            else:
+                # If the local packages channel information does not agree with
+                # the channel information in the index then they are most
+                # likely referring to different packages.  This can occur if a
+                # multi-channel changes configuration, e.g. defaults with and
+                # without the free channel. In this case we need to fake the
+                # channel data for the existing package.
+                prefix_channel = prefix_record.channel
+                prefix_channel._Channel__canonical_name = prefix_channel.url()
+                del prefix_record._PackageRecord__pkey
+                index[prefix_record] = prefix_record
         else:
             # If the package is not in the repodata, use the local data.
             # If the channel is known but the package is not in the index, it


Test patch: