gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _get_pointer(self):
    if (
        self.thisdir is not None
        and self.thisdir.files[self._pointer] != self._pointed_obj
    ):
        try:
            self._pointer = self.thisdir.files.index(self._pointed_obj)
        except ValueError:
            self._pointed_obj = self.thisdir.files[self._pointer]
    return self._pointer


# Traceback (TypeError)
$ ranger --clean                                                          (ai)
ranger version: ranger-master
Python version: 3.8.6 (default, Sep 30 2020, 04:00:38) [GCC 10.2.0]
Locale: en_GB.UTF-8

Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/ranger/core/main.py", line 203, in main
fm.loop()
File "/usr/lib/python3.8/site-packages/ranger/core/fm.py", line 382, in loop
ui.handle_input()
File "/usr/lib/python3.8/site-packages/ranger/gui/ui.py", line 276, in handle_input
self.handle_key(key)
File "/usr/lib/python3.8/site-packages/ranger/gui/ui.py", line 206, in handle_key
elif not DisplayableContainer.press(self, key):
File "/usr/lib/python3.8/site-packages/ranger/gui/displayable.py", line 272, in press
focused_obj.press(key)
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 189, in press
self.type_key(key)
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 218, in type_key
self.on_line_change()
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 514, in on_line_change
self.execute(cmd)
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 454, in execute
cmd.execute()
File "/usr/lib/python3.8/site-packages/ranger/config/commands.py", line 1521, in execute
self.fm.move(right=1)
File "/usr/lib/python3.8/site-packages/ranger/core/actions.py", line 499, in move
self.thistab.enter_dir(tfile)
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 183, in enter_dir
self.thisfile = self.thisdir.pointed_obj
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 52, in _set_thisfile
self.fm.signal_emit('move', previous=previous, new=value, tab=self)
File "/usr/lib/python3.8/site-packages/ranger/ext/signals.py", line 268, in signal_emit
fnc(signal)
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 40, in _set_thisfile_from_signal
self.pointer = self.thisdir.pointer
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 72, in _set_pointer
self._pointed_obj = self.thisdir.files[self._pointer]
TypeError: 'NoneType' object is not subscriptable

ranger crashed. Please report this traceback at:
https://github.com/ranger/ranger/issues

# Fixed code
def _get_pointer(self):
    try:
        if self.thisdir.files[self._pointer] != self._pointed_obj:
            try:
                self._pointer = self.thisdir.files.index(self._pointed_obj)
            except ValueError:
                self._set_pointer(self._pointer)
    except (TypeError, IndexError):
        pass
    return self._pointer
# Buggy code
def _set_pointer(self, value):
    self._pointer = value
    try:
        self._pointed_obj = self.thisdir.files[self._pointer]
    except TypeError:
        pass
    except IndexError:
        pass


# Traceback (TypeError)
$ ranger --clean                                                          (ai)
ranger version: ranger-master
Python version: 3.8.6 (default, Sep 30 2020, 04:00:38) [GCC 10.2.0]
Locale: en_GB.UTF-8

Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/ranger/core/main.py", line 203, in main
fm.loop()
File "/usr/lib/python3.8/site-packages/ranger/core/fm.py", line 382, in loop
ui.handle_input()
File "/usr/lib/python3.8/site-packages/ranger/gui/ui.py", line 276, in handle_input
self.handle_key(key)
File "/usr/lib/python3.8/site-packages/ranger/gui/ui.py", line 206, in handle_key
elif not DisplayableContainer.press(self, key):
File "/usr/lib/python3.8/site-packages/ranger/gui/displayable.py", line 272, in press
focused_obj.press(key)
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 189, in press
self.type_key(key)
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 218, in type_key
self.on_line_change()
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 514, in on_line_change
self.execute(cmd)
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/console.py", line 454, in execute
cmd.execute()
File "/usr/lib/python3.8/site-packages/ranger/config/commands.py", line 1521, in execute
self.fm.move(right=1)
File "/usr/lib/python3.8/site-packages/ranger/core/actions.py", line 499, in move
self.thistab.enter_dir(tfile)
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 183, in enter_dir
self.thisfile = self.thisdir.pointed_obj
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 52, in _set_thisfile
self.fm.signal_emit('move', previous=previous, new=value, tab=self)
File "/usr/lib/python3.8/site-packages/ranger/ext/signals.py", line 268, in signal_emit
fnc(signal)
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 40, in _set_thisfile_from_signal
self.pointer = self.thisdir.pointer
File "/usr/lib/python3.8/site-packages/ranger/core/tab.py", line 72, in _set_pointer
self._pointed_obj = self.thisdir.files[self._pointer]
TypeError: 'NoneType' object is not subscriptable

