gurudesh/pytracebugs huggingface dataset:
# Buggy code
def add_binstar_token(url):
    clean_url, token = split_anaconda_token(url)
    if not token and context.add_anaconda_token:
        for binstar_url, token in iteritems(read_binstar_tokens()):
            if clean_url.startswith(binstar_url):
                log.debug("Adding anaconda token for url <%s>", clean_url)
                from conda.models.channel import Channel

                channel = Channel(clean_url)
                channel.token = token
                return channel.url(with_credentials=True)
    return url


# Traceback (ImportError)
$ conda -h
An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues



Traceback (most recent call last):
File "/home/vmrguser/anaconda2/bin/conda", line 6, in <module>
sys.exit(conda.cli.main())
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/cli/main.py", line 164, in main
return conda_exception_handler(_main, *args)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 589, in conda_exception_handler
print_unexpected_error_message(e)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 543, in print_unexpected_error_message
info_stdout, info_stderr = get_info()
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 513, in get_info
args.func(args, p)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/cli/main_info.py", line 148, in execute
from conda.api import get_index
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/api.py", line 1, in <module>
from .core.index import get_index
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/core/index.py", line 9, in <module>
from .repodata import collect_all_repodata
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/core/repodata.py", line 21, in <module>
from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: No module named packages.urllib3.exceptions

# Fixed code
def add_binstar_token(url):
    clean_url, token = split_anaconda_token(url)
    if not token and context.add_anaconda_token:
        for binstar_url, token in iteritems(read_binstar_tokens()):
            if clean_url.startswith(binstar_url):
                log.debug("Adding anaconda token for url <%s>", clean_url)
                from .models.channel import Channel

                channel = Channel(clean_url)
                channel.token = token
                return channel.url(with_credentials=True)
    return url
# Buggy code
def print_conda_exception(exception):
    from conda.base.context import context

    stdoutlogger = getLogger("stdout")
    stderrlogger = getLogger("stderr")
    if context.json:
        import json

        stdoutlogger.info(
            json.dumps(
                exception.dump_map(), indent=2, sort_keys=True, cls=EntityEncoder
            )
        )
    else:
        stderrlogger.info("\n\n%r", exception)


# Traceback (ImportError)
$ conda -h
An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues



Traceback (most recent call last):
File "/home/vmrguser/anaconda2/bin/conda", line 6, in <module>
sys.exit(conda.cli.main())
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/cli/main.py", line 164, in main
return conda_exception_handler(_main, *args)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 589, in conda_exception_handler
print_unexpected_error_message(e)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 543, in print_unexpected_error_message
info_stdout, info_stderr = get_info()
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 513, in get_info
args.func(args, p)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/cli/main_info.py", line 148, in execute
from conda.api import get_index
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/api.py", line 1, in <module>
from .core.index import get_index
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/core/index.py", line 9, in <module>
from .repodata import collect_all_repodata
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/core/repodata.py", line 21, in <module>
from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: No module named packages.urllib3.exceptions

# Fixed code
def print_conda_exception(exception):
    from .base.context import context

    stdoutlogger = getLogger("stdout")
    stderrlogger = getLogger("stderr")
    if context.json:
        import json

        stdoutlogger.info(
            json.dumps(
                exception.dump_map(), indent=2, sort_keys=True, cls=EntityEncoder
            )
        )
    else:
        stderrlogger.info("\n\n%r", exception)
# Buggy code
def handle_exception(e):
    if isinstance(e, CondaExitZero):
        return 0
    elif isinstance(e, CondaError):
        from conda.base.context import context

        if context.debug or context.verbosity > 0:
            print_unexpected_error_message(e)
        else:
            print_conda_exception(e)
        return 1
    else:
        print_unexpected_error_message(e)
        return 1


# Traceback (ImportError)
$ conda -h
An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues



Traceback (most recent call last):
File "/home/vmrguser/anaconda2/bin/conda", line 6, in <module>
sys.exit(conda.cli.main())
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/cli/main.py", line 164, in main
return conda_exception_handler(_main, *args)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 589, in conda_exception_handler
print_unexpected_error_message(e)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 543, in print_unexpected_error_message
info_stdout, info_stderr = get_info()
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/exceptions.py", line 513, in get_info
args.func(args, p)
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/cli/main_info.py", line 148, in execute
from conda.api import get_index
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/api.py", line 1, in <module>
from .core.index import get_index
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/core/index.py", line 9, in <module>
from .repodata import collect_all_repodata
File "/home/vmrguser/anaconda2/lib/python2.7/site-packages/conda/core/repodata.py", line 21, in <module>
from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: No module named packages.urllib3.exceptions

# Fixed code
def handle_exception(e):
    if isinstance(e, CondaExitZero):
        return 0
    elif isinstance(e, CondaError):
        from .base.context import context

        if context.debug or context.verbosity > 0:
            print_unexpected_error_message(e)
        else:
            print_conda_exception(e)
        return 1
    else:
        print_unexpected_error_message(e)
        return 1
