gurudesh/pytracebugs huggingface dataset:
# Buggy code
def afterExecSheet(cmdlog, sheet, escaped, err):
    cmdlog.afterExecSheet.__wrapped__(cmdlog, sheet, escaped, err)
    if (
        vd.macroMode
        and (vd.activeCommand is not None)
        and (vd.activeCommand is not UNLOADED)
    ):
        cmd = copy(vd.activeCommand)
        cmd.row = cmd.col = cmd.sheet = ""
        vd.macroMode.addRow(cmd)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/visidata/basesheet.py", line 136, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "macro-record", line 1, in <module>
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 52, in startMacro
vd.cmdlog.saveMacro(vd.macroMode.rows, ks)
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 37, in saveMacro
append_tsv_row(vd.macrosheet, (ks, macropath))
File "/usr/lib/python3.9/site-packages/visidata/loaders/tsv.py", line 81, in append_tsv_row
if not vs.source.exists():
AttributeError: 'NoneType' object has no attribute 'exists'

# Fixed code
def afterExecSheet(cmdlog, sheet, escaped, err):
    if (
        vd.macroMode
        and (vd.activeCommand is not None)
        and (vd.activeCommand is not UNLOADED)
    ):
        cmd = copy(vd.activeCommand)
        cmd.row = cmd.col = cmd.sheet = ""
        vd.macroMode.addRow(cmd)

    # the following needs to happen at the end, bc
    # once cmdlog.afterExecSheet.__wrapped__ runs, vd.activeCommand resets to None
    cmdlog.afterExecSheet.__wrapped__(cmdlog, sheet, escaped, err)
# Buggy code
def iterload(self):
    import openpyxl

    self.workbook = openpyxl.load_workbook(
        str(self.source), data_only=True, read_only=True
    )
    for sheetname in self.workbook.sheetnames:
        vs = XlsxSheet(self.name, sheetname, source=self.workbook[sheetname])
        vs.reload()
        yield vs


# Traceback (AttributeError)
opening _20112020100242.xlsx as xlsx
Traceback (most recent call last):
File "/home/aborruso/.local/bin/vd", line 6, in <module>
visidata.main.vd_cli()
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/main.py", line 298, in vd_cli
rc = main_vd()
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/main.py", line 228, in main_vd
vd.push(sources[0])
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/sheets.py", line 982, in push
vs.ensureLoaded()
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/basesheet.py", line 189, in ensureLoaded
return self.reload()   # likely launches new thread
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/vdobj.py", line 20, in _execAsync
return visidata.vd.execAsync(func, *args, **kwargs)
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/main.py", line 198, in <lambda>
vd.execAsync = lambda func, *args, **kwargs: func(*args, **kwargs) # disable async
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/sheets.py", line 269, in reload
for r in self.iterload():
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/loaders/xlsx.py", line 26, in iterload
vs.reload()
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/vdobj.py", line 20, in _execAsync
return visidata.vd.execAsync(func, *args, **kwargs)
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/main.py", line 198, in <lambda>
vd.execAsync = lambda func, *args, **kwargs: func(*args, **kwargs) # disable async
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/sheets.py", line 884, in reload
self.setCols(list(self.optlines(itsource, 'header')))
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/sheets.py", line 870, in optlines
yield next(it)
File "/home/aborruso/.local/lib/python3.8/site-packages/visidata/loaders/xlsx.py", line 33, in iterload
for row in Progress(worksheet.iter_rows(), total=worksheet.max_row or 0):
AttributeError: 'Chartsheet' object has no attribute 'iter_rows'

# Fixed code
def iterload(self):
    import openpyxl

    self.workbook = openpyxl.load_workbook(
        str(self.source), data_only=True, read_only=True
    )
    for sheetname in self.workbook.sheetnames:
        src = self.workbook[sheetname]
        vs = XlsxSheet(self.name, sheetname, source=src)
        if isinstance(src, openpyxl.Workbook):
            vs.reload()
        yield vs
# Buggy code
def __new__(cls, v):
    if isinstance(v, (vlen, int, float)):
        return super(vlen, cls).__new__(cls, v)
    else:
        return super(vlen, cls).__new__(cls, len(v))


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/visidata/threads.py", line 207, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/visidata/pivot.py", line 203, in groupRows
numericGroupRows = {formatRange(numericCols[0], numRange): PivotGroupRow(discreteKeys, numRange, [], {}) for numRange in numericBins}
File "/usr/lib/python3.8/site-packages/visidata/pivot.py", line 203, in <dictcomp>
numericGroupRows = {formatRange(numericCols[0], numRange): PivotGroupRow(discreteKeys, numRange, [], {}) for numRange in numericBins}
File "/usr/lib/python3.8/site-packages/visidata/pivot.py", line 25, in formatRange
nankey = makeErrorKey(col)
File "/usr/lib/python3.8/site-packages/visidata/pivot.py", line 21, in makeErrorKey
return col.type()
TypeError: __new__() missing 1 required positional argument: 'v'