ranger crashed. Please report this traceback at:
https://github.com/ranger/ranger/issues

# Fixed code
def _set_pointer(self, value):
    self._pointer = value
    try:
        self._pointed_obj = self.thisdir.files[self._pointer]
    except (TypeError, IndexError):
        pass
# Buggy code
def _set_pointer(self, value):
    self._pointer = value
    self._pointed_obj = self.thisdir.files[self._pointer]


# Traceback (TypeError)
Message Log:
21:48:19 INFO ranger version: ranger-master
21:48:19 INFO Python version: 3.8.5 (default, Jul 27 2020, 08:42:51) [GCC 10.1.0]
21:48:19 INFO Locale: en_US.UTF-8
21:48:19 INFO Process ID: 73182
21:48:25 ERRO Notification: 'NoneType' object is not subscriptable
21:48:25 ERRO 'NoneType' object is not subscriptable
Traceback (most recent call last):
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/actions.py", line 269, in execute_console
cmd.execute()
File "/home/kevin/.config/ranger/plugins/fzf_find.py", line 31, in execute
self.fm.cd(fzf_file)
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/actions.py", line 600, in cd
self.enter_dir(path, remember=remember)
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/actions.py", line 585, in enter_dir
result = self.thistab.enter_dir(path, history=history)
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/tab.py", line 183, in enter_dir
self.thisfile = self.thisdir.pointed_obj
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/tab.py", line 52, in _set_thisfile
self.fm.signal_emit('move', previous=previous, new=value, tab=self)
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/ext/signals.py", line 268, in signal_emit
fnc(signal)
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/tab.py", line 40, in _set_thisfile_from_signal
self.pointer = self.thisdir.pointer
File "/home/kevin/.local/lib/python3.8/site-packages/ranger/core/tab.py", line 72, in _set_pointer
self._pointed_obj = self.thisdir.files[self._pointer]
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def _set_pointer(self, value):
    self._pointer = value
    try:
        self._pointed_obj = self.thisdir.files[self._pointer]
    except (TypeError, IndexError):
        pass
# Buggy code
def _set_pointer(self, value):
    self._pointer = value
    try:
        self._pointed_obj = self.thisdir.files[self._pointer]
    except TypeError:
        pass


# Traceback (IndexError)
ranger version: ranger-master
Python version: 3.9.0 (default, Oct  7 2020, 23:09:01) [GCC 10.2.0]
Locale: en_IN.UTF-8

Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/ranger/core/main.py", line 203, in main
fm.loop()
File "/usr/lib/python3.9/site-packages/ranger/core/fm.py", line 382, in loop
ui.handle_input()
File "/usr/lib/python3.9/site-packages/ranger/gui/ui.py", line 271, in handle_input
self.handle_mouse()
File "/usr/lib/python3.9/site-packages/ranger/gui/ui.py", line 197, in handle_mouse
DisplayableContainer.click(self, event)
File "/usr/lib/python3.9/site-packages/ranger/gui/displayable.py", line 284, in click
if displayable.click(event):
File "/usr/lib/python3.9/site-packages/ranger/gui/widgets/view_base.py", line 188, in click
if DisplayableContainer.click(self, event):
File "/usr/lib/python3.9/site-packages/ranger/gui/displayable.py", line 284, in click
if displayable.click(event):
File "/usr/lib/python3.9/site-packages/ranger/gui/widgets/browsercolumn.py", line 86, in click
self.fm.enter_dir(self.target.path)
File "/usr/lib/python3.9/site-packages/ranger/core/actions.py", line 585, in enter_dir
result = self.thistab.enter_dir(path, history=history)
File "/usr/lib/python3.9/site-packages/ranger/core/tab.py", line 183, in enter_dir
self.thisfile = self.thisdir.pointed_obj
File "/usr/lib/python3.9/site-packages/ranger/core/tab.py", line 52, in _set_thisfile
self.fm.signal_emit('move', previous=previous, new=value, tab=self)
File "/usr/lib/python3.9/site-packages/ranger/ext/signals.py", line 268, in signal_emit
fnc(signal)
File "/usr/lib/python3.9/site-packages/ranger/core/tab.py", line 40, in _set_thisfile_from_signal
self.pointer = self.thisdir.pointer
File "/usr/lib/python3.9/site-packages/ranger/core/tab.py", line 72, in _set_pointer
self._pointed_obj = self.thisdir.files[self._pointer]
IndexError: list index out of range

# Fixed code
def _set_pointer(self, value):
    self._pointer = value
    try:
        self._pointed_obj = self.thisdir.files[self._pointer]
    except TypeError:
        pass
    except IndexError:
        pass