# Buggy code
def clone(src_arg, dst_prefix, json=False, quiet=False, index_args=None):
    if os.sep in src_arg:
        src_prefix = abspath(src_arg)
        if not isdir(src_prefix):
            raise DirectoryNotFoundError(
                src_arg, "no such directory: %s" % src_arg, json
            )
    else:
        src_prefix = context.clone_src

    if not json:
        print("Source:      %s" % src_prefix)
        print("Destination: %s" % dst_prefix)

    with common.json_progress_bars(json=json and not quiet):
        actions, untracked_files = clone_env(
            src_prefix, dst_prefix, verbose=not json, quiet=quiet, index_args=index_args
        )

    if json:
        common.stdout_json_success(
            actions=actions,
            untracked_files=list(untracked_files),
            src_prefix=src_prefix,
            dst_prefix=dst_prefix,
        )


# Traceback (TypeError)
Traceback (most recent call last):
File "/conda/lib/python3.6/site-packages/conda/exceptions.py", line 591, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/conda/lib/python3.6/site-packages/conda/cli/main.py", line 134, in _main
exit_code = args.func(args, p)
File "/conda/lib/python3.6/site-packages/conda/cli/main_create.py", line 68, in execute
install(args, parser, 'create')
File "/conda/lib/python3.6/site-packages/conda/cli/install.py", line 212, in install
clone(args.clone, prefix, json=context.json, quiet=context.quiet, index_args=index_args)
File "/conda/lib/python3.6/site-packages/conda/cli/install.py", line 57, in clone
raise DirectoryNotFoundError(src_arg, 'no such directory: %s' % src_arg, json)
TypeError: __init__() takes 2 positional arguments but 4 were given

# Fixed code
def clone(src_arg, dst_prefix, json=False, quiet=False, index_args=None):
    if os.sep in src_arg:
        src_prefix = abspath(src_arg)
        if not isdir(src_prefix):
            raise DirectoryNotFoundError(src_arg)
    else:
        src_prefix = context.clone_src

    if not json:
        print("Source:      %s" % src_prefix)
        print("Destination: %s" % dst_prefix)

    with common.json_progress_bars(json=json and not quiet):
        actions, untracked_files = clone_env(
            src_prefix, dst_prefix, verbose=not json, quiet=quiet, index_args=index_args
        )

    if json:
        common.stdout_json_success(
            actions=actions,
            untracked_files=list(untracked_files),
            src_prefix=src_prefix,
            dst_prefix=dst_prefix,
        )
# Buggy code
def signal_handler(handler):
    previous_handlers = []
    for signame in INTERRUPT_SIGNALS:
        sig = getattr(signal, signame, None)
        if sig:
            log.debug("registering handler for %s", signame)
            prev_handler = signal.signal(sig, handler)
            previous_handlers.append((sig, prev_handler))
    try:
        yield
    finally:
        standard_handlers = signal.SIG_IGN, signal.SIG_DFL
        for sig, previous_handler in previous_handlers:
            if callable(previous_handler) or previous_handler in standard_handlers:
                log.debug("de-registering handler for %s", sig)
                signal.signal(sig, previous_handler)


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/travis/build/conda/conda/conda-build/conda_build/build.py", line 688, in create_env
execute_actions(actions, index, verbose=config.debug)
File "/home/travis/build/conda/conda/conda/plan.py", line 612, in execute_actions
execute_instructions(plan, index, verbose)
File "/home/travis/build/conda/conda/conda/instructions.py", line 243, in execute_instructions
cmd(state, arg)
File "/home/travis/build/conda/conda/conda/instructions.py", line 98, in PROGRESSIVEFETCHEXTRACT_CMD
progressive_fetch_extract.execute()
File "/home/travis/build/conda/conda/conda/core/package_cache.py", line 491, in execute
with signal_handler(conda_signal_handler):
File "/home/travis/miniconda/lib/python3.6/contextlib.py", line 82, in __enter__
return next(self.gen)
File "/home/travis/build/conda/conda/conda/common/signals.py", line 41, in signal_handler
prev_handler = signal.signal(sig, handler)
File "/home/travis/miniconda/lib/python3.6/signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

# Fixed code
def signal_handler(handler):
    _thread_local = threading.local()
    _thread_local.previous_handlers = []
    for signame in INTERRUPT_SIGNALS:
        sig = getattr(signal, signame, None)
        if sig:
            log.debug("registering handler for %s", signame)
            try:
                prev_handler = signal.signal(sig, handler)
                _thread_local.previous_handlers.append((sig, prev_handler))
            except ValueError as e:
                # ValueError: signal only works in main thread
                log.debug("%r", e)
    try:
        yield
    finally:
        standard_handlers = signal.SIG_IGN, signal.SIG_DFL
        for sig, previous_handler in _thread_local.previous_handlers:
            if callable(previous_handler) or previous_handler in standard_handlers:
                log.debug("de-registering handler for %s", sig)
                signal.signal(sig, previous_handler)
# Buggy code
def print_export_header():
    print("# This file may be used to create an environment using:")
    print("# $ conda create --name <env> --file <this file>")
    print("# platform: %s" % context.subdir)