# Fixed code
def __new__(cls, v=0):
    if isinstance(v, (vlen, int, float)):
        return super(vlen, cls).__new__(cls, v)
    else:
        return super(vlen, cls).__new__(cls, len(v))
# Buggy code
def setCols(self, headerrows):
    self.columns = []
    for i, colnamelines in enumerate(itertools.zip_longest(*headerrows, fillvalue="")):
        self.addColumn(ColumnItem("".join(colnamelines), i))

    self._rowtype = namedlist("tsvobj", [(c.name or "_") for c in self.columns])


# Traceback (TypeError)
Traceback (most recent call last):
File "[...]/visidata/threads.py", line 207, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "[...]/visidata/sheets.py", line 878, in reload
self.setCols(list(self.optlines(itsource, 'header')))
File "[...]/visidata/sheets.py", line 845, in setCols
self.addColumn(ColumnItem(''.join(colnamelines), i))
TypeError: sequence item 0: expected str instance, NoneType found

# Fixed code
def setCols(self, headerrows):
    self.columns = []
    for i, colnamelines in enumerate(itertools.zip_longest(*headerrows, fillvalue="")):
        colnamelines = ["" if c is None else c for c in colnamelines]
        self.addColumn(ColumnItem("".join(colnamelines), i))

    self._rowtype = namedlist("tsvobj", [(c.name or "_") for c in self.columns])
# Buggy code
def add_y_axis_label(self, frac):
    amt = self.visibleBox.ymin + frac * self.visibleBox.h
    srccol = self.ycols[0]
    txt = srccol.format(srccol.type(amt))

    # plot y-axis labels on the far left of the canvas, but within the plotview height-wise
    attr = colors.color_graph_axis
    self.plotlabel(
        0, self.plotviewBox.ymin + (1.0 - frac) * self.plotviewBox.h, txt, attr
    )


# Traceback (NameError)
Traceback (most recent call last):
File "/Users/Documents/pyv/py3/lib/python3.7/site-packages/visidata/basesheet.py", line 127, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "release-mouse", line 1, in <module>
import math
NameError: name 'mouseX' is not defined

# Fixed code
def add_y_axis_label(self, frac):
    txt = self.formatY(self.visibleBox.ymin + frac * self.visibleBox.h)

    # plot y-axis labels on the far left of the canvas, but within the plotview height-wise
    attr = colors.color_graph_axis
    self.plotlabel(
        0, self.plotviewBox.ymin + (1.0 - frac) * self.plotviewBox.h, txt, attr
    )
# Buggy code
def add_x_axis_label(self, frac):
    amt = self.visibleBox.xmin + frac * self.visibleBox.w
    txt = ",".join(
        xcol.format(xcol.type(amt)) for xcol in self.xcols if isNumeric(xcol)
    )

    # plot x-axis labels below the plotviewBox.ymax, but within the plotview width-wise
    attr = colors.color_graph_axis
    xmin = self.plotviewBox.xmin + frac * self.plotviewBox.w
    if frac == 1.0:
        # shift rightmost label to be readable
        xmin -= max(len(txt) * 2 - self.rightMarginPixels + 1, 0)

    self.plotlabel(xmin, self.plotviewBox.ymax + 4, txt, attr)


# Traceback (NameError)
Traceback (most recent call last):
File "/Users/Documents/pyv/py3/lib/python3.7/site-packages/visidata/basesheet.py", line 127, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "release-mouse", line 1, in <module>
import math
NameError: name 'mouseX' is not defined

# Fixed code
def add_x_axis_label(self, frac):
    txt = self.formatX(self.visibleBox.xmin + frac * self.visibleBox.w)

    # plot x-axis labels below the plotviewBox.ymax, but within the plotview width-wise
    attr = colors.color_graph_axis
    xmin = self.plotviewBox.xmin + frac * self.plotviewBox.w
    if frac == 1.0:
        # shift rightmost label to be readable
        xmin -= max(len(txt) * 2 - self.rightMarginPixels + 1, 0)

    self.plotlabel(xmin, self.plotviewBox.ymax + 4, txt, attr)
# Buggy code
def set_y(sheet, s):
    ymin, ymax = map(float, map(sheet.ycols[0].type, s.split()))
    sheet.zoomTo(BoundingBox(sheet.visibleBox.xmin, ymin, sheet.visibleBox.xmax, ymax))
    sheet.refresh()


# Traceback (NameError)
Traceback (most recent call last):
File "/Users/Documents/pyv/py3/lib/python3.7/site-packages/visidata/basesheet.py", line 127, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "release-mouse", line 1, in <module>
import math
NameError: name 'mouseX' is not defined

# Fixed code
def set_y(sheet, s):
    ymin, ymax = map(float, map(sheet.parseY, s.split()))
    sheet.zoomTo(BoundingBox(sheet.visibleBox.xmin, ymin, sheet.visibleBox.xmax, ymax))
    sheet.refresh()