# Buggy code
def sha512_encode(path, inode=None):
    if inode is None:
        inode = stat(path).st_ino
    inode_path = "{0}{1}".format(str(inode), path)
    if PY3:
        inode_path = inode_path.encode("utf-8", "backslashescape")
    return "{0}.jpg".format(sha512(inode_path).hexdigest())


# Traceback (LookupError)
ranger version: ranger-master
Python version: 3.8.5 (default, Sep  5 2020, 10:50:12) [GCC 10.2.0]
Locale: de_DE.UTF-8
Current file: '/path/to/my/file/Arbeitszeitnachweis_f\udc81r Minijobber_2020_09.PDF'

Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/ranger/core/main.py", line 203, in main
fm.loop()
File "/usr/lib/python3.8/site-packages/ranger/core/fm.py", line 376, in loop
ui.redraw()
File "/usr/lib/python3.8/site-packages/ranger/gui/ui.py", line 343, in redraw
self.draw()
File "/usr/lib/python3.8/site-packages/ranger/gui/ui.py", line 370, in draw
DisplayableContainer.draw(self)
File "/usr/lib/python3.8/site-packages/ranger/gui/displayable.py", line 257, in draw
displayable.draw()
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/view_miller.py", line 100, in draw
DisplayableContainer.draw(self)
File "/usr/lib/python3.8/site-packages/ranger/gui/displayable.py", line 257, in draw
displayable.draw()
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/browsercolumn.py", line 187, in draw
self._draw_file()
File "/usr/lib/python3.8/site-packages/ranger/gui/widgets/browsercolumn.py", line 206, in _draw_file
path = self.target.get_preview_source(self.wid, self.hei)
File "/usr/lib/python3.8/site-packages/ranger/container/file.py", line 96, in get_preview_source
return self.fm.get_preview(self, width, height)
File "/usr/lib/python3.8/site-packages/ranger/core/actions.py", line 1101, in get_preview
self.sha512_encode(path, inode=fobj.stat.st_ino)
File "/usr/lib/python3.8/site-packages/ranger/core/actions.py", line 1028, in sha512_encode
inode_path = inode_path.encode('utf-8', 'backslashescape')
LookupError: unknown error handler name 'backslashescape'

ranger crashed. Please report this traceback at:
https://github.com/ranger/ranger/issues

# Fixed code
def sha512_encode(path, inode=None):
    if inode is None:
        inode = stat(path).st_ino
    inode_path = "{0}{1}".format(str(inode), path)
    if PY3:
        inode_path = inode_path.encode("utf-8", "backslashreplace")
    return "{0}.jpg".format(sha512(inode_path).hexdigest())
# Buggy code
def sha512_encode(path, inode=None):
    if inode is None:
        inode = stat(path).st_ino
    sha = sha512("{0}{1}".format(path, str(inode)).encode("utf-8", "backslashescape"))
    return "{0}.jpg".format(sha.hexdigest())


# Traceback (UnicodeDecodeError)
Current file: '/tmp/example_f\xc2\xa1le.txt'

Traceback (most recent call last):
File "/home/panta/programs/ranger/ranger/core/main.py", line 203, in main
fm.loop()
File "/home/panta/programs/ranger/ranger/core/fm.py", line 376, in loop
ui.redraw()
File "/home/panta/programs/ranger/ranger/gui/ui.py", line 343, in redraw
self.draw()
File "/home/panta/programs/ranger/ranger/gui/ui.py", line 370, in draw
DisplayableContainer.draw(self)
File "/home/panta/programs/ranger/ranger/gui/displayable.py", line 257, in draw
displayable.draw()
File "/home/panta/programs/ranger/ranger/gui/widgets/view_miller.py", line 100, in draw
DisplayableContainer.draw(self)
File "/home/panta/programs/ranger/ranger/gui/displayable.py", line 257, in draw
displayable.draw()
File "/home/panta/programs/ranger/ranger/gui/widgets/browsercolumn.py", line 187, in draw
self._draw_file()
File "/home/panta/programs/ranger/ranger/gui/widgets/browsercolumn.py", line 206, in _draw_file
path = self.target.get_preview_source(self.wid, self.hei)
File "/home/panta/programs/ranger/ranger/container/file.py", line 96, in get_preview_source
return self.fm.get_preview(self, width, height)
File "/home/panta/programs/ranger/ranger/core/actions.py", line 1102, in get_preview
self.sha512_encode(path, inode=fobj.stat.st_ino)
File "/home/panta/programs/ranger/ranger/core/actions.py", line 1028, in sha512_encode
"{0}{1}".format(path, str(inode)).encode('utf-8', 'backslashescape')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 14: ordinal not in range(128)