# Traceback (ImportError)
Traceback (most recent call last):
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/exceptions.py", line 573, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/cli/main.py", line 98, in _main
imported = importlib.import_module(module)
File "/Users/tasalta/anaconda/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/cli/main_list.py", line 20, in <module>
from ..egg_info import get_egg_info
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/egg_info.py", line 15, in <module>
from .misc import rel_path
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/misc.py", line 19, in <module>
from .core.index import get_index, _supplement_index_with_cache
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/core/index.py", line 9, in <module>
from .repodata import collect_all_repodata
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/core/repodata.py", line 21, in <module>
from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: cannot import name InsecureRequestWarning


at throwCondaError (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/conda.js:117:9)
at runConda (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/conda.js:146:5)
at Object.info (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/conda.js:395:10)
at Object.isGLCLauncherReady (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/systemState.js:207:27)
at [object Object].onWindowOpen [as _onTimeout] (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/main.js:144:57)
at Timer.listOnTimeout (timers.js:89:15)

# Fixed code
def print_export_header(subdir):
    print("# This file may be used to create an environment using:")
    print("# $ conda create --name <env> --file <this file>")
    print("# platform: %s" % subdir)
# Buggy code
def print_explicit(prefix, add_md5=False):
    if not isdir(prefix):
        raise CondaEnvironmentNotFoundError(prefix)
    print_export_header()
    print("@EXPLICIT")
    for meta in sorted(linked_data(prefix).values(), key=lambda x: x["name"]):
        url = meta.get("url")
        if not url or url.startswith(UNKNOWN_CHANNEL):
            print("# no URL for: %s" % meta["fn"])
            continue
        md5 = meta.get("md5")
        print(url + ("#%s" % md5 if add_md5 and md5 else ""))


# Traceback (ImportError)
Traceback (most recent call last):
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/exceptions.py", line 573, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/cli/main.py", line 98, in _main
imported = importlib.import_module(module)
File "/Users/tasalta/anaconda/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/cli/main_list.py", line 20, in <module>
from ..egg_info import get_egg_info
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/egg_info.py", line 15, in <module>
from .misc import rel_path
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/misc.py", line 19, in <module>
from .core.index import get_index, _supplement_index_with_cache
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/core/index.py", line 9, in <module>
from .repodata import collect_all_repodata
File "/Users/tasalta/anaconda/lib/python2.7/site-packages/conda/core/repodata.py", line 21, in <module>
from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: cannot import name InsecureRequestWarning


at throwCondaError (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/conda.js:117:9)
at runConda (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/conda.js:146:5)
at Object.info (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/conda.js:395:10)
at Object.isGLCLauncherReady (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/utils/systemState.js:207:27)
at [object Object].onWindowOpen [as _onTimeout] (/Applications/GraphLab Create Launcher.app/Contents/Resources/app.asar/main.js:144:57)
at Timer.listOnTimeout (timers.js:89:15)

# Fixed code
def print_explicit(prefix, add_md5=False):
    from ..base.constants import UNKNOWN_CHANNEL
    from ..base.context import context
    from ..core.linked_data import linked_data

    if not isdir(prefix):
        from ..exceptions import CondaEnvironmentNotFoundError

        raise CondaEnvironmentNotFoundError(prefix)
    print_export_header(context.subdir)
    print("@EXPLICIT")
    for meta in sorted(linked_data(prefix).values(), key=lambda x: x["name"]):
        url = meta.get("url")
        if not url or url.startswith(UNKNOWN_CHANNEL):
            print("# no URL for: %s" % meta["fn"])
            continue
        md5 = meta.get("md5")
        print(url + ("#%s" % md5 if add_md5 and md5 else ""))
# Buggy code
def main(*args):
    if not args:
        args = sys.argv

    if not args:
        args = sys.argv

    log.debug("conda.cli.main called with %s", args)
    if len(args) > 1:
        try:
            argv1 = args[1].strip()
            if argv1.startswith(".."):
                import conda.cli.activate as activate

                activate.main()
                return
            if argv1 in ("activate", "deactivate"):
                message = "'%s' is not a conda command.\n" % argv1
                from ..common.compat import on_win

                if not on_win:
                    message += ' Did you mean "source %s" ?\n' % " ".join(args[1:])

                from ..exceptions import CommandNotFoundError

                raise CommandNotFoundError(argv1, message)
        except Exception as e:
            from ..exceptions import handle_exception

            return handle_exception(e)

    from ..exceptions import conda_exception_handler

    return conda_exception_handler(_main, *args)


# Traceback (TypeError)
(root) [root@d4cb01a1b5b6 ~]# conda activate
Traceback (most recent call last):
File "/conda/bin/conda", line 6, in <module>
sys.exit(conda.cli.main())
File "/conda/lib/python2.7/site-packages/conda/cli/main.py", line 161, in main
raise CommandNotFoundError(argv1, message)
TypeError: __init__() takes exactly 2 arguments (3 given)