# Buggy code
def set_x(sheet, s):
    xmin, xmax = map(float, map(sheet.xcols[0].type, s.split()))
    sheet.zoomTo(BoundingBox(xmin, sheet.visibleBox.ymin, xmax, sheet.visibleBox.ymax))
    sheet.refresh()


# Traceback (NameError)
Traceback (most recent call last):
File "/Users/Documents/pyv/py3/lib/python3.7/site-packages/visidata/basesheet.py", line 127, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "release-mouse", line 1, in <module>
import math
NameError: name 'mouseX' is not defined

# Fixed code
def set_x(sheet, s):
    xmin, xmax = map(float, map(sheet.parseX, s.split()))
    sheet.zoomTo(BoundingBox(xmin, sheet.visibleBox.ymin, xmax, sheet.visibleBox.ymax))
    sheet.refresh()
# Buggy code
def reload(self):
    # key rows become column names
    col = Column(
        "_".join(c.name for c in self.source.keyCols),
        getter=lambda c, origcol: origcol.name,
    )
    # associate column with sheet
    col.recalc(self)
    self.columns = [col]
    self.setKeys(self.columns)

    # rows become columns
    for row in Progress(self.source.rows, "transposing"):
        self.addColumn(
            Column(
                "_".join(self.source.rowkey(row)),
                getter=lambda c, origcol, row=row: origcol.getValue(row),
            )
        )

    # columns become rows
    self.rows = list(self.source.nonKeyVisibleCols)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/env/lib/python3.8/site-packages/visidata/threads.py", line 207, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "/usr/env/lib/python3.8/site-packages/visidata/transpose.py", line 18, in reload