# Fixed code
def sha512_encode(path, inode=None):
    if inode is None:
        inode = stat(path).st_ino
    inode_path = "{0}{1}".format(str(inode), path)
    if PY3:
        inode_path = inode_path.encode("utf-8", "backslashescape")
    return "{0}.jpg".format(sha512(inode_path).hexdigest())
# Buggy code
def __init__(self, env=None, fm=None):  # pylint: disable=super-init-not-called
    self.keybuffer = KeyBuffer()
    self.keymaps = KeyMaps(self.keybuffer)
    self.redrawlock = threading.Event()
    self.redrawlock.set()

    self.titlebar = None
    self._viewmode = None
    self.taskview = None
    self.status = None
    self.console = None
    self.pager = None
    self.multiplexer = None
    self._draw_title = None
    self._tmux_automatic_rename = None
    self._tmux_title = None
    self._screen_title = None
    self.browser = None

    if fm is not None:
        self.fm = fm


# Traceback (FileNotFoundError)
ranger version: ranger 1.9.3
Python version: 3.7.3 (default, Apr  3 2019, 05:39:12) [GCC 8.2.0]
Locale: en_US.UTF-8

Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/ranger/core/main.py", line 171, in main
fm.initialize()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/core/fm.py", line 132, in initialize
self.ui.initialize()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/gui/ui.py", line 127, in initialize
self.handle_multiplexer()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/gui/ui.py", line 500, in handle_multiplexer
['screen', '-Q', 'title']).strip()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/ext/spawn.py", line 35, in check_output
process = Popen(popenargs, stderr=fd_devnull, **kwargs)
File "/usr/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'screen': 'screen'

ranger crashed. Please report this traceback at:
https://github.com/ranger/ranger/issu

# Fixed code
def __init__(self, env=None, fm=None):  # pylint: disable=super-init-not-called
    self.keybuffer = KeyBuffer()
    self.keymaps = KeyMaps(self.keybuffer)
    self.redrawlock = threading.Event()
    self.redrawlock.set()

    self.titlebar = None
    self._viewmode = None
    self.taskview = None
    self.status = None
    self.console = None
    self.pager = None
    self.multiplexer = None
    self._draw_title = None
    self._tmux_automatic_rename = None
    self._multiplexer_title = None
    self._multiplexer_title = None
    self.browser = None

    if fm is not None:
        self.fm = fm
# Buggy code
def restore_multiplexer_name(self):
    try:
        if "TMUX" in os.environ:
            if self._tmux_automatic_rename:
                check_output(
                    [
                        "tmux",
                        "set-window-option",
                        "automatic-rename",
                        self._tmux_automatic_rename,
                    ]
                )
            else:
                check_output(["tmux", "set-window-option", "-u", "automatic-rename"])
            if self._tmux_title:
                check_output(["tmux", "rename-window", self._tmux_title])
        elif "screen" in os.environ["TERM"] and self._screen_title:
            check_output(["screen", "-X", "title", self._screen_title])
    except CalledProcessError:
        self.fm.notify("Could not restore window-name!", bad=True)


# Traceback (FileNotFoundError)
ranger version: ranger 1.9.3
Python version: 3.7.3 (default, Apr  3 2019, 05:39:12) [GCC 8.2.0]
Locale: en_US.UTF-8

Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/ranger/core/main.py", line 171, in main
fm.initialize()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/core/fm.py", line 132, in initialize
self.ui.initialize()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/gui/ui.py", line 127, in initialize
self.handle_multiplexer()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/gui/ui.py", line 500, in handle_multiplexer
['screen', '-Q', 'title']).strip()
File "/home/pi/.local/lib/python3.7/site-packages/ranger/ext/spawn.py", line 35, in check_output
process = Popen(popenargs, stderr=fd_devnull, **kwargs)
File "/usr/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'screen': 'screen'

ranger crashed. Please report this traceback at:
https://github.com/ranger/ranger/issu

# Fixed code
def restore_multiplexer_name(self):
    if self._multiplexer_title:
        try:
            if _in_tmux():
                if self._tmux_automatic_rename:
                    check_output(
                        [
                            "tmux",
                            "set-window-option",
                            "automatic-rename",
                            self._tmux_automatic_rename,
                        ]
                    )
                else:
                    check_output(
                        ["tmux", "set-window-option", "-u", "automatic-rename"]
                    )
        except CalledProcessError:
            self.fm.notify("Could not restore multiplexer window name!", bad=True)

        sys.stdout.write("\033k{}\033\\".format(self._multiplexer_title))
        sys.stdout.flush()