# Fixed code
def main(*args):
    if not args:
        args = sys.argv

    if not args:
        args = sys.argv

    log.debug("conda.cli.main called with %s", args)
    if len(args) > 1:
        try:
            argv1 = args[1].strip()
            if argv1.startswith(".."):
                import conda.cli.activate as activate

                activate.main()
                return
            if argv1 in ("activate", "deactivate"):
                from ..exceptions import CommandNotFoundError

                raise CommandNotFoundError(argv1)
        except Exception as e:
            from ..exceptions import handle_exception

            return handle_exception(e)

    from ..exceptions import conda_exception_handler

    return conda_exception_handler(_main, *args)
# Buggy code
def __init__(self, command):
    message = "Conda could not find the command: '%(command)s'"
    super(CommandNotFoundError, self).__init__(message, command=command)


# Traceback (TypeError)
(root) [root@d4cb01a1b5b6 ~]# conda activate
Traceback (most recent call last):
File "/conda/bin/conda", line 6, in <module>
sys.exit(conda.cli.main())
File "/conda/lib/python2.7/site-packages/conda/cli/main.py", line 161, in main
raise CommandNotFoundError(argv1, message)
TypeError: __init__() takes exactly 2 arguments (3 given)

# Fixed code
def __init__(self, command):
    build_commands = {
        "build",
        "convert",
        "develop",
        "index",
        "inspect",
        "metapackage",
        "render",
        "skeleton",
    }
    needs_source = {"activate", "deactivate"}
    if command in build_commands:
        message = dals("""
            You need to install conda-build in order to
            use the 'conda %(command)s' command.
            """)
    elif command in needs_source and not on_win:
        message = dals("""
            '%(command)s is not a conda command.
            Did you mean 'source %(command)s'?
            """)
    else:
        message = "Conda could not find the command: '%(command)s'"
    super(CommandNotFoundError, self).__init__(message, command=command)
# Buggy code
def is_url(url):
    try:
        p = urlparse(url)
        return p.netloc is not None or p.scheme == "file"
    except LocationParseError:
        log.debug("Could not parse url ({0}).".format(url))
        return False


# Traceback (AttributeError)
An unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues



Current conda install:

platform : win-64
conda version : 4.2.12
conda is private : False
conda-env version : 4.2.12
conda-build version : 2.0.7
python version : 3.5.2.final.0
requests version : 2.10.0
root environment : C:\Miniconda3  (writable)
default environment : C:\Miniconda3\envs\test_conda
envs directories : C:\Miniconda3\envs
package cache : C:\Miniconda3\pkgs
channel URLs : https://repo.continuum.io/pkgs/free/win-64
https://repo.continuum.io/pkgs/free/noarch
https://repo.continuum.io/pkgs/pro/win-64
https://repo.continuum.io/pkgs/pro/noarch
https://repo.continuum.io/pkgs/msys2/win-64
https://repo.continuum.io/pkgs/msys2/noarch
config file : None
offline mode : False



`$ C:\Miniconda3\Scripts\conda-script.py install bzip2-1.0.6-vc14_3.tar.bz2 --dry-run`




Traceback (most recent call last):
File "C:\Miniconda3\lib\site-packages\conda\exceptions.py", line 479, in conda_exception_handler
return_value = func(*args, **kwargs)
File "C:\Miniconda3\lib\site-packages\conda\cli\main.py", line 145, in _main
exit_code = args.func(args, p)
File "C:\Miniconda3\lib\site-packages\conda\cli\main_install.py", line 80, in execute
install(args, parser, 'install')
File "C:\Miniconda3\lib\site-packages\conda\cli\install.py", line 209, in install
explicit(args.packages, prefix, verbose=not context.quiet)
File "C:\Miniconda3\lib\site-packages\conda\misc.py", line 66, in explicit
if not is_url(url_p):
File "C:\Miniconda3\lib\site-packages\conda\common\url.py", line 72, in is_url
p = urlparse(url)
File "C:\Miniconda3\lib\site-packages\conda\_vendor\auxlib\decorators.py", line 56, in _memoized_func
result = func(*args, **kwargs)
File "C:\Miniconda3\lib\site-packages\conda\common\url.py", line 55, in urlparse
if on_win and url.startswith('file:'):
AttributeError: 'NoneType' object has no attribute 'startswith'

# Fixed code
def is_url(url):
    if not url:
        return False
    try:
        p = urlparse(url)
        return p.netloc is not None or p.scheme == "file"
    except LocationParseError:
        log.debug("Could not parse url ({0}).".format(url))
        return False
# Buggy code
def replace_long_shebang(mode, data):
    if mode is FileMode.text:
        shebang_match = SHEBANG_REGEX.match(data)
        if shebang_match:
            whole_shebang, executable, options = shebang_match.groups()
            if len(whole_shebang) > 127:
                executable_name = executable.decode(UTF8).split("/")[-1]
                new_shebang = "#!/usr/bin/env %s%s" % (
                    executable_name,
                    options.decode(UTF8),
                )
                data = data.replace(whole_shebang, new_shebang.encode(UTF8))
    else:
        # TODO: binary shebangs exist; figure this out in the future if text works well
        log.debug(
            "TODO: binary shebangs exist; figure this out in the future if text works well"
        )
    return data