self.addColumn(Column('_'.join(self.source.rowkey(row)),
TypeError: sequence item 0: expected str instance, int found

# Fixed code
def reload(self):
    # key rows become column names
    col = Column(
        "_".join(c.name for c in self.source.keyCols),
        getter=lambda c, origcol: origcol.name,
    )
    # associate column with sheet
    col.recalc(self)
    self.columns = [col]
    self.setKeys(self.columns)

    # rows become columns
    for row in Progress(self.source.rows, "transposing"):
        self.addColumn(
            Column(
                "_".join(map(str, self.source.rowkey(row))),
                getter=lambda c, origcol, row=row: origcol.getValue(row),
            )
        )

    # columns become rows
    self.rows = list(self.source.nonKeyVisibleCols)
# Buggy code
def parseArgs(vd, parser: argparse.ArgumentParser):
    addOptions(parser)
    args, remaining = parser.parse_known_args()

    # add visidata_dir to path before loading config file (can only be set from cli)
    sys.path.append(str(visidata.Path(args.visidata_dir or options.visidata_dir)))

    # import plugins from .visidata/plugins before .visidatarc, so plugin options can be overridden
    for modname in args.imports.split():
        addGlobals(importlib.import_module(modname).__dict__)

    # user customisations in config file in standard location
    loadConfigFile(visidata.Path(args.config or options.config), getGlobals())

    # add plugin options and reparse
    addOptions(parser)
    args, remaining = parser.parse_known_args()

    # apply command-line overrides after .visidatarc
    for optname, optval in vars(args).items():
        if optval is not None and optname not in [
            "inputs",
            "play",
            "batch",
            "output",
            "diff",
        ]:
            options[optname] = optval

    return args


# Traceback (ModuleNotFoundError)
Traceback (most recent call last):
File "/usr/bin/vd", line 6, in <module>
visidata.main.vd_cli()
File "/usr/lib/python3.8/site-packages/visidata/main.py", line 220, in vd_cli
rc = main_vd()
File "/usr/lib/python3.8/site-packages/visidata/main.py", line 75, in main_vd
args = vd.parseArgs(parser)
File "/usr/lib/python3.8/site-packages/visidata/settings.py", line 312, in parseArgs
addGlobals(importlib.import_module(modname).__dict__)
File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'plugins'

# Fixed code
def parseArgs(vd, parser: argparse.ArgumentParser):
    addOptions(parser)
    args, remaining = parser.parse_known_args()

    # add visidata_dir to path before loading config file (can only be set from cli)
    sys.path.append(str(visidata.Path(args.visidata_dir or options.visidata_dir)))

    # import plugins from .visidata/plugins before .visidatarc, so plugin options can be overridden
    for modname in args.imports.split():
        try:
            addGlobals(importlib.import_module(modname).__dict__)
        except ModuleNotFoundError:
            continue

    # user customisations in config file in standard location
    loadConfigFile(visidata.Path(args.config or options.config), getGlobals())

    # add plugin options and reparse
    addOptions(parser)
    args, remaining = parser.parse_known_args()

    # apply command-line overrides after .visidatarc
    for optname, optval in vars(args).items():
        if optval is not None and optname not in [
            "inputs",
            "play",
            "batch",
            "output",
            "diff",
        ]:
            options[optname] = optval

    return args
# Buggy code
def numericFormatter(fmtstr, typedval):
    fmtstr = fmtstr or options["disp_" + type(typedval).__name__ + "_fmt"]
    if fmtstr:
        if fmtstr[0] == "%":
            return locale.format_string(fmtstr, typedval, grouping=True)
        else:
            return fmtstr.format(typedval)
    return str(typedval)


# Traceback (visidata.errors.ExpectedException)
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/visidata/column.py", line 247, in getCell
dw.display = self.format(typedval) or ''
File "/usr/lib/python3.8/site-packages/visidata/column.py", line 140, in format
return getType(self.type).formatter(self.fmtstr, typedval)
File "/usr/lib/python3.8/site-packages/visidata/_types.py", line 40, in numericFormatter
fmtstr = fmtstr or options['disp_'+type(typedval).__name__+'_fmt']
File "/usr/lib/python3.8/site-packages/visidata/settings.py", line 199, in __getitem__
vd.error('no option "%s"' % k)
File "/usr/lib/python3.8/site-packages/visidata/statusbar.py", line 55, in error
raise ExpectedException(args[0] if args else '')
visidata.errors.ExpectedException: no option "disp_bool_fmt"

# Fixed code
def numericFormatter(fmtstr, typedval):
    try:
        fmtstr = fmtstr or options["disp_" + type(typedval).__name__ + "_fmt"]
        if fmtstr[0] == "%":
            return locale.format_string(fmtstr, typedval, grouping=True)
        else:
            return fmtstr.format(typedval)
    except ValueError:
        return str(typedval)
# Buggy code
def reload(self):
    # key rows become column names
    self.columns = [
        Column(
            "_".join(c.name for c in self.source.keyCols),
            getter=lambda c, origcol: origcol.name,
        )
    ]
    self.setKeys(self.columns)

    # rows become columns
    for row in Progress(self.source.rows, "transposing"):
        self.addColumn(
            Column(
                "_".join(self.source.rowkey(row)),
                getter=lambda c, origcol, row=row: origcol.getValue(row),
            )
        )

    # columns become rows
    self.rows = list(self.source.nonKeyVisibleCols)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/visidata/basesheet.py", line 127, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "pyobj-cell", line 1, in <module>
import math
File "/usr/lib/python3.8/site-packages/visidata/basesheet.py", line 30, in __getitem__
return getattr(obj, k)
File "/usr/lib/python3.8/site-packages/visidata/sheets.py", line 419, in cursorValue
return self.cursorCol.getValue(self.cursorRow)
File "/usr/lib/python3.8/site-packages/visidata/column.py", line 182, in getValue
if self.sheet.defer:
AttributeError: 'NoneType' object has no attribute 'defer'

# Fixed code
def reload(self):
    # key rows become column names
    col = Column(
        "_".join(c.name for c in self.source.keyCols),
        getter=lambda c, origcol: origcol.name,
    )
    # associate column with sheet
    col.recalc(self)
    self.columns = [col]
    self.setKeys(self.columns)

    # rows become columns
    for row in Progress(self.source.rows, "transposing"):
        self.addColumn(
            Column(
                "_".join(self.source.rowkey(row)),
                getter=lambda c, origcol, row=row: origcol.getValue(row),
            )
        )

    # columns become rows
    self.rows = list(self.source.nonKeyVisibleCols)
# Buggy code
def openRow(self, row):
    k = self.rowkey(row) or [self.cursorRowIndex]
    name = f"{self.name}[{self.keystr(row)}]"
    return vd.load_pyobj(tuple(c.getTypedValue(row) for c in self.visibleCols))


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/visidata/basesheet.py", line 126, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "dive-row", line 1, in <module>
import math
File "/usr/lib/visidata/sheets.py", line 241, in openRow
return vd.load_pyobj(tuple(c.getTypedValue(row) for c in self.visibleCols)) TypeError: load_pyobj() missing 1 required positional argument: 'obj"

# Fixed code
def openRow(self, row):
    k = self.rowkey(row) or [self.cursorRowIndex]
    name = f"{self.name}[{self.keystr(row)}]"
    return vd.load_pyobj(name, tuple(c.getTypedValue(row) for c in self.visibleCols))
# Buggy code
def openRow(self, row):
    return load_pyobj("%s[%s]" % (name, rowIndex), row)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/visidata/basesheet.py", line 126, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "dive-row", line 1, in <module>
import math
File "/usr/lib/visidata/sheets.py", line 241, in openRow
return vd.load_pyobj(tuple(c.getTypedValue(row) for c in self.visibleCols)) TypeError: load_pyobj() missing 1 required positional argument: 'obj"

# Fixed code
def openRow(self, row):
    return load_pyobj("%s[%s]" % (self.name, self.keystr(row)), row)
# Buggy code
def openRow(self, row):
    k = self.rowkey(row) or [self.cursorRowIndex]
    name = f"{self.name}[{self.keystr(row)}]"
    return vd.load_pyobj(name, tuple(c.getTypedValue(row) for c in self.visibleCols))


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/visidata/basesheet.py", line 126, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "dive-row", line 1, in <module>
import math
File "/usr/lib/visidata/sheets.py", line 241, in openRow
return vd.load_pyobj(tuple(c.getTypedValue(row) for c in self.visibleCols)) TypeError: load_pyobj() missing 1 required positional argument: 'obj"

# Fixed code
def openRow(self, row):
    k = self.rowkey(row) or [self.cursorRowIndex]
    name = f"{self.name}[{k}]"
    return vd.load_pyobj(name, tuple(c.getTypedValue(row) for c in self.visibleCols))
# Buggy code
def openCell(self, col, row):
    k = self.keystr(row) or [str(self.cursorRowIndex)]
    name = f"{self.name}.{col.name}[{self.keystr(row)}]"
    return vd.load_pyobj(name, col.getTypedValue(row))


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/visidata/basesheet.py", line 126, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "dive-row", line 1, in <module>
import math
File "/usr/lib/visidata/sheets.py", line 241, in openRow
return vd.load_pyobj(tuple(c.getTypedValue(row) for c in self.visibleCols)) TypeError: load_pyobj() missing 1 required positional argument: 'obj"

# Fixed code
def openCell(self, col, row):
    k = self.keystr(row) or [str(self.cursorRowIndex)]
    name = f"{self.name}.{col.name}[{k}]"
    return vd.load_pyobj(name, col.getTypedValue(row))
# Buggy code
def save_html(vd, p, *vsheets):
    "Save vsheets as HTML tables in a single file"

    with open(p, "w", encoding="ascii", errors="xmlcharrefreplace") as fp:
        for sheet in vsheets:
            fp.write(
                '<h2 class="sheetname">%s</h2>\n'.format(
                    sheetname=html.escape(sheet.name)
                )
            )

            fp.write(
                '<table id="{sheetname}">\n'.format(sheetname=html.escape(sheet.name))
            )

            # headers
            fp.write("<tr>")
            for col in sheet.visibleCols:
                contents = html.escape(col.name)
                fp.write("<th>{colname}</th>".format(colname=contents))
            fp.write("</tr>\n")

            # rows
            with Progress(gerund="saving"):
                for typedvals in sheet.iterdispvals(format=False):
                    fp.write("<tr>")
                    for col, val in typedvals.items():
                        fp.write("<td>")
                        fp.write(html.escape(val))
                        fp.write("</td>")
                    fp.write("</tr>\n")

            fp.write("</table>")
            vd.status("%s save finished" % p)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Documents/pyv/py3/lib/python3.7/site-packages/visidata/threads.py", line 201, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "/Documents/pyv/py3/lib/python3.7/site-packages/visidata/loaders/html.py", line 124, in save_html
fp.write(html.escape(val))
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/html/__init__.py", line 19, in escape
s = s.replace("&amp;", "&amp;amp;") # Must be done first!
AttributeError: 'vlen' object has no attribute 'replace'

# Fixed code
def save_html(vd, p, *vsheets):
    "Save vsheets as HTML tables in a single file"

    with open(p, "w", encoding="ascii", errors="xmlcharrefreplace") as fp:
        for sheet in vsheets:
            fp.write(
                '<h2 class="sheetname">%s</h2>\n'.format(
                    sheetname=html.escape(sheet.name)
                )
            )

            fp.write(
                '<table id="{sheetname}">\n'.format(sheetname=html.escape(sheet.name))
            )

            # headers
            fp.write("<tr>")
            for col in sheet.visibleCols:
                contents = html.escape(col.name)
                fp.write("<th>{colname}</th>".format(colname=contents))
            fp.write("</tr>\n")

            # rows
            with Progress(gerund="saving"):
                for typedvals in sheet.iterdispvals(format=False):
                    fp.write("<tr>")
                    for col, val in typedvals.items():
                        fp.write("<td>")
                        fp.write(html.escape(str(val)))
                        fp.write("</td>")
                    fp.write("</tr>\n")

            fp.write("</table>")
            vd.status("%s save finished" % p)
# Buggy code
def __getattr__(self, k):
    if hasattr(self.__dict__, k):
        r = getattr(self.__dict__, k)
    else:
        r = getattr(self._path, k)
    if isinstance(r, pathlib.Path):
        return Path(r)
    return r


# Traceback (RecursionError)
Traceback (most recent call last):
File "/path/vd_plugins/radare2/r2/lib/python3.7/site-packages/visidata-2._4dev-py3.7.egg/visidata/threads.py", line 201, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "/path/vd_plugins/radare2/r2/lib/python3.7/site-packages/visidata-2._4dev-py3.7.egg/visidata/threads.py", line 80, in _async_deepcopy
newlist.append(deepcopy(r))
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/copy.py", line 180, in deepcopy
y = _reconstruct(x, memo, *rv)
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/copy.py", line 281, in _reconstruct
if hasattr(y, '__setstate__'):
File "/path/vd_plugins/radare2/r2/lib/python3.7/site-packages/visidata-2._4dev-py3.7.egg/visidata/path.py", line 77, in __getattr__
r = getattr(self._path, k)
File "/path/vd_plugins/radare2/r2/lib/python3.7/site-packages/visidata-2._4dev-py3.7.egg/visidata/path.py", line 77, in __getattr__
r = getattr(self._path, k)
File "/path/vd_plugins/radare2/r2/lib/python3.7/site-packages/visidata-2._4dev-py3.7.egg/visidata/path.py", line 77, in __getattr__
r = getattr(self._path, k)
[Previous line repeated 492 more times]
RecursionError: maximum recursion depth exceeded

# Fixed code
def __getattr__(self, k):
    if hasattr(self.__dict__, k):
        r = getattr(self.__dict__, k)
    else:
        if self.__dict__.get("_path", None) is not None:
            r = getattr(self._path, k)
        else:
            raise AttributeError(k)
    if isinstance(r, pathlib.Path):
        return Path(r)
    return r
# Buggy code
def open_fixed(p):
    return FixedWidthColumnsSheet(p.name, source=p)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3/site-packages/visidata/threads.py", line 202, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "/usr/lib/python3/site-packages/visidata/sheets.py", line 828, in reload
list(self.optlines(itsource, 'skip'))
File "/usr/lib/python3/site-packages/visidata/sheets.py", line 817, in optlines
yield next(it)
File "/usr/lib/python3/site-packages/visidata/loaders/fixed_width.py", line 67, in iterload
self.setColNames(self.headerlines)
AttributeError: 'FixedWidthColumnsSheet' object has no attribute 'headerlines'

# Fixed code
def open_fixed(p):
    return FixedWidthColumnsSheet(p.name, source=p, headerlines=[])
# Buggy code
def bindkey(cls, keystrokes, longname):
    oldlongname = bindkeys._get(keystrokes, cls)
    if oldlongname:
        vd.warning("%s was already bound to %s" % (keystrokes, oldlongname))
    bindkeys.set(keystrokes, longname, cls)


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/sfranky/.local/lib/python3.7/site-packages/visidata/settings.py", line 257, in loadConfigFile
exec(code, _globals or globals())
File "/home/sfranky/.visidatarc", line 19, in <module>
bindkey('0', 'go-leftmost')
TypeError: 'classmethod' object is not callable

# Fixed code
def bindkey(keystrokes, longname):
    bindkeys.setdefault(keystrokes, longname)
# Buggy code
def unbindkey(cls, keystrokes):
    bindkeys.unset(keystrokes, cls)


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/sfranky/.local/lib/python3.7/site-packages/visidata/settings.py", line 257, in loadConfigFile
exec(code, _globals or globals())
File "/home/sfranky/.visidatarc", line 19, in <module>
bindkey('0', 'go-leftmost')
TypeError: 'classmethod' object is not callable

# Fixed code
def unbindkey(keystrokes):
    bindkeys.unset(keystrokes)
# Buggy code
def reload(self):
    from pkg_resources import resource_filename

    cmdlist = TsvSheet(
        "cmdlist", source=Path(resource_filename(__name__, "commands.tsv"))
    )
    cmdlist.reload_sync()

    self.rows = []
    for (k, o), v in commands.iter(self.source):
        self.addRow(v)
        v.sheet = o

    self.cmddict = {}
    for cmdrow in cmdlist.rows:
        self.cmddict[(cmdrow.sheet, cmdrow.longname)] = cmdrow

    self.revbinds = {}  # [longname] -> keystrokes
    for (keystrokes, _), longname in bindkeys.iter(self.source):
        if keystrokes not in self.revbinds:
            self.revbinds[longname] = keystrokes


# Traceback (KeyError)
==> cell_err.txt <==
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/visidata/wrappers.py", line 95, in wrapply
return func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/visidata/column.py", line 168, in getValue
return self.calcValue(row)
File "/usr/lib/python3.6/site-packages/visidata/column.py", line 136, in calcValue
return (self.getter)(self, row)
File "/usr/lib/python3.6/site-packages/visidata/metasheets.py", line 83, in <lambda>
Column('description', getter=lambda col,row: col.sheet.cmddict[(row.sheet, row.longname)].helpstr),
KeyError: ('Sheet', 'show-cursor')

==> last_err.txt <==
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/visidata/utils.py", line 76, in __getattr__
return self[self._fields.index(k)]
ValueError: 'sheet' is not in list

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/visidata/threads.py", line 191, in _toplevelTryFunc
t.status = func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/visidata/metasheets.py", line 101, in reload
self.cmddict[(cmdrow.sheet, cmdrow.longname)] = cmdrow
File "/usr/lib/python3.6/site-packages/visidata/utils.py", line 78, in __getattr__
raise AttributeError
AttributeError

# Fixed code
def reload(self):
    from pkg_resources import resource_filename

    cmdlist = TsvSheet(
        "cmdlist", source=Path(resource_filename(__name__, "commands.tsv"))
    )
    options.set("delimiter", vd_system_sep, cmdlist)
    cmdlist.reload_sync()

    self.rows = []
    for (k, o), v in commands.iter(self.source):
        self.addRow(v)
        v.sheet = o

    self.cmddict = {}
    for cmdrow in cmdlist.rows:
        self.cmddict[(cmdrow.sheet, cmdrow.longname)] = cmdrow

    self.revbinds = {}  # [longname] -> keystrokes
    for (keystrokes, _), longname in bindkeys.iter(self.source):
        if keystrokes not in self.revbinds:
            self.revbinds[longname] = keystrokes
# Buggy code
def execute(self, conn, sql, where={}, parms=None):
    parms = parms or []
    if where:
        sql += " WHERE %s" % " AND ".join("%s=?" % k for k in where)
    status(sql)
    parms += list(where.values())
    return conn.execute(sql, parms)


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def execute(self, conn, sql, where={}, parms=None):
    parms = parms or []
    if where:
        sql += " WHERE %s" % " AND ".join('"%s"=?' % k for k in where)
    status(sql)
    parms += list(where.values())
    return conn.execute(sql, parms)
# Buggy code
def reload_sync(self, _conn=None):
    self.reset()
    with _conn or self.conn() as conn:
        tblname = self.tableName
        self.columns = self.getColumns(tblname, conn)
        self.recalc()
        r = self.execute(conn, "SELECT COUNT(*) FROM %s" % tblname).fetchall()
        rowcount = r[0][0]
        self.rows = []
        for row in Progress(
            self.execute(conn, "SELECT * FROM %s" % tblname), total=rowcount - 1
        ):
            self.addRow(row)


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def reload_sync(self, _conn=None):
    self.reset()
    with _conn or self.conn() as conn:
        tblname = self.tableName
        self.columns = self.getColumns(tblname, conn)
        self.recalc()
        r = self.execute(conn, 'SELECT COUNT(*) FROM "%s"' % tblname).fetchall()
        rowcount = r[0][0]
        self.rows = []
        for row in Progress(
            self.execute(conn, 'SELECT * FROM "%s"' % tblname), total=rowcount - 1
        ):
            self.addRow(row)
# Buggy code
def getColumns(self, tableName, conn):
    cols = []
    for i, r in enumerate(self.execute(conn, "PRAGMA TABLE_INFO(%s)" % tableName)):
        c = DeferredSetColumn(
            r[1],
            getter=lambda col, row, idx=i: row[idx],
            setter=lambda col, row, val: col.sheet.commit(),
        )
        t = r[2].lower()
        if t == "integer":
            c.type = int
        elif t == "text":
            c.type = anytype
        elif t == "blob":
            c.type = str
        elif t == "real":
            c.type = float
        else:
            status('unknown sqlite type "%s"' % t)

        cols.append(c)
        if r[-1]:
            self.setKeys([c])

    return cols


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def getColumns(self, tableName, conn):
    cols = []
    for i, r in enumerate(self.execute(conn, 'PRAGMA TABLE_INFO("%s")' % tableName)):
        c = DeferredSetColumn(
            r[1],
            getter=lambda col, row, idx=i: row[idx],
            setter=lambda col, row, val: col.sheet.commit(),
        )
        t = r[2].lower()
        if t == "integer":
            c.type = int
        elif t == "text":
            c.type = anytype
        elif t == "blob":
            c.type = str
        elif t == "real":
            c.type = float
        else:
            status('unknown sqlite type "%s"' % t)

        cols.append(c)
        if r[-1]:
            self.setKeys([c])

    return cols
# Buggy code
def multisave_sqlite(p, *vsheets):
    import sqlite3

    conn = sqlite3.connect(p.resolve())
    c = conn.cursor()

    for vs in vsheets:
        tblname = clean_to_id(vs.name)
        sqlcols = []
        for col in vs.visibleCols:
            sqlcols.append("%s %s" % (col.name, sqlite_type(col.type)))
        sql = "CREATE TABLE IF NOT EXISTS %s (%s)" % (tblname, ", ".join(sqlcols))
        c.execute(sql)

        for r in Progress(vs.rows, "saving"):
            sqlvals = []
            for col in vs.visibleCols:
                sqlvals.append(col.getTypedValue(r))
            sql = "INSERT INTO %s VALUES (%s)" % (
                tblname,
                ",".join(["?"] * len(sqlvals)),
            )
            c.execute(sql, sqlvals)

    conn.commit()

    status("%s save finished" % p)


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def multisave_sqlite(p, *vsheets):
    import sqlite3

    conn = sqlite3.connect(p.resolve())
    c = conn.cursor()

    for vs in vsheets:
        tblname = clean_to_id(vs.name)
        sqlcols = []
        for col in vs.visibleCols:
            sqlcols.append('"%s" %s' % (col.name, sqlite_type(col.type)))
        sql = 'CREATE TABLE IF NOT EXISTS "%s" (%s)' % (tblname, ", ".join(sqlcols))
        c.execute(sql)

        for r in Progress(vs.rows, "saving"):
            sqlvals = []
            for col in vs.visibleCols:
                sqlvals.append(col.getTypedValue(r))
            sql = 'INSERT INTO "%s" VALUES (%s)' % (
                tblname,
                ",".join(["?"] * len(sqlvals)),
            )
            c.execute(sql, sqlvals)

    conn.commit()

    status("%s save finished" % p)
# Buggy code
def reload_sync(self, _conn=None):
    with _conn or self.conn() as conn:
        tblname = self.tableName
        self.columns = self.getColumns(tblname, conn)
        self.recalc()
        r = self.execute(conn, "SELECT COUNT(*) FROM %s" % tblname).fetchall()
        rowcount = r[0][0]
        self.rows = []
        for row in Progress(
            self.execute(conn, "SELECT * FROM %s" % tblname), total=rowcount - 1
        ):
            self.addRow(row)


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def reload_sync(self, _conn=None):
    with _conn or self.conn() as conn:
        tblname = self.tableName
        self.columns = self.getColumns(tblname, conn)
        self.recalc()
        r = self.execute(conn, 'SELECT COUNT(*) FROM "%s"' % tblname).fetchall()
        rowcount = r[0][0]
        self.rows = []
        for row in Progress(
            self.execute(conn, 'SELECT * FROM "%s"' % tblname), total=rowcount - 1
        ):
            self.addRow(row)
# Buggy code
def getColumns(self, tableName, conn):
    cols = []
    for i, r in enumerate(self.execute(conn, "PRAGMA TABLE_INFO(%s)" % tableName)):
        c = Column(r[1], getter=lambda col, row, idx=i: row[idx])
        t = r[2].lower()
        if t == "integer":
            c.type = int
        elif t == "text":
            c.type = anytype
        elif t == "blob":
            c.type = str
        elif t == "real":
            c.type = float
        else:
            status('unknown sqlite type "%s"' % t)

        cols.append(c)
        if r[-1]:
            self.setKeys([c])

    return cols


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def getColumns(self, tableName, conn):
    cols = []
    for i, r in enumerate(self.execute(conn, 'PRAGMA TABLE_INFO("%s")' % tableName)):
        c = Column(r[1], getter=lambda col, row, idx=i: row[idx])
        t = r[2].lower()
        if t == "integer":
            c.type = int
        elif t == "text":
            c.type = anytype
        elif t == "blob":
            c.type = str
        elif t == "real":
            c.type = float
        else:
            status('unknown sqlite type "%s"' % t)

        cols.append(c)
        if r[-1]:
            self.setKeys([c])

    return cols
# Buggy code
def multisave_sqlite(p, *vsheets):
    import sqlite3

    conn = sqlite3.connect(str(p))
    c = conn.cursor()

    for vs in vsheets:
        tblname = clean_to_id(vs.name)
        sqlcols = []
        for col in vs.visibleCols:
            sqlcols.append("%s %s" % (col.name, sqlite_type(col.type)))
        sql = "CREATE TABLE IF NOT EXISTS %s (%s)" % (tblname, ", ".join(sqlcols))
        c.execute(sql)

        for r in Progress(vs.rows, "saving"):
            sqlvals = []
            for col in vs.visibleCols:
                sqlvals.append(col.getTypedValue(r))
            sql = "INSERT INTO %s VALUES (%s)" % (
                tblname,
                ",".join(["?"] * len(sqlvals)),
            )
            c.execute(sql, sqlvals)

    conn.commit()

    status("%s save finished" % p)


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):                                                           ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 1115, in exec_command        ‖
exec(cmd.execstr, vdglobals, LazyMap(self))                                              ‖
File "<string>", line 1, in <module>                                                       ‖
File "/usr/lib/python3/dist-packages/visidata/vdtui.py", line 961, in push                 ‖
vs.reload()                                                                              ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 24, in reload       ‖
self.columns = self.getColumns(tblname)                                                  ‖
File "/usr/lib/python3/dist-packages/visidata/loaders/sqlite.py", line 33, in getColumns   ‖
for i, r in enumerate(self.conn.execute('PRAGMA TABLE_INFO(%s)' % tableName)):           ‖
sqlite3.OperationalError: near "select": syntax error                                        ‖

# Fixed code
def multisave_sqlite(p, *vsheets):
    import sqlite3

    conn = sqlite3.connect(str(p))
    c = conn.cursor()

    for vs in vsheets:
        tblname = clean_to_id(vs.name)
        sqlcols = []
        for col in vs.visibleCols:
            sqlcols.append('"%s" %s' % (col.name, sqlite_type(col.type)))
        sql = 'CREATE TABLE IF NOT EXISTS "%s" (%s)' % (tblname, ", ".join(sqlcols))
        c.execute(sql)

        for r in Progress(vs.rows, "saving"):
            sqlvals = []
            for col in vs.visibleCols:
                sqlvals.append(col.getTypedValue(r))
            sql = 'INSERT INTO "%s" VALUES (%s)' % (
                tblname,
                ",".join("?" for v in sqlvals),
            )
            c.execute(sql, sqlvals)

    conn.commit()

    status("%s save finished" % p)