# Buggy code
def data_status_root(self):
    statuses = set()

    # Paths with status
    lines = self._run(["status"]).split("\n")
    if not lines:
        return "sync"
    for line in lines:
        code = line[0]
        if code == " ":
            continue
        statuses.add(self._status_translate(code))

    for status in self.DIRSTATUSES:
        if status in statuses:
            return status
    return "sync"


# Traceback (IndexError)
Message Log:
11:12:54 INFO ranger version: ranger-master 1.9.1
11:12:54 INFO Python version: 3.6.5 (default, Aug  9 2018, 08:22:49) [GCC 5.5.0]
11:12:54 INFO Locale: en_GB.UTF-8
11:12:54 INFO Process ID: 27126
11:12:56 ERRO Notification: VCS Exception: View log for more info
11:12:56 ERRO string index out of range
Traceback (most recent call last):
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 472, in run
self._queue_process()
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 452, in _queue_process
has_vcschild = self._update_subroots(dirobj.files_all)
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 414, in _update_subroots
if not rootvcs.init_root():
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 237, in init_root
self.obj.vcsstatus = self.data_status_root()
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/svn.py", line 104, in data_status_root
code = line[0]
IndexError: string index out of range

# Fixed code
def data_status_root(self):
    statuses = set()

    # Paths with status
    lines = self._run(["status"]).split("\n")
    lines = list(filter(None, lines))
    if not lines:
        return "sync"
    for line in lines:
        code = line[0]
        if code == " ":
            continue
        statuses.add(self._status_translate(code))

    for status in self.DIRSTATUSES:
        if status in statuses:
            return status
    return "sync"
# Buggy code
def data_status_subpaths(self):
    statuses = {}

    # Paths with status
    lines = self._run(["status"]).split("\n")
    for line in lines:
        code, path = line[0], line[8:]
        if code == " ":
            continue
        statuses[os.path.normpath(path)] = self._status_translate(code)

    return statuses


# Traceback (IndexError)
Message Log:
11:12:54 INFO ranger version: ranger-master 1.9.1
11:12:54 INFO Python version: 3.6.5 (default, Aug  9 2018, 08:22:49) [GCC 5.5.0]
11:12:54 INFO Locale: en_GB.UTF-8
11:12:54 INFO Process ID: 27126
11:12:56 ERRO Notification: VCS Exception: View log for more info
11:12:56 ERRO string index out of range
Traceback (most recent call last):
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 472, in run
self._queue_process()
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 452, in _queue_process
has_vcschild = self._update_subroots(dirobj.files_all)
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 414, in _update_subroots
if not rootvcs.init_root():
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/vcs.py", line 237, in init_root
self.obj.vcsstatus = self.data_status_root()
File "/usr/lib64/python3.6/site-packages/ranger/ext/vcs/svn.py", line 104, in data_status_root
code = line[0]
IndexError: string index out of range

# Fixed code
def data_status_subpaths(self):
    statuses = {}

    # Paths with status
    lines = self._run(["status"]).split("\n")
    lines = list(filter(None, lines))
    for line in lines:
        code, path = line[0], line[8:]
        if code == " ":
            continue
        statuses[os.path.normpath(path)] = self._status_translate(code)

    return statuses
# Buggy code
def summary_str(self, end="\n") -> str:
    """Make a summary string of all of the factories."""
    rows = self._summary_rows()
    n_triples = sum(count for *_, count in rows)
    rows.append(("Total", "-", "-", n_triples))
    t = tabulate(rows, headers=["Name", "Entities", "Relations", "Triples"])
    return f"{self.__class__.__name__} (create_inverse_triples={self.create_inverse_triples})\n{t}{end}"


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def summary_str(self, title: Optional[str] = None, end="\n") -> str:
    """Make a summary string of all of the factories."""
    rows = self._summary_rows()
    n_triples = sum(count for *_, count in rows)
    rows.append(("Total", "-", "-", n_triples))
    t = tabulate(rows, headers=["Name", "Entities", "Relations", "Triples"])
    return f"{title or self.__class__.__name__} (create_inverse_triples={self.create_inverse_triples})\n{t}{end}"
# Buggy code
def summarize(self) -> None:
    """Print a summary of the dataset."""
    print(self.summary_str())


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def summarize(self, title: Optional[str] = None, file=None) -> None:
    """Print a summary of the dataset."""
    print(self.summary_str(title=title), file=file)