# Traceback (CondaRuntimeError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/exceptions.py", line 472, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/main.py", line 144, in _main
exit_code = args.func(args, p)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/main_install.py", line 80, in execute
install(args, parser, 'install')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/install.py", line 420, in install
raise CondaRuntimeError('RuntimeError: %s' % e)
CondaRuntimeError: Runtime error: RuntimeError: Invalid mode: <conda.install.FileMode object at 0x10846b110>

# Fixed code
def replace_long_shebang(mode, data):
    if mode == FileMode.text:
        shebang_match = SHEBANG_REGEX.match(data)
        if shebang_match:
            whole_shebang, executable, options = shebang_match.groups()
            if len(whole_shebang) > 127:
                executable_name = executable.decode(UTF8).split("/")[-1]
                new_shebang = "#!/usr/bin/env %s%s" % (
                    executable_name,
                    options.decode(UTF8),
                )
                data = data.replace(whole_shebang, new_shebang.encode(UTF8))
    else:
        # TODO: binary shebangs exist; figure this out in the future if text works well
        log.debug(
            "TODO: binary shebangs exist; figure this out in the future if text works well"
        )
    return data
# Buggy code
def replace_prefix(mode, data, placeholder, new_prefix):
    if mode is FileMode.text:
        data = data.replace(placeholder.encode(UTF8), new_prefix.encode(UTF8))
    elif mode == FileMode.binary:
        data = binary_replace(data, placeholder.encode(UTF8), new_prefix.encode(UTF8))
    else:
        raise RuntimeError("Invalid mode: %r" % mode)
    return data


# Traceback (CondaRuntimeError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/exceptions.py", line 472, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/main.py", line 144, in _main
exit_code = args.func(args, p)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/main_install.py", line 80, in execute
install(args, parser, 'install')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/install.py", line 420, in install
raise CondaRuntimeError('RuntimeError: %s' % e)
CondaRuntimeError: Runtime error: RuntimeError: Invalid mode: <conda.install.FileMode object at 0x10846b110>

# Fixed code
def replace_prefix(mode, data, placeholder, new_prefix):
    if mode == FileMode.text:
        data = data.replace(placeholder.encode(UTF8), new_prefix.encode(UTF8))
    elif mode == FileMode.binary:
        data = binary_replace(data, placeholder.encode(UTF8), new_prefix.encode(UTF8))
    else:
        raise RuntimeError("Invalid mode: %r" % mode)
    return data
# Buggy code
def update_prefix(path, new_prefix, placeholder=PREFIX_PLACEHOLDER, mode=FileMode.text):
    if on_win and mode is FileMode.text:
        # force all prefix replacements to forward slashes to simplify need to escape backslashes
        # replace with unix-style path separators
        new_prefix = new_prefix.replace("\\", "/")

    path = os.path.realpath(path)
    with open(path, "rb") as fi:
        original_data = data = fi.read()

    data = replace_prefix(mode, data, placeholder, new_prefix)
    if not on_win:
        data = replace_long_shebang(mode, data)

    if data == original_data:
        return
    st = os.lstat(path)
    with exp_backoff_fn(open, path, "wb") as fo:
        fo.write(data)
    os.chmod(path, stat.S_IMODE(st.st_mode))


# Traceback (CondaRuntimeError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/exceptions.py", line 472, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/main.py", line 144, in _main
exit_code = args.func(args, p)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/main_install.py", line 80, in execute
install(args, parser, 'install')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/conda/cli/install.py", line 420, in install
raise CondaRuntimeError('RuntimeError: %s' % e)
CondaRuntimeError: Runtime error: RuntimeError: Invalid mode: <conda.install.FileMode object at 0x10846b110>

# Fixed code
def update_prefix(path, new_prefix, placeholder=PREFIX_PLACEHOLDER, mode=FileMode.text):
    if on_win and mode == FileMode.text:
        # force all prefix replacements to forward slashes to simplify need to escape backslashes
        # replace with unix-style path separators
        new_prefix = new_prefix.replace("\\", "/")

    path = os.path.realpath(path)
    with open(path, "rb") as fi:
        original_data = data = fi.read()

    data = replace_prefix(mode, data, placeholder, new_prefix)
    if not on_win:
        data = replace_long_shebang(mode, data)

    if data == original_data:
        return
    st = os.lstat(path)
    with exp_backoff_fn(open, path, "wb") as fo:
        fo.write(data)
    os.chmod(path, stat.S_IMODE(st.st_mode))
# Buggy code
def from_value(value):
    if value is None:
        return Channel(name="<unknown>")
    elif has_scheme(value):
        if value.startswith("file:") and on_win:
            value = value.replace("\\", "/")
        return Channel.from_url(value)
    elif value.startswith(("./", "..", "~", "/")) or is_windows_path(value):
        return Channel.from_url(path_to_url(value))
    elif value.endswith(".tar.bz2"):
        if value.startswith("file:") and on_win:
            value = value.replace("\\", "/")
        return Channel.from_url(value)
    else:
        # at this point assume we don't have a bare (non-scheme) url
        #   e.g. this would be bad:  repo.continuum.io/pkgs/free
        if value in context.custom_multichannels:
            return MultiChannel(value, context.custom_multichannels[value])
        else:
            return Channel.from_channel_name(value)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr1/eclark/anaconda3/lib/python3.4/site-packages/conda/exceptions.py", line 473, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/usr1/eclark/anaconda3/lib/python3.4/site-packages/conda/cli/main.py", line 144, in _main
