gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, **kwargs):
    # Save values so that we can revert to their initial values
    self.old_defaults = {}
    with Session() as lib:
        for key in kwargs:
            self.old_defaults[key] = lib.get_default(key)

    # call gmt set to change GMT defaults
    arg_str = " ".join(["{}={}".format(key, value) for key, value in kwargs.items()])
    with Session() as lib:
        lib.call_module("set", arg_str)


# Traceback (pygmt.exceptions.GMTCLibError)
pygmt-session [ERROR]: Syntax error: Unrecognized keyword FONT
Traceback (most recent call last):
File "/opt/miniconda3/envs/liam/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-19-8e431d18430a>", line 1, in <module>
pygmt.config(FONT='8p')
File "/opt/miniconda3/envs/liam/lib/python3.7/site-packages/pygmt/modules.py", line 168, in __init__
self.old_defaults[key] = lib.get_default(key)
File "/opt/miniconda3/envs/liam/lib/python3.7/site-packages/pygmt/clib/session.py", line 458, in get_default
name, status
pygmt.exceptions.GMTCLibError: Error getting default value for 'FONT' (error code 67).

# Fixed code
def __init__(self, **kwargs):
    # Save values so that we can revert to their initial values
    self.old_defaults = {}
    self.special_params = {
        "FONT": [
            "FONT_ANNOT_PRIMARY",
            "FONT_ANNOT_SECONDARY",
            "FONT_HEADING",
            "FONT_LABEL",
            "FONT_TAG",
            "FONT_TITLE",
        ],
        "FONT_ANNOT": ["FONT_ANNOT_PRIMARY", "FONT_ANNOT_SECONDARY"],
        "FORMAT_TIME_MAP": ["FORMAT_TIME_PRIMARY_MAP", "FORMAT_TIME_SECONDARY_MAP"],
        "MAP_ANNOT_OFFSET": [
            "MAP_ANNOT_OFFSET_PRIMARY",
            "MAP_ANNOT_OFFSET_SECONDARY",
        ],
        "MAP_GRID_CROSS_SIZE": [
            "MAP_GRID_CROSS_SIZE_PRIMARY",
            "MAP_GRID_CROSS_SIZE_SECONDARY",
        ],
        "MAP_GRID_PEN": ["MAP_GRID_PEN_PRIMARY", "MAP_GRID_PEN_SECONDARY"],
        "MAP_TICK_LENGTH": ["MAP_TICK_LENGTH_PRIMARY", "MAP_TICK_LENGTH_SECONDARY"],
        "MAP_TICK_PEN": ["MAP_TICK_PEN_PRIMARY", "MAP_TICK_PEN_SECONDARY"],
    }
    with Session() as lib:
        for key in kwargs:
            if key in self.special_params:
                for k in self.special_params[key]:
                    self.old_defaults[k] = lib.get_default(k)
            else:
                self.old_defaults[key] = lib.get_default(key)

    # call gmt set to change GMT defaults
    arg_str = " ".join(["{}={}".format(key, value) for key, value in kwargs.items()])
    with Session() as lib:
        lib.call_module("set", arg_str)