# Buggy code
def _load(self) -> None:
    self._training = TriplesFactory.from_path(
        path=self.training_path,
        create_inverse_triples=self.create_inverse_triples,
    )
    self._testing = TriplesFactory.from_path(
        path=self.testing_path,
        entity_to_id=self._training.entity_to_id,  # share entity index with training
        relation_to_id=self._training.relation_to_id,  # share relation index with training
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _load(self) -> None:
    self._training = TriplesFactory.from_path(
        path=self.training_path,
        create_inverse_triples=self.create_inverse_triples,
    )
    self._testing = TriplesFactory.from_path(
        path=self.testing_path,
        entity_to_id=self._training.entity_to_id,  # share entity index with training
        relation_to_id=self._training.relation_to_id,  # share relation index with training
        create_inverse_triples=self.create_inverse_triples,
    )
# Buggy code
def _load_validation(self) -> None:
    # don't call this function by itself. assumes called through the `validation`
    # property and the _training factory has already been loaded
    self._validation = TriplesFactory.from_path(
        path=self.validation_path,
        entity_to_id=self._training.entity_to_id,  # share entity index with training
        relation_to_id=self._training.relation_to_id,  # share relation index with training
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _load_validation(self) -> None:
    # don't call this function by itself. assumes called through the `validation`
    # property and the _training factory has already been loaded
    self._validation = TriplesFactory.from_path(
        path=self.validation_path,
        entity_to_id=self._training.entity_to_id,  # share entity index with training
        relation_to_id=self._training.relation_to_id,  # share relation index with training
        create_inverse_triples=self.create_inverse_triples,
    )
# Buggy code
def generate_triples(
    num_entities: int = 33,
    num_relations: int = 7,
    num_triples: int = 101,
    compact: bool = True,
    random_state: RandomHint = None,
) -> np.ndarray:
    """Generate random triples."""
    random_state = ensure_random_state(random_state)
    rv = np.stack(
        [
            random_state.randint(num_entities, size=(num_triples,)),
            random_state.randint(num_relations, size=(num_triples,)),
            random_state.randint(num_entities, size=(num_triples,)),
        ],
        axis=1,
    )

    if compact:
        new_entity_id = {entity: i for i, entity in enumerate(sorted(get_entities(rv)))}
        new_relation_id = {
            relation: i for i, relation in enumerate(sorted(get_relations(rv)))
        }
        rv = np.asarray(
            [
                [new_entity_id[h], new_relation_id[r], new_entity_id[t]]
                for h, r, t in rv
            ],
            dtype=int,
        )

    return rv


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def generate_triples(
    num_entities: int = 33,
    num_relations: int = 7,
    num_triples: int = 101,
    compact: bool = True,
    random_state: TorchRandomHint = None,
) -> torch.LongTensor:
    """Generate random triples in a torch tensor."""
    random_state = ensure_torch_random_state(random_state)

    rv = torch.stack(
        [
            torch.randint(num_entities, size=(num_triples,), generator=random_state),
            torch.randint(num_relations, size=(num_triples,), generator=random_state),
            torch.randint(num_entities, size=(num_triples,), generator=random_state),
        ],
        dim=1,
    )

    if compact:
        new_entity_id = {entity: i for i, entity in enumerate(sorted(get_entities(rv)))}
        new_relation_id = {
            relation: i for i, relation in enumerate(sorted(get_relations(rv)))
        }
        rv = torch.as_tensor(
            data=[
                [new_entity_id[h], new_relation_id[r], new_entity_id[t]]
                for h, r, t in rv.tolist()
            ],
            dtype=torch.long,
        )

    return rv
# Buggy code
def generate_labeled_triples(
    num_entities: int = 33,
    num_relations: int = 7,
    num_triples: int = 101,
    random_state: RandomHint = None,
) -> np.ndarray:
    """Generate labeled random triples."""
    t = generate_triples(
        num_entities=num_entities,
        num_relations=num_relations,
        num_triples=num_triples,
        compact=False,
        random_state=random_state,
    )
    entity_id_to_label = _make_id_to_labels(num_entities)
    relation_id_to_label = _make_id_to_labels(num_relations)
    return np.asarray(
        [
            (
                entity_id_to_label[h],
                relation_id_to_label[r],
                entity_id_to_label[t],
            )
            for h, r, t in t
        ],
        dtype=str,
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def generate_labeled_triples(
    num_entities: int = 33,
    num_relations: int = 7,
    num_triples: int = 101,
    random_state: TorchRandomHint = None,
) -> np.ndarray:
    """Generate labeled random triples."""
    mapped_triples = generate_triples(
        num_entities=num_entities,
        num_relations=num_relations,
        num_triples=num_triples,
        compact=False,
        random_state=random_state,
    )
    entity_id_to_label = _make_id_to_labels(num_entities)
    relation_id_to_label = _make_id_to_labels(num_relations)
    return np.asarray(
        [
            (
                entity_id_to_label[h],
                relation_id_to_label[r],
                entity_id_to_label[t],
            )
            for h, r, t in mapped_triples
        ],
        dtype=str,
    )
# Buggy code
def generate_triples_factory(
    num_entities: int = 33,
    num_relations: int = 7,
    num_triples: int = 101,
    random_state: RandomHint = None,
    create_inverse_triples: bool = False,
) -> TriplesFactory:
    """Generate a triples factory with random triples."""
    triples = generate_labeled_triples(
        num_entities=num_entities,
        num_relations=num_relations,
        num_triples=num_triples,
        random_state=random_state,
    )
    return TriplesFactory.from_labeled_triples(
        triples=triples,
        create_inverse_triples=create_inverse_triples,
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def generate_triples_factory(
    num_entities: int = 33,
    num_relations: int = 7,
    num_triples: int = 101,
    random_state: TorchRandomHint = None,
    create_inverse_triples: bool = False,
) -> TriplesFactory:
    """Generate a triples factory with random triples."""
    mapped_triples = generate_triples(
        num_entities=num_entities,
        num_relations=num_relations,
        num_triples=num_triples,
        random_state=random_state,
    )
    return TriplesFactory(
        entity_to_id=_make_label_to_ids(num_entities),
        relation_to_id=_make_label_to_ids(num_relations),
        mapped_triples=mapped_triples,
        create_inverse_triples=create_inverse_triples,
    )
# Buggy code
def apply(self, triples_factory: TriplesFactory) -> TriplesFactory:
    """Make a new triples factory containing neither duplicate nor inverse relationships."""
    return triples_factory.new_without_relations(self.relations_to_delete)


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def apply(self, triples_factory: TriplesFactory) -> TriplesFactory:
    """Make a new triples factory containing neither duplicate nor inverse relationships."""
    return triples_factory.new_with_restriction(
        relations=self.relations_to_delete, invert_relation_selection=True
    )
# Buggy code
def reindex(*triples_factories: TriplesFactory) -> List[TriplesFactory]:
    """Reindex a set of triples factories."""
    triples = np.concatenate(
        [triples_factory.triples for triples_factory in triples_factories],
        axis=0,
    )
    entity_to_id = create_entity_mapping(triples)
    relation_to_id = create_relation_mapping(set(triples[:, 1]))

    return [
        TriplesFactory.from_labeled_triples(
            triples=triples_factory.triples,
            entity_to_id=entity_to_id,
            relation_to_id=relation_to_id,
            # FIXME doesn't carry flag of create_inverse_triples through
        )
        for triples_factory in triples_factories
    ]


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def reindex(*triples_factories: TriplesFactory) -> List[TriplesFactory]:
    """Reindex a set of triples factories."""
    # get entities and relations occurring in triples
    all_triples = torch.cat(
        [factory.mapped_triples for factory in triples_factories], dim=0
    )

    # generate ID translation and new label to Id mappings
    one_factory = triples_factories[0]
    (entity_to_id, entity_id_translation), (relation_to_id, relation_id_translation) = [
        _generate_compact_vectorized_lookup(
            ids=all_triples[:, cols],
            label_to_id=label_to_id,
        )
        for cols, label_to_id in (
            ([0, 2], one_factory.entity_to_id),
            (1, one_factory.relation_to_id),
        )
    ]

    return [
        TriplesFactory(
            entity_to_id=entity_to_id,
            relation_to_id=relation_to_id,
            mapped_triples=_translate_triples(
                triples=factory.mapped_triples,
                entity_translation=entity_id_translation,
                relation_translation=relation_id_translation,
            ),
            create_inverse_triples=factory.create_inverse_triples,
        )
        for factory in triples_factories
    ]
# Buggy code
def _main():
    """Test unleaking FB15K.

    Run with ``python -m pykeen.triples.leakage``.
    """
    from pykeen.datasets import get_dataset

    logging.basicConfig(format="pykeen: %(message)s", level=logging.INFO)

    print("Summary FB15K")
    fb15k = get_dataset(dataset="fb15k")
    summarize(fb15k.training, fb15k.testing, fb15k.validation)

    print("\nSummary FB15K (cleaned)")
    n = 401  # magic 401 from the paper
    train, test, validate = unleak(fb15k.training, fb15k.testing, fb15k.validation, n=n)
    summarize(train, test, validate)

    print("\nSummary FB15K-237")
    fb15k237 = get_dataset(dataset="fb15k237")
    summarize(fb15k237.training, fb15k237.testing, fb15k237.validation)


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def _main():
    """Test unleaking FB15K.

    Run with ``python -m pykeen.triples.leakage``.
    """
    from pykeen.datasets import get_dataset

    logging.basicConfig(format="pykeen: %(message)s", level=logging.INFO)

    fb15k = get_dataset(dataset="fb15k")
    fb15k.summarize()

    n = 401  # magic 401 from the paper
    train, test, validate = unleak(fb15k.training, fb15k.testing, fb15k.validation, n=n)
    print()
    EagerDataset(train, test, validate).summarize(title="FB15k (cleaned)")

    fb15k237 = get_dataset(dataset="fb15k237")
    print("\nSummary FB15K-237")
    fb15k237.summarize()
# Buggy code
def num_relations(self) -> int:  # noqa: D401
    """The number of unique relations."""
    return len(self.relation_to_id)


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def num_relations(self) -> int:  # noqa: D401
    """The number of unique relations."""
    if self.create_inverse_triples:
        return 2 * self.real_num_relations
    return self.real_num_relations
# Buggy code
def triples(self) -> np.ndarray:  # noqa: D401
    """The labeled triples."""
    # TODO: Deprecation warning. Will be replaced by re-constructing them from ID-based + mapping soon.
    return self._triples


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def triples(self) -> np.ndarray:  # noqa: D401
    """The labeled triples, a 3-column matrix where each row are the head label, relation label, then tail label."""
    logger.warning(
        "Reconstructing all label-based triples. This is expensive and rarely needed."
    )
    return self.label_triples(self.mapped_triples)
# Buggy code
def get_inverse_relation_id(self, relation: str) -> int:
    """Get the inverse relation identifier for the given relation."""
    if not self.create_inverse_triples:
        raise ValueError("Can not get inverse triple, they have not been created.")
    inverse_relation = self.relation_to_inverse[relation]
    return self.relation_to_id[inverse_relation]


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def get_inverse_relation_id(self, relation: Union[str, int]) -> int:
    """Get the inverse relation identifier for the given relation."""
    if not self.create_inverse_triples:
        raise ValueError("Can not get inverse triple, they have not been created.")
    relation = next(iter(self.relations_to_ids(relations=[relation])))
    return self._get_inverse_relation_id(relation)
# Buggy code
def create_slcwa_instances(self) -> Instances:
    """Create sLCWA instances for this factory's triples."""
    return SLCWAInstances(mapped_triples=self.mapped_triples)


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def create_slcwa_instances(self) -> Instances:
    """Create sLCWA instances for this factory's triples."""
    return SLCWAInstances(
        mapped_triples=self._add_inverse_triples_if_necessary(
            mapped_triples=self.mapped_triples
        )
    )
# Buggy code
def create_lcwa_instances(self, use_tqdm: Optional[bool] = None) -> Instances:
    """Create LCWA instances for this factory's triples."""
    return LCWAInstances.from_triples(
        mapped_triples=self.mapped_triples, num_entities=self.num_entities
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def create_lcwa_instances(self, use_tqdm: Optional[bool] = None) -> Instances:
    """Create LCWA instances for this factory's triples."""
    return LCWAInstances.from_triples(
        mapped_triples=self._add_inverse_triples_if_necessary(
            mapped_triples=self.mapped_triples
        ),
        num_entities=self.num_entities,
    )
# Buggy code
def get_most_frequent_relations(self, n: Union[int, float]) -> Set[str]:
    """Get the n most frequent relations.

    :param n: Either the (integer) number of top relations to keep or the (float) percentage of top relationships
     to keep
    """
    logger.info(f"applying cutoff of {n} to {self}")
    if isinstance(n, float):
        assert 0 < n < 1
        n = int(self.num_relations * n)
    elif not isinstance(n, int):
        raise TypeError("n must be either an integer or a float")

    counter = Counter(self.triples[:, 1])
    return {relation for relation, _ in counter.most_common(n)}


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 49, in <module>
main()
File "/Users/cthoyt/dev/pykeen/scratch/tst.py", line 36, in main
testing.new_with_restriction(relations=evaluation_relation_whitelist)
File "/Users/cthoyt/dev/pykeen/src/pykeen/triples/triples_factory.py", line 641, in new_with_restriction
relations = list(relations) + list(map(self.relation_to_inverse.__getitem__, relations))
KeyError: 'accusation_inverse'

# Fixed code
def get_most_frequent_relations(self, n: Union[int, float]) -> Set[int]:
    """Get the IDs of the n most frequent relations.

    :param n: Either the (integer) number of top relations to keep or the (float) percentage of top relationships
     to keep
    """
    logger.info(f"applying cutoff of {n} to {self}")
    if isinstance(n, float):
        assert 0 < n < 1
        n = int(self.num_relations * n)
    elif not isinstance(n, int):
        raise TypeError("n must be either an integer or a float")

    uniq, counts = self.mapped_triples[:, 1].unique(return_counts=True)
    top_counts, top_ids = counts.topk(k=n, largest=True)
    return set(uniq[top_ids].tolist())