exit_code = args.func(args, p)
File "/usr1/eclark/anaconda3/lib/python3.4/site-packages/conda/cli/main_search.py", line 126, in execute
execute_search(args, parser)
File "/usr1/eclark/anaconda3/lib/python3.4/site-packages/conda/cli/main_search.py", line 268, in execute_search
Channel(pkg.channel).canonical_name,
File "/usr1/eclark/anaconda3/lib/python3.4/site-packages/conda/models/channel.py", line 44, in __call__
elif value.endswith('.tar.bz2'):
TypeError: endswith first arg must be bytes or a tuple of bytes, not str

# Fixed code
def from_value(value):
    if value is None:
        return Channel(name="<unknown>")
    if hasattr(value, "decode"):
        value = value.decode(UTF8)
    if has_scheme(value):
        if value.startswith("file:") and on_win:
            value = value.replace("\\", "/")
        return Channel.from_url(value)
    elif value.startswith(("./", "..", "~", "/")) or is_windows_path(value):
        return Channel.from_url(path_to_url(value))
    elif value.endswith(".tar.bz2"):
        if value.startswith("file:") and on_win:
            value = value.replace("\\", "/")
        return Channel.from_url(value)
    else:
        # at this point assume we don't have a bare (non-scheme) url
        #   e.g. this would be bad:  repo.continuum.io/pkgs/free
        if value in context.custom_multichannels:
            return MultiChannel(value, context.custom_multichannels[value])
        else:
            return Channel.from_channel_name(value)
# Buggy code
def collect_errors(self, instance, value, source="<<merged>>"):
    errors = super(MapParameter, self).collect_errors(instance, value)
    element_type = self._element_type
    errors.extend(
        InvalidElementTypeError(self.name, val, source, type(val), element_type, key)
        for key, val in iteritems(value)
        if not isinstance(val, element_type)
    )
    return errors


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:\Anaconda3\lib\site-packages\conda\exceptions.py", line 472, in conda_exception_handler
return_value = func(*args, **kwargs)
File "C:\Anaconda3\lib\site-packages\conda\cli\main.py", line 144, in _main
exit_code = args.func(args, p)
File "C:\Anaconda3\lib\site-packages\conda\cli\main_update.py", line 65, in execute
install(args, parser, 'update')
File "C:\Anaconda3\lib\site-packages\conda\cli\install.py", line 139, in install
context.validate_all()
File "C:\Anaconda3\lib\site-packages\conda\common\configuration.py", line 752, in validate_all
for source in self.raw_data))
File "C:\Anaconda3\lib\site-packages\conda\common\configuration.py", line 752, in <genexpr>
for source in self.raw_data))
File "C:\Anaconda3\lib\site-packages\conda\common\configuration.py", line 739, in check_source
collected_errors = parameter.collect_errors(self, typed_value, match.source)
File "C:\Anaconda3\lib\site-packages\conda\common\configuration.py", line 642, in collect_errors
for key, val in iteritems(value) if not isinstance(val, element_type))
File "C:\Anaconda3\lib\site-packages\conda\compat.py", line 148, in iteritems
return iter(getattr(d, _iteritems)())
AttributeError: 'str' object has no attribute 'items'

# Fixed code
def collect_errors(self, instance, value, source="<<merged>>"):
    errors = super(MapParameter, self).collect_errors(instance, value)
    if isinstance(value, Mapping):
        element_type = self._element_type
        errors.extend(
            InvalidElementTypeError(
                self.name, val, source, type(val), element_type, key
            )
            for key, val in iteritems(value)
            if not isinstance(val, element_type)
        )
    return errors
# Buggy code
def check_prefix(prefix, json=False):
    name = basename(prefix)
    error = None
    if name.startswith("."):
        error = "environment name cannot start with '.': %s" % name
    if name == ROOT_ENV_NAME:
        error = "'%s' is a reserved environment name" % name
    if exists(prefix):
        if isdir(prefix) and not os.listdir(prefix):
            return None
        error = "prefix already exists: %s" % prefix

    if error:
        raise CondaValueError(error, json)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/opt/a/b/c/muunitnoc/anaconda/lib/python2.7/site-packages/conda/exceptions.py", line 472, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/opt/a/b/c/muunitnoc/anaconda/lib/python2.7/site-packages/conda/cli/main.py", line 144, in _main
exit_code = args.func(args, p)
File "/opt/a/b/c/muunitnoc/anaconda/lib/python2.7/site-packages/conda/cli/main_create.py", line 68, in execute
install(args, parser, 'create')
File "/opt/a/b/c/muunitnoc/anaconda/lib/python2.7/site-packages/conda/cli/install.py", line 171, in install
default_packages.remove(default_pkg)
AttributeError: 'tuple' object has no attribute 'remove'