# Buggy code
def __init__(
    self,
    text: base.String,
    request_contact: base.Boolean = None,
    request_location: base.Boolean = None,
    request_poll: KeyboardButtonPollType = None,
):
    super(KeyboardButton, self).__init__(
        text=text,
        request_contact=request_contact,
        request_location=request_location,
        request_poll=request_poll,
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.8/site-packages/aiogram/types/base.py", line 145, in to_object
return cls(**data)
File "/usr/lib/python3.8/site-packages/aiogram/types/reply_keyboard.py", line 35, in __init__
super(ReplyKeyboardMarkup, self).__init__(keyboard=keyboard, resize_keyboard=resize_keyboard,
File "/usr/lib/python3.8/site-packages/aiogram/types/base.py", line 91, in __init__
self.props[key].set_value(self, value, parent=self)
File "/usr/lib/python3.8/site-packages/aiogram/types/fields.py", line 56, in set_value
value = self.deserialize(value, parent)
File "/usr/lib/python3.8/site-packages/aiogram/types/fields.py", line 161, in deserialize
row_result.append(deserialize(item, parent=parent))
File "/usr/lib/python3.8/site-packages/aiogram/types/fields.py", line 112, in deserialize
return self.base_object(conf={'parent': parent}, **value)
TypeError: __init__() got an unexpected keyword argument 'conf'

# Fixed code
def __init__(
    self,
    text: base.String,
    request_contact: base.Boolean = None,
    request_location: base.Boolean = None,
    request_poll: KeyboardButtonPollType = None,
    **kwargs,
):
    super(KeyboardButton, self).__init__(
        text=text,
        request_contact=request_contact,
        request_location=request_location,
        request_poll=request_poll,
        **kwargs,
    )
# Buggy code
def disconnect_all_containers(self):
    containers = self.client.inspect_network(self.parameters.network_name)["Containers"]
    for cont in containers.values():
        self.disconnect_container(cont["Name"])


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 392, in <module>
main()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 385, in main
cm = DockerNetworkManager(client)
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 218, in __init__
self.present()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 352, in present
self.disconnect_missing()
File "/tmp/ansible_9Ntaqw/ansible_module_docker_network.py", line 323, in disconnect_missing
for c in self.existing_network['Containers'].values():
AttributeError: 'NoneType' object has no attribute 'values'

failed: [192.168.1.120 -> 127.0.0.1] (item={u'driver': u'overlay', u'name': u'networks_default_1'}) => {
"failed": true,
"item": {
"driver": "overlay",
"name": "networks_default_1"
},
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 392, in <module>\n    main()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 385, in main\n    cm = DockerNetworkManager(client)\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 218, in __init__\n    self.present()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 352, in present\n    self.disconnect_missing()\n  File \"/tmp/ansible_9Ntaqw/ansible_module_docker_network.py\", line 323, in disconnect_missing\n    for c in self.existing_network['Containers'].values():\nAttributeError: 'NoneType' object has no attribute 'values'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0

# Fixed code
def disconnect_all_containers(self):
    containers = self.client.inspect_network(self.parameters.network_name)["Containers"]
    if not containers:
        return
    for cont in containers.values():
        self.disconnect_container(cont["Name"])
# Buggy code
def list_databases(self):
    """
    List the databases available from the WFAU archive.
    """
    self.databases = set(self.all_databases + self._get_databases())
    return self.databases


# Traceback (TypeError)
In [1]: from astroquery.ukidss import Ukidss
dbus[49296]: Dynamic session lookup supported but failed: launchd did not provide a socket path, verify that org.freedesktop.dbus-session.plist is loaded!
dbus[49296]: Dynamic session lookup supported but failed: launchd did not provide a socket path, verify that org.freedesktop.dbus-session.plist is loaded!

In [2]: Ukidss.list_databases()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-5e67702382f5> in <module>
----> 1 Ukidss.list_databases()

/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/astroquery/wfau/core.py in list_databases(self)
674         List the databases available from the WFAU archive.
675         """
--> 676         self.databases = set(self.all_databases + self._get_databases())
677         return self.databases
678

TypeError: can only concatenate tuple (not "list") to tuple

# Fixed code
def list_databases(self):
    """
    List the databases available from the WFAU archive.
    """
    self.databases = set(self.all_databases + tuple(self._get_databases()))
    return self.databases
# Buggy code
@contextmanager
    def _emit_changed(self):
        """
        A context manager that calls `emit_selection_rows_changed after
        changing a selection.
        """
        def map_from_source(rows):
            from_src = self.proxy.mapFromSource
            index = self.proxy.sourceModel().index
            return {from_src(index(row, 0)).row() for row in rows}

        old_rows = self._rows.copy()
        try:
            yield
        finally:
            deselected = map_from_source(old_rows - self._rows)
            selected = map_from_source(self._rows - old_rows)
            if selected or deselected:
                for model in self._selection_models:
                    model.emit_selection_rows_changed(selected, deselected)


# Traceback (AttributeError)
-------------------------- AttributeError Exception ---------------------------
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/evaluate/owpredictions.py", line 1130, in select
self.store.select(selection, flags)
File "/Users/ajda/orange/orange3/Orange/widgets/evaluate/owpredictions.py", line 1057, in select
rows = {selection.model().mapToSource(selection).row()}
AttributeError: 'NoneType' object has no attribute 'mapToSource'
-------------------------------------------------------------------------------

# Fixed code
@contextmanager
    def _emit_changed(self):
        """
        A context manager that calls `emit_selection_rows_changed after
        changing a selection.
        """
        def map_from_source(rows):
            from_src = self.proxy.mapFromSource
            index = self.proxy.sourceModel().index
            return {from_src(index(row, 0)).row() for row in rows}

        old_rows = self._rows.copy()
        try:
            yield
        finally:
            if self.proxy.sourceModel() is not None:
                deselected = map_from_source(old_rows - self._rows)
                selected = map_from_source(self._rows - old_rows)
                if selected or deselected:
                    for model in self._selection_models:
                        model.emit_selection_rows_changed(selected, deselected)
# Buggy code
def get_client(
    self, keystore, force_pair=True, *, devices=None, allow_user_interaction=True
) -> Optional["KeepKeyClient"]:
    client = super().get_client(
        keystore,
        force_pair,
        devices=devices,
        allow_user_interaction=allow_user_interaction,
    )
    # returns the client for a given keystore. can use xpub
    if client:
        client.used()
    return client


# Traceback (OSError)
$ ~/Downloads/apps/electrum-4.0.2-x86_64.AppImage --testnet
Warning: Ignoring XDG_SESSION_TYPE=wayland on Gnome. Use QT_QPA_PLATFORM=wayland to run on Wayland anyway.
E | plugin.DeviceMgr | failed to create client for bitbox02 at b'0001:0009:01': Exception('No BitBox02 detected')
E | plugins.coldcard.coldcard.Coldcard_KeyStore |
Traceback (most recent call last):
File "/tmp/.mount_electrcFBIsQ/usr/lib/python3.7/site-packages/electrum/plugins/coldcard/coldcard.py", line 383, in sign_transaction
resp = client.sign_transaction_poll()
File "/tmp/.mount_electrcFBIsQ/usr/lib/python3.7/site-packages/electrum/plugins/coldcard/coldcard.py", line 233, in sign_transaction_poll
return self.dev.send_recv(CCProtocolPacker.get_signed_txn(), timeout=None)
File "/tmp/.mount_electrcFBIsQ/usr/lib/python3.7/site-packages/ckcc/client.py", line 139, in send_recv
buf = self.dev.read(64, timeout_ms=(timeout or 0))
File "hid.pyx", line 123, in hid.device.read
OSError: read error
double free or corruption (fasttop)
Aborted

# Fixed code
@runs_in_hwd_thread
    def get_client(self, keystore, force_pair=True, *,
                   devices=None, allow_user_interaction=True) -> Optional['KeepKeyClient']:
        client = super().get_client(keystore, force_pair,
                                    devices=devices,
                                    allow_user_interaction=allow_user_interaction)
        # returns the client for a given keystore. can use xpub
        if client:
            client.used()
        return client
# Buggy code
async def is_online(self):
    if not self.id:
        self.id = await self.fetch_id()
    url = YOUTUBE_SEARCH_ENDPOINT
    params = {
        "key": self._token,
        "part": "snippet",
        "channelId": self.id,
        "type": "video",
        "eventType": "live",
    }
    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=params) as r:
            data = await r.json()
    if "items" in data and len(data["items"]) == 0:
        raise OfflineStream()
    elif "items" in data:
        vid_id = data["items"][0]["id"]["videoId"]
        params = {"key": self._token, "id": vid_id, "part": "snippet"}
        async with aiohttp.ClientSession() as session:
            async with session.get(YOUTUBE_VIDEOS_ENDPOINT, params=params) as r:
                data = await r.json()
        return self.make_embed(data)


# Traceback (AttributeError)
Exception during loading of cog
Traceback (most recent call last):
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\core\core_commands.py", line 87, in _load
await bot.load_extension(spec)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\core\bot.py", line 222, in load_extension
await lib.setup(self)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\__init__.py", line 6, in setup
await cog.initialize()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\streams.py", line 71, in initialize
self.streams = await self.load_streams()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\streams.py", line 618, in load_streams
return [x for x in streams if not (x.name.lower() in seen or seen_add(x.name.lower()))]
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\streams.py", line 618, in <listcomp>
return [x for x in streams if not (x.name.lower() in seen or seen_add(x.name.lower()))]
AttributeError: 'NoneType' object has no attribute 'lower'

# Fixed code
async def is_online(self):
    if not self._token:
        raise InvalidYoutubeCredentials("YouTube API key is not set.")

    if not self.id:
        self.id = await self.fetch_id()
    elif not self.name:
        self.name = await self.fetch_name()

    url = YOUTUBE_SEARCH_ENDPOINT
    params = {
        "key": self._token,
        "part": "snippet",
        "channelId": self.id,
        "type": "video",
        "eventType": "live",
    }
    async with aiohttp.ClientSession() as session:
        async with session.get(url, params=params) as r:
            data = await r.json()
    if "items" in data and len(data["items"]) == 0:
        raise OfflineStream()
    elif "items" in data:
        vid_id = data["items"][0]["id"]["videoId"]
        params = {"key": self._token, "id": vid_id, "part": "snippet"}
        async with aiohttp.ClientSession() as session:
            async with session.get(YOUTUBE_VIDEOS_ENDPOINT, params=params) as r:
                data = await r.json()
        return self.make_embed(data)
# Buggy code
@hydra.main(config_name="config")
def my_app(cfg: DictConfig):
    log.info(f"Process ID {os.getpid()} executing task {cfg.task} ...")

    time.sleep(1)


# Traceback (RuntimeError)
$ HYDRA_FULL_ERROR=1 python foo.py
Traceback (most recent call last):
File "/private/home/calebh/miniconda3/envs/bench-detectron2/lib/python3.7/site-packages/hydra/_internal/utils.py", line 198, in run_and_report
return func()
File "/private/home/calebh/miniconda3/envs/bench-detectron2/lib/python3.7/site-packages/hydra/_internal/utils.py", line 336, in <lambda>
overrides=args.overrides,
File "/private/home/calebh/miniconda3/envs/bench-detectron2/lib/python3.7/site-packages/hydra/_internal/hydra.py", line 109, in run
job_subdir_key=None,
File "/private/home/calebh/miniconda3/envs/bench-detectron2/lib/python3.7/site-packages/hydra/core/utils.py", line 123, in run_job
ret.return_value = task_function(task_cfg)
File "foo.py", line 7, in main
submitit.JobEnvironment()
File "/private/home/calebh/miniconda3/envs/bench-detectron2/lib/python3.7/site-packages/submitit/core/job_environment.py", line 37, in __new__
return plugins.get_job_environment()
File "/private/home/calebh/miniconda3/envs/bench-detectron2/lib/python3.7/site-packages/submitit/core/plugins.py", line 82, in get_job_environment
f"Could not figure out which environment the job is runnning in. Known environments: {', '.join(envs.keys())}."
RuntimeError: Could not figure out which environment the job is runnning in. Known environments: slurm, local, debug.

# Fixed code
@hydra.main(config_name="config")
def my_app(cfg: DictConfig):
    env = submitit.JobEnvironment()
    log.info(f"Process ID {os.getpid()} executing task {cfg.task}, with {env}")
    time.sleep(1)
# Buggy code
def populate(self):
    self.get_cpu_facts()
    self.get_memory_facts()
    self.get_dmi_facts()
    self.get_device_facts()
    self.get_uptime_facts()
    try:
        self.get_mount_facts()
    except TimeoutError:
        pass
    return self.facts


# Traceback (nValueError)
$ LANG=de_DE.UTF-8
$ ansible puppet-d01 -m setup
puppet-d01 | FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "######################################################################\nThis is a private computer facility.  Access for any reason must be  |\nspecifically authorized by the owner.  Unless you are so authorized, |\nyour continued access and any other use may expose you to criminal   |\nand/or civil proceedings.  Usage may be monitored.                   |\n---------------------------------------------------------------------|\n# Usage:                 puppet-d01                                  |\n######################################################################\nConnection to puppet-d01 closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_c31TXu/ansible_module_setup.py\", line 139, in <module>\r\n    main()\r\n  File \"/tmp/ansible_c31TXu/ansible_module_setup.py\", line 131, in main\r\n    data = get_all_facts(module)\r\n  File \"/tmp/ansible_c31TXu/ansible_modlib.zip/ansible/module_utils/facts.py\", line 3932, in get_all_facts\r\n  File \"/tmp/ansible_c31TXu/ansible_modlib.zip/ansible/module_utils/facts.py\", line 3875, in ansible_facts\r\n  File \"/tmp/ansible_c31TXu/ansible_modlib.zip/ansible/module_utils/facts.py\", line 1569, in populate\r\n  File \"/tmp/ansible_c31TXu/ansible_modlib.zip/ansible/module_utils/facts.py\", line 1728, in get_uptime_facts\r\nValueError: invalid literal for float(): 26761555,805674\r\n\r\n",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def populate(self):
    self.module.run_command_environ_update = {
        "LANG": "C",
        "LC_ALL": "C",
        "LC_NUMERIC": "C",
    }
    self.get_cpu_facts()
    self.get_memory_facts()
    self.get_dmi_facts()
    self.get_device_facts()
    self.get_uptime_facts()
    try:
        self.get_mount_facts()
    except TimeoutError:
        pass
    return self.facts
# Buggy code
def isintlike(x):
    """Is x appropriate as an index into a sparse matrix? Returns True
    if it can be cast safely to a machine int.
    """
    if issequence(x):
        return False
    else:
        try:
            if int(x) == x:
                return True
            else:
                return False
        except TypeError:
            return False


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/jbw/data/src/kwant/python3-env/lib/python3.4/site-packages/nose/case.py", line 198, in runTest
self.test(*self.arg)
File "/home/jbw/data/src/kwant/python3-env/lib/python3.4/site-packages/kwant/tests/test_system.py", line 33, in test_hamiltonian_submatrix
mat = sys2.hamiltonian_submatrix(sparse=True)
File "kwant/_system.pyx", line 313, in kwant._system.hamiltonian_submatrix (kwant/_system.c:8029)
File "kwant/_system.pyx", line 151, in kwant._system.make_sparse_full (kwant/_system.c:4482)
File "/home/jbw/data/src/kwant/python3-env/lib/python3.4/site-packages/scipy/sparse/coo.py", line 120, in __init__
if isshape(arg1):
File "/home/jbw/data/src/kwant/python3-env/lib/python3.4/site-packages/scipy/sparse/sputils.py", line 212, in isshape
if isintlike(M) and isintlike(N):
File "/home/jbw/data/src/kwant/python3-env/lib/python3.4/site-packages/scipy/sparse/sputils.py", line 195, in isintlike
if int(x) == x:
ValueError: invalid literal for int() with base 10: b'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\x00\x00\x00

# Fixed code
def isintlike(x):
    """Is x appropriate as an index into a sparse matrix? Returns True
    if it can be cast safely to a machine int.
    """
    if issequence(x):
        return False
    try:
        return bool(int(x) == x)
    except (TypeError, ValueError):
        return False
# Buggy code
def cachedir_index_del(minion_id, base=None):
    """
    Delete an entry from the cachedir index. This generally only needs to happen
    when an instance is deleted.
    """
    base = init_cachedir(base)
    index_file = os.path.join(base, "index.p")
    lock_file(index_file)

    if os.path.exists(index_file):
        with salt.utils.fopen(index_file, "r") as fh_:
            index = msgpack.load(fh_)
    else:
        return

    if minion_id in index:
        del index[minion_id]

    with salt.utils.fopen(index_file, "w") as fh_:
        msgpack.dump(index, fh_)

    unlock_file(index_file)


# Traceback (UnicodeEncodeError)
$ salt-call -l trace cloud.full_query
.....
[DEBUG   ] Failed to execute 'ec2.list_nodes_min()' while querying for running nodes: 'ascii' codec can't encode characters in position 70860-70863: ordinal not in range(128)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 2198, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/ec2.py", line 2720, in list_nodes_min
instances = query(params)
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/ec2.py", line 345, in query
result.text
UnicodeEncodeError: 'ascii' codec can't encode characters in position 70860-70863: ordinal not in range(128)
......

# Fixed code
def cachedir_index_del(minion_id, base=None):
    """
    Delete an entry from the cachedir index. This generally only needs to happen
    when an instance is deleted.
    """
    base = init_cachedir(base)
    index_file = os.path.join(base, "index.p")
    lock_file(index_file)

    if os.path.exists(index_file):
        with salt.utils.fopen(index_file, "r") as fh_:
            index = msgpack.load(fh_, encoding=MSGPACK_ENCODING)
    else:
        return

    if minion_id in index:
        del index[minion_id]

    with salt.utils.fopen(index_file, "w") as fh_:
        msgpack.dump(index, fh_, encoding=MSGPACK_ENCODING)

    unlock_file(index_file)
# Buggy code
def _update_magp_data(self, magp_data):
    for magp_item in magp_data:
        magp_id = self.get_magp_id(magp_item)
        inst_data = self._create_magp_instance_data(magp_id, magp_item)
        self._current_config[magp_id] = inst_data


# Traceback (nAttributeError)
fatal: [sn2410_leaf1_1]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 227, in <module>\n    main()\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 223, in main\n    OnyxMagpModule.main()\n  File \"/tmp/ansible_2cIQBk/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 240, in main\n  File \"/tmp/ansible_2cIQBk/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 218, in run\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 150, in load_current_config\n    self._update_magp_data(magp_data)\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 137, in _update_magp_data\n    magp_id = self.get_magp_id(magp_item)\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 123, in get_magp_id\n    return int(header.split()[1])\nAttributeError: 'NoneType' object has no attribute 'split'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def _update_magp_data(self, magp_data):
    if self._os_version >= self.ONYX_API_VERSION:
        for magp_config in magp_data:
            for magp_name, data in iteritems(magp_config):
                magp_id = int(magp_name.replace("MAGP ", ""))
                self._current_config[magp_id] = self._create_magp_instance_data(
                    magp_id, data[0]
                )
    else:
        for magp_item in magp_data:
            magp_id = self.get_magp_id(magp_item)
            inst_data = self._create_magp_instance_data(magp_id, magp_item)
            self._current_config[magp_id] = inst_data
# Buggy code
def make_main(argv=sys.argv):
    """Sphinx build "make mode" entry."""
    warnings.warn(
        "`sphinx.build_main()` has moved to `sphinx.cmd.build.make_main()`.",
        RemovedInSphinx20Warning,
        stacklevel=2,
    )
    return build.make_main(
        argv[1:]
    )  # skip first argument to adjust arguments (refs: #4615)


# Traceback (NameError)
Traceback (most recent call last):
File "./build-deploy.py", line 141, in <module>
errno = build_html(args.sourcedir, args.outputdir, args.branch, args.nitpicky, args.force)
File "./build-deploy.py", line 65, in build_html
errno = _sphinx_build(arglist)
File "./build-deploy.py", line 44, in _sphinx_build
return sphinx.make_main(arglist)
File "/usr/local/lib/python3.6/site-packages/sphinx/__init__.py", line 91, in make_main
return build.make_main(argv[1:])  # skip first argument to adjust arguments (refs: #4615)
NameError: name 'build' is not defined

# Fixed code
def make_main(argv=sys.argv):
    """Sphinx build "make mode" entry."""
    from .cmd import build

    warnings.warn(
        "`sphinx.build_main()` has moved to `sphinx.cmd.build.make_main()`.",
        RemovedInSphinx20Warning,
        stacklevel=2,
    )
    return build.make_main(
        argv[1:]
    )  # skip first argument to adjust arguments (refs: #4615)
# Buggy code
def transform(self, y):
    """Transform labels to normalized encoding.

    Parameters
    ----------
    y : array-like of shape [n_samples]
        Target values.

    Returns
    -------
    y : array-like of shape [n_samples]
    """
    check_is_fitted(self, "classes_")
    y = column_or_1d(y, warn=True)

    classes = np.unique(y)
    if len(np.intersect1d(classes, self.classes_)) < len(classes):
        diff = np.setdiff1d(classes, self.classes_)
        raise ValueError("y contains previously unseen labels: %s" % str(diff))
    return np.searchsorted(self.classes_, y)


# Traceback (TypeError)
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit([1,2])
LabelEncoder()
le.transform([])
array([], dtype=int64)
le.fit(["a","b"])
LabelEncoder()
le.transform([])
Traceback (most recent call last):
File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 57, in _wrapfunc
return getattr(obj, method)(*args, **kwds)
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[...]\Python36\lib\site-packages\sklearn\preprocessing\label.py", line 134, in transform
return np.searchsorted(self.classes_, y)
File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 1075, in searchsorted
return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 67, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "[...]\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 47, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'

# Fixed code
def transform(self, y):
    """Transform labels to normalized encoding.

    Parameters
    ----------
    y : array-like of shape [n_samples]
        Target values.

    Returns
    -------
    y : array-like of shape [n_samples]
    """
    check_is_fitted(self, "classes_")
    y = column_or_1d(y, warn=True)
    # transform of empty array is empty array
    if _num_samples(y) == 0:
        return np.array([])

    classes = np.unique(y)
    if len(np.intersect1d(classes, self.classes_)) < len(classes):
        diff = np.setdiff1d(classes, self.classes_)
        raise ValueError("y contains previously unseen labels: %s" % str(diff))
    return np.searchsorted(self.classes_, y)
# Buggy code
def parse_txt_dict(data, msg):
    """Parse DNS TXT record containing a dict."""
    output = {}
    txt, _ = qname_decode(data, msg, raw=True)
    for prop in txt:
        key, value = prop.split(b"=")
        output[key] = value
    return output


# Traceback (ValueError)
$ atvremote scan -s 192.168.0.6
ERROR: Exception in callback _SelectorDatagramTransport._read_ready()
handle: <Handle _SelectorDatagramTransport._read_ready()>
Traceback (most recent call last):
File "/usr/lib/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 1068, in _read_ready
self._protocol.datagram_received(data, addr)
File "/home/jacob/.local/lib/python3.6/site-packages/pyatv/udns.py", line 229, in datagram_received
self.result = DnsMessage().unpack(data)
File "/home/jacob/.local/lib/python3.6/site-packages/pyatv/udns.py", line 147, in unpack
ptr, data = unpack_rr(ptr, msg)
File "/home/jacob/.local/lib/python3.6/site-packages/pyatv/udns.py", line 98, in unpack_rr
rd_data = parse_txt_dict(rd_data, msg)
File "/home/jacob/.local/lib/python3.6/site-packages/pyatv/udns.py", line 58, in parse_txt_dict
key, value = prop.split(b'=')
ValueError: too many values to unpack (expected 2)
Scan Results
========================================

# Fixed code
def parse_txt_dict(data, msg):
    """Parse DNS TXT record containing a dict."""
    output = {}
    txt, _ = qname_decode(data, msg, raw=True)
    for prop in txt:
        key, value = prop.split(b"=", 1)
        output[key] = value
    return output
# Buggy code
def batch_to(data):
    # try to move torchtext data first
    if TORCHTEXT_AVAILABLE and isinstance(data, Batch):
        # Shallow copy because each Batch has a reference to Dataset which contains all examples
        device_data = copy(data)
        for field in data.fields:
            device_field = move_data_to_device(getattr(data, field), device)
            setattr(device_data, field, device_field)
        return device_data

    kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}
    return data.to(device, **kwargs)


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-bd904d609559> in <module>()
----> 1 test_x(tmpdir)  # works when using no gpu

15 frames
/usr/local/lib/python3.6/dist-packages/pytorch_lightning/utilities/apply_func.py in batch_to(data)
115             device_data = copy(data)
116             for field in data.fields:
--> 117                 device_field = move_data_to_device(getattr(data, field), device)
118                 setattr(device_data, field, device_field)
119             return device_data

AttributeError: 'Batch' object has no attribute 'TITLE'

# Fixed code
def batch_to(data):
    # try to move torchtext data first
    if TORCHTEXT_AVAILABLE and isinstance(data, Batch):
        # Shallow copy because each Batch has a reference to Dataset which contains all examples
        device_data = copy(data)
        for field, field_value in data.dataset.fields.items():
            if field_value is None:
                continue
            device_field = move_data_to_device(getattr(data, field), device)
            setattr(device_data, field, device_field)
        return device_data

    kwargs = dict(non_blocking=True) if isinstance(data, torch.Tensor) else {}
    return data.to(device, **kwargs)
# Buggy code
def _wait_for_task(task, vm_name, task_type, sleep_seconds=1, log_level="debug"):
    time_counter = 0
    starttime = time.time()
    while task.info.state == "running":
        if time_counter % sleep_seconds == 0:
            message = "[ {0} ] Waiting for {1} task to finish [{2} s]".format(
                vm_name, task_type, time_counter
            )
            if log_level == "info":
                log.info(message)
            else:
                log.debug(message)
        time.sleep(1.0 - ((time.time() - starttime) % 1.0))
        time_counter += 1
    if task.info.state == "success":
        message = "[ {0} ] Successfully completed {1} task in {2} seconds".format(
            vm_name, task_type, time_counter
        )
        if log_level == "info":
            log.info(message)
        else:
            log.debug(message)
    else:
        raise Exception(task.info.error)


# Traceback (Exception)
[ERROR   ] Error creating <machine>: None
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/vmware.py", line 2446, in create
_wait_for_task(task, vm_name, "clone", 5, 'info')
File "/usr/lib/python2.7/dist-packages/salt/cloud/clouds/vmware.py", line 823, in _wait_for_task
raise Exception(task.info.error)
Exception: None
[DEBUG   ] LazyLoaded nested.output
<machine>:
----------
Error:
Error creating <machine>: None

# Fixed code
def _wait_for_task(task, vm_name, task_type, sleep_seconds=1, log_level="debug"):
    time_counter = 0
    starttime = time.time()
    while task.info.state == "running" or task.info.state == "queued":
        if time_counter % sleep_seconds == 0:
            message = "[ {0} ] Waiting for {1} task to finish [{2} s]".format(
                vm_name, task_type, time_counter
            )
            if log_level == "info":
                log.info(message)
            else:
                log.debug(message)
        time.sleep(1.0 - ((time.time() - starttime) % 1.0))
        time_counter += 1
    if task.info.state == "success":
        message = "[ {0} ] Successfully completed {1} task in {2} seconds".format(
            vm_name, task_type, time_counter
        )
        if log_level == "info":
            log.info(message)
        else:
            log.debug(message)
    else:
        raise Exception(task.info.error)
# Buggy code
@classmethod
    def write_content(cls, filename, content, rewrite_html=True):
        """Write content to file."""
        if rewrite_html:
            doc = html.document_fromstring(content)
            doc.rewrite_links(replacer)
            content = html.tostring(doc, encoding='utf8')
        else:
            content = content.encode('utf-8')

        utils.makedirs(os.path.dirname(filename))
        with open(filename, "wb+") as fd:
            fd.write(content)


# Traceback (lxml.etree.ParserError)
$ nikola import_wordpress /Users/davidak/Downloads/davidakweblog.wordpress.2016-02-23.xml
[2016-02-23T17:06:37Z] NOTICE: Nikola: The folder new_site already exists - assuming that this is a already existing Nikola site.
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/doit/doit_cmd.py", line 168, in run
return command.parse_execute(args)
File "/usr/local/lib/python3.5/site-packages/doit/cmd_base.py", line 122, in parse_execute
return self.execute(params, args)
File "/usr/local/lib/python3.5/site-packages/nikola/plugin_categories.py", line 124, in execute
return self._execute(options, args)
File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 332, in _execute
self.import_posts(channel)
File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 1015, in import_posts
self.process_item_if_post_or_page(item)
File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 996, in process_item_if_post_or_page
out_folder_slug = self.import_postpage_item(item, wordpress_namespace, 'posts', attachments)
File "/usr/local/lib/python3.5/site-packages/nikola/plugins/command/import_wordpress.py", line 938, in import_postpage_item
rewrite_html)
File "/usr/local/lib/python3.5/site-packages/nikola/plugins/basic_import.py", line 130, in write_content
doc = html.document_fromstring(content)
File "/usr/local/lib/python3.5/site-packages/lxml/html/__init__.py", line 755, in document_fromstring
"Document is empty")
lxml.etree.ParserError: Document is empty

# Fixed code
@classmethod
    def write_content(cls, filename, content, rewrite_html=True):
        """Write content to file."""
        if rewrite_html:
            try:
                doc = html.document_fromstring(content)
                doc.rewrite_links(replacer)
                content = html.tostring(doc, encoding='utf8')
            except etree.ParserError:
                content = content.encode('utf-8')
        else:
            content = content.encode('utf-8')

        utils.makedirs(os.path.dirname(filename))
        with open(filename, "wb+") as fd:
            fd.write(content)
# Buggy code
def setup_vpn(runner: Runner, args):
    runner.require(
        ["sshuttle-telepresence"], "Part of the Telepresence package. Try reinstalling."
    )
    if runner.platform == "linux":
        # Need conntrack for sshuttle on Linux:
        runner.require(["conntrack", "iptables"], "Required for the vpn-tcp method")
    if runner.platform == "darwin":
        runner.require(["pfctl"], "Required for the vpn-tcp method")
    runner.require_sudo()
    if runner.chatty:
        runner.show(
            "Starting proxy with method 'vpn-tcp', which has the following "
            "limitations: All processes are affected, only one telepresence "
            "can run per machine, and you can't use other VPNs. You may need "
            "to add cloud hosts and headless services with --also-proxy. For "
            "a full list of method limitations see "
            "https://telepresence.io/reference/methods.html"
        )
    command = args.run or ["bash--norc"]

    def launch(runner_, remote_info, env, _socks_port, ssh, _mount_dir):
        return launch_vpn(runner_, remote_info, command, args.also_proxy, env, ssh)

    return launch


# Traceback (FileNotFoundError)
Traceback (most recent call last):
File "/usr/bin/telepresence/telepresence/cli.py", line 129, in crash_reporting
yield
File "/usr/bin/telepresence/telepresence/main.py", line 78, in main
runner, remote_info, env, socks_port, ssh, mount_dir
File "/usr/bin/telepresence/telepresence/outbound/__init__.py", line 60, in launch
runner_, remote_info, command, args.also_proxy, env, ssh
File "/usr/bin/telepresence/telepresence/outbound/local.py", line 123, in launch_vpn
process = Popen(command, env=env)
File "/usr/lib64/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/usr/lib64/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'bash--norc': 'bash--norc'

# Fixed code
def setup_vpn(runner: Runner, args):
    runner.require(
        ["sshuttle-telepresence"], "Part of the Telepresence package. Try reinstalling."
    )
    if runner.platform == "linux":
        # Need conntrack for sshuttle on Linux:
        runner.require(["conntrack", "iptables"], "Required for the vpn-tcp method")
    if runner.platform == "darwin":
        runner.require(["pfctl"], "Required for the vpn-tcp method")
    runner.require_sudo()
    if runner.chatty:
        runner.show(
            "Starting proxy with method 'vpn-tcp', which has the following "
            "limitations: All processes are affected, only one telepresence "
            "can run per machine, and you can't use other VPNs. You may need "
            "to add cloud hosts and headless services with --also-proxy. For "
            "a full list of method limitations see "
            "https://telepresence.io/reference/methods.html"
        )
    command = args.run or ["bash", "--norc"]

    def launch(runner_, remote_info, env, _socks_port, ssh, _mount_dir):
        return launch_vpn(runner_, remote_info, command, args.also_proxy, env, ssh)

    return launch
# Buggy code
def validateMasterArgument(self, master_arg):
    """
    Parse the <master> argument.

    @param master_arg: the <master> argument to parse

    @return: tuple of master's host and port
    @raise UsageError: on errors parsing the argument
    """
    if master_arg[:5] == "http:":
        raise usage.UsageError("<master> is not a URL - do not use URL")

    if ":" not in master_arg:
        master = master_arg
        port = 9989
    else:
        master, port = master_arg.split(":")

    if not master:
        raise usage.UsageError("invalid <master> argument '{}'".format(master_arg))
    try:
        port = int(port)
    except ValueError:
        raise usage.UsageError(
            "invalid master port '{}', needs to be a number".format(port)
        )

    return master, port


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/bin/buildbot-worker", line 11, in <module>
load_entry_point('buildbot-worker==2.0.1.post2', 'console_scripts', 'buildbot-worker')()
File "/usr/lib/python3/dist-packages/buildbot_worker/scripts/runner.py", line 238, in run
config.parseOptions()
File "/usr/lib/python3/dist-packages/twisted/python/usage.py", line 267, in parseOptions
self.subOptions.parseOptions(rest)
File "/usr/lib/python3/dist-packages/twisted/python/usage.py", line 273, in parseOptions
self.parseArgs(*args)
File "/usr/lib/python3/dist-packages/buildbot_worker/scripts/runner.py", line 183, in parseArgs
self['host'], self['port'] = self.validateMasterArgument(master)
File "/usr/lib/python3/dist-packages/buildbot_worker/scripts/runner.py", line 161, in validateMasterArgument
master, port = master_arg.split(":")
ValueError: too many values to unpack (expected 2)

# Fixed code
def validateMasterArgument(self, master_arg):
    """
    Parse the <master> argument.

    @param master_arg: the <master> argument to parse

    @return: tuple of master's host and port
    @raise UsageError: on errors parsing the argument
    """
    if master_arg[:5] == "http:":
        raise usage.UsageError("<master> is not a URL - do not use URL")

    if master_arg.startswith("[") and "]" in master_arg:
        # detect ipv6 address with format [2001:1:2:3:4::1]:4321
        master, port_tmp = master_arg.split("]")
        master = master[1:]
        if ":" not in port_tmp:
            port = 9989
        else:
            port = port_tmp.split(":")[1]

    elif ":" not in master_arg:
        master = master_arg
        port = 9989
    else:
        try:
            master, port = master_arg.split(":")
        except ValueError:
            raise usage.UsageError(
                "invalid <master> argument '{}', "
                "if it is an ipv6 address, it must be enclosed by []".format(master_arg)
            )

    if not master:
        raise usage.UsageError("invalid <master> argument '{}'".format(master_arg))
    try:
        port = int(port)
    except ValueError:
        raise usage.UsageError(
            "invalid master port '{}', needs to be a number".format(port)
        )

    return master, port
# Buggy code
def object_description(object):
    # type: (Any) -> unicode
    """A repr() implementation that returns text safe to use in reST context."""
    if isinstance(object, dict):
        try:
            sorted_keys = sorted(object)
        except TypeError:
            pass  # Cannot sort dict keys, fall back to generic repr
        else:
            items = (
                "%s: %s" % (object_description(key), object_description(object[key]))
                for key in sorted_keys
            )
            return "{%s}" % ", ".join(items)
    if isinstance(object, set):
        try:
            sorted_values = sorted(object)
        except TypeError:
            pass  # Cannot sort set values, fall back to generic repr
        else:
            template = "{%s}" if PY3 else "set([%s])"
            return template % ", ".join(object_description(x) for x in sorted_values)
    try:
        s = repr(object)
    except Exception:
        raise ValueError
    if isinstance(s, binary_type):
        s = force_decode(s, None)  # type: ignore
    # Strip non-deterministic memory addresses such as
    # ``<__main__.A at 0x7f68cb685710>``
    s = memory_address_re.sub("", s)
    return s.replace("\n", " ")


# Traceback (KeyError)
Traceback (most recent call last):
......
File "/usr/lib/python2.7/site-packages/sphinx/ext/autodoc/__init__.py", line 1252, in add_directive_header
objrepr = object_description(self.object)
File "/usr/lib/python2.7/site-packages/sphinx/util/inspect.py", line 243, in object_description
sorted_keys = sorted(object)
File "/opt/fabrix/fabrix/config.py", line 59, in __iter__
return self.__super__getitem__(env.host_string).__iter__()
KeyError: None

# Fixed code
def object_description(object):
    # type: (Any) -> unicode
    """A repr() implementation that returns text safe to use in reST context."""
    if isinstance(object, dict):
        try:
            sorted_keys = sorted(object)
        except Exception:
            pass  # Cannot sort dict keys, fall back to generic repr
        else:
            items = (
                "%s: %s" % (object_description(key), object_description(object[key]))
                for key in sorted_keys
            )
            return "{%s}" % ", ".join(items)
    if isinstance(object, set):
        try:
            sorted_values = sorted(object)
        except TypeError:
            pass  # Cannot sort set values, fall back to generic repr
        else:
            template = "{%s}" if PY3 else "set([%s])"
            return template % ", ".join(object_description(x) for x in sorted_values)
    try:
        s = repr(object)
    except Exception:
        raise ValueError
    if isinstance(s, binary_type):
        s = force_decode(s, None)  # type: ignore
    # Strip non-deterministic memory addresses such as
    # ``<__main__.A at 0x7f68cb685710>``
    s = memory_address_re.sub("", s)
    return s.replace("\n", " ")
# Buggy code
def get_current_subtitles(video_path):
    """Returns a list of current subtitles for the episode

    :param video_path: the video path
    :return: the current subtitles for the specified video
    """
    video = get_video(video_path)
    if not video:
        logger.log(
            "Exception caught in subliminal.scan_video, subtitles couldn't be refreshed",
            logger.DEBUG,
        )
    else:
        return get_subtitles(video)


# Traceback (TypeError)
2016-04-05 12:05:53 FINDSUBTITLES :: [a90e41d] Traceback (most recent call last):
File "/home/dariox/.sickrage/sickbeard/subtitles.py", line 325, in download_best_subs
get_subtitle_description(subtitle)), logger.DEBUG)
File "/home/dariox/.sickrage/sickbeard/subtitles.py", line 489, in get_subtitle_description
return subtitle.id + '-' + desc if desc not in subtitle.id else desc
TypeError: argument of type 'int' is not iterable

# Fixed code
def get_current_subtitles(video_path):
    """Returns a list of current subtitles for the episode

    :param video_path: the video path
    :type video_path: str
    :return: the current subtitles (3-letter opensubtitles codes) for the specified video
    :rtype: list of str
    """
    video = get_video(video_path)
    if not video:
        logger.log(
            "Exception caught in subliminal.scan_video, subtitles couldn't be refreshed",
            logger.DEBUG,
        )
    else:
        return get_subtitles(video)