# Fixed code
def check_prefix(prefix, json=False):
    name = basename(prefix)
    error = None
    if name.startswith("."):
        error = "environment name cannot start with '.': %s" % name
    if name == ROOT_ENV_NAME:
        error = "'%s' is a reserved environment name" % name
    if exists(prefix):
        if isdir(prefix) and "conda-meta" not in os.listdir(prefix):
            return None
        error = "prefix already exists: %s" % prefix

    if error:
        raise CondaValueError(error, json)
# Buggy code
def environment(self):
    dependencies = []
    with open(self.filename) as reqfile:
        for line in reqfile:
            dependencies.append(line)
    return env.Environment(name=self.name, dependencies=dependencies)


# Traceback (AttributeError)
n unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues


Current conda install:

platform : linux-64
conda version : 4.2.1
conda is private : False
conda-env version : 2.5.2
conda-build version : 1.21.11+0.g5b44ab3.dirty
python version : 2.7.12.final.0
requests version : 2.10.0
root environment : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7  (writable)
default environment : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/envs/anabase
envs directories : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/envs
package cache : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/pkgs
channel URLs : file:///reg/g/psdm/sw/conda/channels/system-rhel7
file:///reg/g/psdm/sw/conda/channels/psana-rhel7
file:///reg/g/psdm/sw/conda/channels/external-rhel7
defaults
scikit-beam
file:///reg/g/psdm/sw/conda/channels/testing-rhel7
config file : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/.condarc
offline mode : False


`$ /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/bin/conda-env export`


Traceback (most recent call last):
File "/reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/lib/python2.7/site-packages/conda/exceptions.py", line 403, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/lib/python2.7/site-packages/conda_env/cli/main_export.py", line 93, in execute
ignore_channels=args.ignore_prefix)
AttributeError: 'Namespace' object has no attribute 'ignore_prefix'
../manage/config/environment-anabase-1.0.0.yml (END)

# Fixed code
def environment(self):
    dependencies = []
    with open(self.filename) as reqfile:
        for line in reqfile:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            dependencies.append(line)
    return env.Environment(name=self.name, dependencies=dependencies)
# Buggy code
def add_pip_installed(prefix, installed_pkgs, json=None, output=True):
    # Defer to json for backwards compatibility
    if type(json) is bool:
        output = not json

    # TODO Refactor so installed is a real list of objects/dicts
    #      instead of strings allowing for direct comparison
    conda_names = {d.rsplit("-", 2)[0] for d in installed_pkgs}

    for pip_pkg in installed(prefix, output=output):
        if pip_pkg["name"] in conda_names and not "path" in pip_pkg:
            continue
        installed_pkgs.add(str(pip_pkg))


# Traceback (AttributeError)
n unexpected error has occurred.
Please consider posting the following information to the
conda GitHub issue tracker at:

https://github.com/conda/conda/issues


Current conda install:

platform : linux-64
conda version : 4.2.1
conda is private : False
conda-env version : 2.5.2
conda-build version : 1.21.11+0.g5b44ab3.dirty
python version : 2.7.12.final.0
requests version : 2.10.0
root environment : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7  (writable)
default environment : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/envs/anabase
envs directories : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/envs
package cache : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/pkgs
channel URLs : file:///reg/g/psdm/sw/conda/channels/system-rhel7
file:///reg/g/psdm/sw/conda/channels/psana-rhel7
file:///reg/g/psdm/sw/conda/channels/external-rhel7
defaults
scikit-beam
file:///reg/g/psdm/sw/conda/channels/testing-rhel7
config file : /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/.condarc
offline mode : False


`$ /reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/bin/conda-env export`


Traceback (most recent call last):
File "/reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/lib/python2.7/site-packages/conda/exceptions.py", line 403, in conda_exception_handler
return_value = func(*args, **kwargs)
File "/reg/g/psdm/sw/conda/inst/miniconda2-dev-rhel7/lib/python2.7/site-packages/conda_env/cli/main_export.py", line 93, in execute
ignore_channels=args.ignore_prefix)
AttributeError: 'Namespace' object has no attribute 'ignore_prefix'
../manage/config/environment-anabase-1.0.0.yml (END)

# Fixed code
def add_pip_installed(prefix, installed_pkgs, json=None, output=True):
    # Defer to json for backwards compatibility
    if type(json) is bool:
        output = not json

    # TODO Refactor so installed is a real list of objects/dicts
    #      instead of strings allowing for direct comparison
    # split :: to get rid of channel info
    conda_names = {d.rsplit("-", 2)[0].split("::")[-1] for d in installed_pkgs}
    for pip_pkg in installed(prefix, output=output):
        if pip_pkg["name"] in conda_names and not "path" in pip_pkg:
            continue
        installed_pkgs.add(str(pip_pkg))
# Buggy code
def __init__(self, path, retries=10):
    self.path = path
    self.end = "-" + str(os.getpid())
    self.lock_path = os.path.join(self.path, LOCKFN + self.end)
    self.retries = retries


# Traceback (PermissionError)
Traceback (most recent call last):
File "/opt/anaconda/bin/conda-env", line 6, in <module>
sys.exit(conda_env.cli.main.main())
File "/opt/anaconda/lib/python3.5/site-packages/conda_env/cli/main.py", line 68, in main
return args_func(args, parser)
File "/opt/anaconda/lib/python3.5/site-packages/conda/cli/main.py", line 127, in args_func
args.func(args, p)
File "/opt/anaconda/lib/python3.5/site-packages/conda_env/cli/main_create.py", line 105, in execute
installer.install(prefix, pkg_specs, args, env)
File "/opt/anaconda/lib/python3.5/site-packages/conda_env/installers/conda.py", line 20, in install
plan.execute_actions(actions, index, verbose=not args.quiet)
File "/opt/anaconda/lib/python3.5/site-packages/conda/plan.py", line 589, in execute_actions
inst.execute_instructions(plan, index, verbose)
File "/opt/anaconda/lib/python3.5/site-packages/conda/instructions.py", line 137, in execute_instructions
cmd(state, arg)
File "/opt/anaconda/lib/python3.5/site-packages/conda/instructions.py", line 80, in LINK_CMD
link(state['prefix'], dist, lt, index=state['index'], shortcuts=shortcuts)
File "/opt/anaconda/lib/python3.5/site-packages/conda/install.py", line 1059, in link
with Locked(prefix), Locked(pkgs_dir):
File "/opt/anaconda/lib/python3.5/site-packages/conda/lock.py", line 60, in __enter__
os.makedirs(self.lock_path)
File "/opt/anaconda/lib/python3.5/os.py", line 241, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/opt/anaconda/pkgs/.conda_lock-5633'

# Fixed code
def __init__(self, path):
    self.path = path
    self.end = "-" + str(os.getpid())
    self.lock_path = join(self.path, LOCKFN + self.end)
    self.pattern = join(self.path, LOCKFN + "-*")
    self.remove = True
# Buggy code
def __exit__(self, exc_type, exc_value, traceback):
    try:
        os.rmdir(self.lock_path)
        os.rmdir(self.path)
    except OSError:
        pass


# Traceback (PermissionError)
Traceback (most recent call last):
File "/opt/anaconda/bin/conda-env", line 6, in <module>
sys.exit(conda_env.cli.main.main())
File "/opt/anaconda/lib/python3.5/site-packages/conda_env/cli/main.py", line 68, in main
return args_func(args, parser)
File "/opt/anaconda/lib/python3.5/site-packages/conda/cli/main.py", line 127, in args_func
args.func(args, p)
File "/opt/anaconda/lib/python3.5/site-packages/conda_env/cli/main_create.py", line 105, in execute
installer.install(prefix, pkg_specs, args, env)
File "/opt/anaconda/lib/python3.5/site-packages/conda_env/installers/conda.py", line 20, in install
plan.execute_actions(actions, index, verbose=not args.quiet)
File "/opt/anaconda/lib/python3.5/site-packages/conda/plan.py", line 589, in execute_actions
inst.execute_instructions(plan, index, verbose)
File "/opt/anaconda/lib/python3.5/site-packages/conda/instructions.py", line 137, in execute_instructions
cmd(state, arg)
File "/opt/anaconda/lib/python3.5/site-packages/conda/instructions.py", line 80, in LINK_CMD
link(state['prefix'], dist, lt, index=state['index'], shortcuts=shortcuts)
File "/opt/anaconda/lib/python3.5/site-packages/conda/install.py", line 1059, in link
with Locked(prefix), Locked(pkgs_dir):
File "/opt/anaconda/lib/python3.5/site-packages/conda/lock.py", line 60, in __enter__
os.makedirs(self.lock_path)
File "/opt/anaconda/lib/python3.5/os.py", line 241, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/opt/anaconda/pkgs/.conda_lock-5633'

# Fixed code
def __exit__(self, exc_type, exc_value, traceback):
    if self.remove:
        for path in self.lock_path, self.path:
            try:
                os.rmdir(path)
            except OSError:
                pass
# Buggy code
def get_rc_urls():
    if rc.get("channels") is None:
        return []
    if "system" in rc["channels"]:
        raise RuntimeError("system cannot be used in .condarc")
    return rc["channels"]


# Traceback (AttributeError)
$ conda info
Traceback (most recent call last):
File "/Users/jenns/anaconda/bin/conda", line 6, in <module>
sys.exit(main())
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/cli/main.py", line 61, in main
from conda.cli import conda_argparse
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/cli/conda_argparse.py", line 15, in <module>
from .common import add_parser_help
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/cli/common.py", line 12, in <module>
from ..config import (envs_dirs, default_prefix, platform, update_dependencies,
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/config.py", line 331, in <module>
allowed_channels = get_allowed_channels()
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/config.py", line 329, in get_allowed_channels
return normalize_urls(base_urls)
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/config.py", line 253, in normalize_urls
urls = get_rc_urls() + urls
File "/Users/jenns/anaconda/lib/python2.7/site-packages/conda/config.py", line 197, in get_rc_urls
if rc.get('channels') is None:
AttributeError: 'NoneType' object has no attribute 'get'

# Fixed code
def get_rc_urls():
    if rc is None or rc.get("channels") is None:
        return []
    if "system" in rc["channels"]:
        raise RuntimeError("system cannot be used in .condarc")
    return rc["channels"]