gurudesh/pytracebugs huggingface dataset:
# Buggy code
def search(type, hex, string, executable, writable, value, mapping, save, next):
    # Adjust pointer sizes to the local architecture
    if type == "pointer":
        type = {4: "dword", 8: "qword"}[pwndbg.arch.ptrsize]

    if save is None:
        save = bool(pwndbg.config.auto_save_search)

    if hex:
        value = codecs.decode(value, "hex")

    # Convert to an integer if needed, and pack to bytes
    if type not in ("string", "bytes"):
        value = pwndbg.commands.fix_int(value)
        fmt = {"little": "<", "big": ">"}[pwndbg.arch.endian] + {
            "byte": "B",
            "short": "H",
            "dword": "L",
            "qword": "Q",
        }[type]

        value = struct.pack(fmt, value)

    # Null-terminate strings
    elif type == "string":
        value += b"\x00"

    # Prep the saved set if necessary
    global saved
    if save:
        saved = set()

    # Perform the search
    for address in pwndbg.search.search(
        value, mapping=mapping, executable=executable, writable=writable
    ):
        if next and address not in saved:
            continue

        if save:
            saved.add(address)

        print_search_hit(address)


# Traceback (struct.error)
pwndbg> search -4 0xf7eebf83
Traceback (most recent call last):
File "/home/bruce30262/pwndbg/pwndbg/commands/__init__.py", line 57, in __call__
return self.function(*args, **kwargs)
File "/home/bruce30262/pwndbg/pwndbg/commands/__init__.py", line 162, in _ArgparsedCommand
return function(**vars(args))
File "/home/bruce30262/pwndbg/pwndbg/commands/__init__.py", line 115, in _OnlyWhenRunning
return function(*a, **kw)
File "/home/bruce30262/pwndbg/pwndbg/commands/search.py", line 112, in search
value = struct.pack(fmt, value)
struct.error: argument out of range

# Fixed code
def search(type, hex, string, executable, writable, value, mapping, save, next):
    # Adjust pointer sizes to the local architecture
    if type == "pointer":
        type = {4: "dword", 8: "qword"}[pwndbg.arch.ptrsize]

    if save is None:
        save = bool(pwndbg.config.auto_save_search)

    if hex:
        value = codecs.decode(value, "hex")

    # Convert to an integer if needed, and pack to bytes
    if type not in ("string", "bytes"):
        value = pwndbg.commands.fix_int(value)
        value &= pwndbg.arch.ptrmask
        fmt = {"little": "<", "big": ">"}[pwndbg.arch.endian] + {
            "byte": "B",
            "short": "H",
            "dword": "L",
            "qword": "Q",
        }[type]

        value = struct.pack(fmt, value)

    # Null-terminate strings
    elif type == "string":
        value += b"\x00"

    # Prep the saved set if necessary
    global saved
    if save:
        saved = set()

    # Perform the search
    for address in pwndbg.search.search(
        value, mapping=mapping, executable=executable, writable=writable
    ):
        if next and address not in saved:
            continue

        if save:
            saved.add(address)

        print_search_hit(address)
# Buggy code
def _same_modules(source_module, target_module):
    """Compare the filenames associated with the given modules names.

    This tries to not actually load the modules.
    """
    if not (source_module or target_module):
        return False

    if target_module == source_module:
        return True

    def _get_filename(module):
        filename = None
        try:
            if not inspect.ismodule(module):
                loader = pkgutil.get_loader(module)
                if loader:
                    filename = loader.get_filename()
            else:
                filename = inspect.getfile(module)
        except (TypeError, ImportError):
            pass

        return filename

    source_filename = _get_filename(source_module)
    target_filename = _get_filename(target_module)

    return source_filename and target_filename and source_filename == target_filename


# Traceback (AttributeError)
$ python
Python 3.7.5 (default, Jun  8 2020, 17:36:22)
[Clang 11.0.3 (clang-1103.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import hy
hy.eval(hy.read_str("(require  [hy.contrib.walk [let]])"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/compiler.py", line 2099, in hy_eval
module.__dict__, locals)
File "<string>", line 1, in <module>
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 170, in require
if _same_modules(source_module, target_module):
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 118, in _same_modules
target_filename = _get_filename(target_module)
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 109, in _get_filename
filename = loader.get_filename()
AttributeError: type object 'BuiltinImporter' has no attribute 'get_filename'

# Fixed code
def _same_modules(source_module, target_module):
    """Compare the filenames associated with the given modules names.

    This tries to not actually load the modules.
    """
    if not (source_module or target_module):
        return False

    if target_module == source_module:
        return True

    def _get_filename(module):
        filename = None
        try:
            if not inspect.ismodule(module):
                loader = pkgutil.get_loader(module)
                if isinstance(loader, importlib.machinery.SourceFileLoader):
                    filename = loader.get_filename()
            else:
                filename = inspect.getfile(module)
        except (TypeError, ImportError):
            pass

        return filename

    source_filename = _get_filename(source_module)
    target_filename = _get_filename(target_module)

    return source_filename and target_filename and source_filename == target_filename
# Buggy code
def _get_filename(module):
    filename = None
    try:
        if not inspect.ismodule(module):
            loader = pkgutil.get_loader(module)
            if loader:
                filename = loader.get_filename()
        else:
            filename = inspect.getfile(module)
    except (TypeError, ImportError):
        pass

    return filename


# Traceback (AttributeError)
$ python
Python 3.7.5 (default, Jun  8 2020, 17:36:22)
[Clang 11.0.3 (clang-1103.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import hy
hy.eval(hy.read_str("(require  [hy.contrib.walk [let]])"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/compiler.py", line 2099, in hy_eval
module.__dict__, locals)
File "<string>", line 1, in <module>
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 170, in require
if _same_modules(source_module, target_module):
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 118, in _same_modules
target_filename = _get_filename(target_module)
File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 109, in _get_filename
filename = loader.get_filename()
AttributeError: type object 'BuiltinImporter' has no attribute 'get_filename'

# Fixed code
def _get_filename(module):
    filename = None
    try:
        if not inspect.ismodule(module):
            loader = pkgutil.get_loader(module)
            if isinstance(loader, importlib.machinery.SourceFileLoader):
                filename = loader.get_filename()
        else:
            filename = inspect.getfile(module)
    except (TypeError, ImportError):
        pass

    return filename
# Buggy code
def run_command(source, filename=None):
    __main__ = importlib.import_module("__main__")
    require("hy.cmdline", __main__, assignments="ALL")
    try:
        tree = hy_parse(source, filename=filename)
    except HyLanguageError:
        hy_exc_handler(*sys.exc_info())
        return 1

    with filtered_hy_exceptions():
        hy_eval(tree, None, __main__, filename=filename, source=source)
    return 0


# Traceback (NameError)
$ CODE='(import math) (print (lfor j [1] (math.sqrt 5)))'
$ hy -c "$CODE"
Traceback (most recent call last):
File "/usr/local/bin/hy", line 8, in <module>
sys.exit(hy_main())
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>
NameError: name 'math' is not defined
$ echo "$CODE" | hy
hy 0.18.0 using CPython(default) 3.7.5 on Linux
=> [2.23606797749979]
=>
now exiting HyREPL...
$ echo "$CODE" > /tmp/foo.hy &amp;&amp; hy /tmp/foo.hy
[2.23606797749979]

# Fixed code
def run_command(source, filename=None):
    __main__ = importlib.import_module("__main__")
    require("hy.cmdline", __main__, assignments="ALL")
    try:
        tree = hy_parse(source, filename=filename)
    except HyLanguageError:
        hy_exc_handler(*sys.exc_info())
        return 1

    with filtered_hy_exceptions():
        hy_eval(tree, __main__.__dict__, __main__, filename=filename, source=source)
    return 0
# Buggy code
def mangle(s):
    """Stringify the argument and convert it to a valid Python identifier
    according to Hy's mangling rules."""

    def unicode_char_to_hex(uchr):
        # Covert a unicode char to hex string, without prefix
        return (
            uchr.encode("unicode-escape")
            .decode("utf-8")
            .lstrip("\\U")
            .lstrip("\\u")
            .lstrip("0")
        )

    assert s

    s = str_type(s)
    s = s.replace("-", "_")
    s2 = s.lstrip("_")
    leading_underscores = "_" * (len(s) - len(s2))
    s = s2

    if s.endswith("?"):
        s = "is_" + s[:-1]
    if not isidentifier(leading_underscores + s):
        # Replace illegal characters with their Unicode character
        # names, or hexadecimal if they don't have one.
        s = "hyx_" + "".join(
            c
            if c != mangle_delim and isidentifier("S" + c)
            # We prepend the "S" because some characters aren't
            # allowed at the start of an identifier.
            else "{0}{1}{0}".format(
                mangle_delim,
                unicodedata.name(c, "").lower().replace("-", "H").replace(" ", "_")
                or "U{}".format(unicode_char_to_hex(c)),
            )
            for c in unicode_to_ucs4iter(s)
        )

    s = leading_underscores + s
    assert isidentifier(s)
    return s


# Traceback (ValueError)
=> (mangle "\n")
'hyx_XUnX'
=> (unmangle (mangle "\n"))
Traceback (most recent call last):
…
ValueError: invalid literal for int() with base 16: 'n'

# Fixed code
def mangle(s):
    """Stringify the argument and convert it to a valid Python identifier
    according to Hy's mangling rules."""

    def unicode_char_to_hex(uchr):
        # Covert a unicode char to hex string, without prefix
        if len(uchr) == 1 and ord(uchr) < 128:
            return format(ord(uchr), "x")
        return (
            uchr.encode("unicode-escape")
            .decode("utf-8")
            .lstrip("\\U")
            .lstrip("\\u")
            .lstrip("\\x")
            .lstrip("0")
        )

    assert s

    s = str_type(s)
    s = s.replace("-", "_")
    s2 = s.lstrip("_")
    leading_underscores = "_" * (len(s) - len(s2))
    s = s2

    if s.endswith("?"):
        s = "is_" + s[:-1]
    if not isidentifier(leading_underscores + s):
        # Replace illegal characters with their Unicode character
        # names, or hexadecimal if they don't have one.
        s = "hyx_" + "".join(
            c
            if c != mangle_delim and isidentifier("S" + c)
            # We prepend the "S" because some characters aren't
            # allowed at the start of an identifier.
            else "{0}{1}{0}".format(
                mangle_delim,
                unicodedata.name(c, "").lower().replace("-", "H").replace(" ", "_")
                or "U{}".format(unicode_char_to_hex(c)),
            )
            for c in unicode_to_ucs4iter(s)
        )

    s = leading_underscores + s
    assert isidentifier(s)
    return s
# Buggy code
def unicode_char_to_hex(uchr):
    # Covert a unicode char to hex string, without prefix
    return (
        uchr.encode("unicode-escape")
        .decode("utf-8")
        .lstrip("\\U")
        .lstrip("\\u")
        .lstrip("0")
    )


# Traceback (ValueError)
=> (mangle "\n")
'hyx_XUnX'
=> (unmangle (mangle "\n"))
Traceback (most recent call last):
…
ValueError: invalid literal for int() with base 16: 'n'

# Fixed code
def unicode_char_to_hex(uchr):
    # Covert a unicode char to hex string, without prefix
    if len(uchr) == 1 and ord(uchr) < 128:
        return format(ord(uchr), "x")
    return (
        uchr.encode("unicode-escape")
        .decode("utf-8")
        .lstrip("\\U")
        .lstrip("\\u")
        .lstrip("\\x")
        .lstrip("0")
    )
# Buggy code
def __getattr__(self, name):
    setattr(
        Asty,
        name,
        lambda self, x, **kwargs: getattr(ast, name)(
            lineno=getattr(x, "start_line", getattr(x, "lineno", None)),
            col_offset=getattr(x, "start_column", getattr(x, "col_offset", None)),
            **kwargs,
        ),
    )
    return getattr(self, name)


# Traceback (NameError)
=> (list-comp (do (print n) (print n)) [n [1 2]])
print(n)
[print(n) for n in [1L, 2L]]
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'n' is not defined

# Fixed code
def __getattr__(self, name):
    setattr(
        Asty,
        name,
        staticmethod(
            lambda x, **kwargs: getattr(ast, name)(
                lineno=getattr(x, "start_line", getattr(x, "lineno", None)),
                col_offset=getattr(x, "start_column", getattr(x, "col_offset", None)),
                **kwargs,
            )
        ),
    )
    return getattr(Asty, name)
# Buggy code
def spoof_positions(obj):
    if not isinstance(obj, HyObject) or isinstance(obj, HyCons):
        return
    if not hasattr(obj, "start_column"):
        obj.start_column = 0
    if not hasattr(obj, "start_line"):
        obj.start_line = 0
    if hasattr(obj, "__iter__") and not isinstance(obj, (string_types, bytes_type)):
        for x in obj:
            spoof_positions(x)


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def spoof_positions(obj):
    if not isinstance(obj, HyObject):
        return
    if not hasattr(obj, "start_column"):
        obj.start_column = 0
    if not hasattr(obj, "start_line"):
        obj.start_line = 0
    if hasattr(obj, "__iter__") and not isinstance(obj, (string_types, bytes_type)):
        for x in obj:
            spoof_positions(x)
# Buggy code
def paren(p):
    cont = p[1]

    # Dotted lists are expressions of the form
    # (a b c . d)
    # that evaluate to nested cons cells of the form
    # (a . (b . (c . d)))
    if len(cont) >= 3 and isinstance(cont[-2], HySymbol) and cont[-2] == ".":
        reject_spurious_dots(cont[:-2], cont[-1:])

        if len(cont) == 3:
            # Two-item dotted list: return the cons cell directly
            return HyCons(cont[0], cont[2])
        else:
            # Return a nested cons cell
            return HyCons(cont[0], paren([p[0], cont[1:], p[2]]))

    # Warn preemptively on a malformed dotted list.
    # Only check for dots after the first item to allow for a potential
    # attribute accessor shorthand
    reject_spurious_dots(cont[1:])

    return HyExpression(p[1])


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def paren(p):
    return HyExpression(p[1])
# Buggy code
def replace(self, other):
    if self.car is not None:
        replace_hy_obj(self.car, other)
    if self.cdr is not None:
        replace_hy_obj(self.cdr, other)

    HyObject.replace(self, other)


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def replace(self, other):
    for x in self:
        replace_hy_obj(x, other)

    HyObject.replace(self, other)
    return self
# Buggy code
def __repr__(self):
    if PRETTY:
        return str(self)
    else:
        return "HyCons({}, {})".format(repr(self.car), repr(self.cdr))


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def __repr__(self):
    return str(self) if PRETTY else super(HyList, self).__repr__()
# Buggy code
def __new__(cls, car, cdr):
    if isinstance(cdr, list):
        # Keep unquotes in the cdr of conses
        if type(cdr) == HyExpression:
            if len(cdr) > 0 and type(cdr[0]) == HySymbol:
                if cdr[0] in ("unquote", "unquote-splice"):
                    return super(HyCons, cls).__new__(cls)

        return cdr.__class__([wrap_value(car)] + cdr)

    elif cdr is None:
        return HyExpression([wrap_value(car)])

    else:
        return super(HyCons, cls).__new__(cls)


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def __new__(cls, real, imag=0, *args, **kwargs):
    if isinstance(real, string_types):
        value = super(HyComplex, cls).__new__(cls, strip_digit_separators(real))
        p1, _, p2 = real.lstrip("+-").replace("-", "+").partition("+")
        check_inf_nan_cap(p1, value.imag if "j" in p1 else value.real)
        if p2:
            check_inf_nan_cap(p2, value.imag)
        return value
    return super(HyComplex, cls).__new__(cls, real, imag)
# Buggy code
def __init__(self, car, cdr):
    self.car = wrap_value(car)
    self.cdr = wrap_value(cdr)


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def __init__(self, value):
    self.name = value
# Buggy code
def __str__(self):
    with pretty():
        c = colored.yellow
        lines = ["" + c("<HyCons (")]
        while True:
            lines.append("  " + repr_indent(self.car))
            if not isinstance(self.cdr, HyCons):
                break
            self = self.cdr
        lines.append("{} {}{}".format(c("."), repr_indent(self.cdr), c(")>")))
        return "\n".join(lines)


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def __str__(self):
    with pretty():
        g = colored.green
        if self:
            pairs = []
            for k, v in zip(self[::2], self[1::2]):
                k, v = repr_indent(k), repr_indent(v)
                pairs.append(
                    ("{0}{c}\n  {1}\n  " if "\n" in k + v else "{0}{c} {1}").format(
                        k, v, c=g(",")
                    )
                )
            if len(self) % 2 == 1:
                pairs.append("{}  {}\n".format(repr_indent(self[-1]), g("# odd")))
            return "{}\n  {}{}".format(
                g("HyDict(["), ("{c}\n  ".format(c=g(",")).join(pairs)), g("])")
            )
        else:
            return "" + g("HyDict()")
# Buggy code
def __eq__(self, other):
    return (
        isinstance(other, self.__class__)
        and self.car == other.car
        and self.cdr == other.cdr
    )


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def __eq__(self, other):
    if not isinstance(other, HyKeyword):
        return NotImplemented
    return self.name == other.name
# Buggy code
def __getitem__(self, n):
    if n == 0:
        return self.car
    if n == slice(1, None):
        return self.cdr

    raise IndexError("Can only get the car ([0]) or the cdr ([1:]) of a HyCons")


# Traceback (TypeError)
=> (setv c (cons {"a" 1} []))
from hy.core.language import cons
c = cons({u'a': 1L, }, [])
=> (type (car c))
type(c[0L])
<class 'hy.models.dict.HyDict'>
=> (get (car c) "a")
c[0L][u'a']
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/maresp/workbench/cbf/venv/lib/python2.7/site-packages/hy/models/list.py", line 43, in __getitem__
ret = super(HyList, self).__getitem__(item)
TypeError: list indices must be integers, not unicode
=>

# Fixed code
def __getitem__(self, item):
    ret = super(HyList, self).__getitem__(item)

    if isinstance(item, slice):
        return self.__class__(ret)

    return ret
# Buggy code
def imports_as_stmts(self, expr):
    """Convert the Result's imports to statements"""
    ret = Result()
    for module, names in self.imports.items():
        if None in names:
            ret += self.compile(
                [
                    HyExpression(
                        [
                            HySymbol("import"),
                            HySymbol(module),
                        ]
                    ).replace(expr)
                ]
            )
        names = sorted(name for name in names if name)
        if names:
            ret += self.compile(
                [
                    HyExpression(
                        [
                            HySymbol("import"),
                            HyList(
                                [
                                    HySymbol(module),
                                    HyList([HySymbol(name) for name in names]),
                                ]
                            ),
                        ]
                    ).replace(expr)
                ]
            )
    self.imports = defaultdict(set)
    return ret.stmts


# Traceback (TypeError)
=> (import numpy)


=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)

# Fixed code
def imports_as_stmts(self, expr):
    """Convert the Result's imports to statements"""
    ret = Result()
    for module, names in self.imports.items():
        if None in names:
            e = HyExpression(
                [
                    HySymbol("import"),
                    HySymbol(module),
                ]
            ).replace(expr)
            spoof_positions(e)
            ret += self.compile(e)
        names = sorted(name for name in names if name)
        if names:
            e = HyExpression(
                [
                    HySymbol("import"),
                    HyList(
                        [HySymbol(module), HyList([HySymbol(name) for name in names])]
                    ),
                ]
            ).replace(expr)
            spoof_positions(e)
            ret += self.compile(e)
    self.imports = defaultdict(set)
    return ret.stmts
# Buggy code
def compile_atom(self, atom_type, atom):
    if atom_type in _compile_table:
        ret = _compile_table[atom_type](self, atom)
        if not isinstance(ret, Result):
            ret = Result() + ret
        return ret


# Traceback (TypeError)
=> (import numpy)


=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)

# Fixed code
def compile_atom(self, atom_type, atom):
    if atom_type in _compile_table:
        ret = _compile_table[atom_type](self, atom)
        if not isinstance(ret, Result):
            ret = Result() + ret
        return ret
    if not isinstance(atom, HyObject):
        atom = wrap_value(atom)
        if isinstance(atom, HyObject):
            spoof_positions(atom)
            return self.compile_atom(type(atom), atom)
# Buggy code
def _compile_maths_expression(self, expression):
    ops = {
        "+": ast.Add,
        "/": ast.Div,
        "//": ast.FloorDiv,
        "*": ast.Mult,
        "-": ast.Sub,
        "%": ast.Mod,
        "**": ast.Pow,
        "<<": ast.LShift,
        ">>": ast.RShift,
        "|": ast.BitOr,
        "^": ast.BitXor,
        "&": ast.BitAnd,
    }
    if PY35:
        ops.update({"@": ast.MatMult})

    op = ops[expression.pop(0)]
    right_associative = op == ast.Pow

    if right_associative:
        expression = expression[::-1]
    ret = self.compile(expression.pop(0))
    for child in expression:
        left_expr = ret.force_expr
        ret += self.compile(child)
        right_expr = ret.force_expr
        if right_associative:
            left_expr, right_expr = right_expr, left_expr
        ret += ast.BinOp(
            left=left_expr,
            op=op(),
            right=right_expr,
            lineno=child.start_line,
            col_offset=child.start_column,
        )
    return ret


# Traceback (TypeError)
=> (import numpy)


=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)

# Fixed code
def _compile_maths_expression(self, expression):
    ops = {
        "+": ast.Add,
        "/": ast.Div,
        "//": ast.FloorDiv,
        "*": ast.Mult,
        "-": ast.Sub,
        "%": ast.Mod,
        "**": ast.Pow,
        "<<": ast.LShift,
        ">>": ast.RShift,
        "|": ast.BitOr,
        "^": ast.BitXor,
        "&": ast.BitAnd,
    }
    if PY35:
        ops.update({"@": ast.MatMult})

    op = ops[expression.pop(0)]
    right_associative = op == ast.Pow

    lineno, col_offset = expression.start_line, expression.start_column
    if right_associative:
        expression = expression[::-1]
    ret = self.compile(expression.pop(0))
    for child in expression:
        left_expr = ret.force_expr
        ret += self.compile(child)
        right_expr = ret.force_expr
        if right_associative:
            left_expr, right_expr = right_expr, left_expr
        ret += ast.BinOp(
            left=left_expr,
            op=op(),
            right=right_expr,
            lineno=lineno,
            col_offset=col_offset,
        )
    return ret
# Buggy code
def hy_compile(tree, module_name, root=ast.Module, get_expr=False):
    """
    Compile a HyObject tree into a Python AST Module.

    If `get_expr` is True, return a tuple (module, last_expression), where
    `last_expression` is the.
    """

    body = []
    expr = None

    if not (isinstance(tree, HyObject) or type(tree) is list):
        raise HyCompileError("tree must be a HyObject or a list")

    if isinstance(tree, HyObject) or tree:
        compiler = HyASTCompiler(module_name)
        result = compiler.compile(tree)
        expr = result.force_expr

        if not get_expr:
            result += result.expr_as_stmt()

        # We need to test that the type is *exactly* `list` because we don't
        # want to do `tree[0]` on HyList or such.
        spoof_tree = tree[0] if type(tree) is list else tree
        body = compiler.imports_as_stmts(spoof_tree) + result.stmts

    ret = root(body=body)

    if get_expr:
        expr = ast.Expression(body=expr)
        ret = (ret, expr)

    return ret


# Traceback (TypeError)
=> (import numpy)


=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)

# Fixed code
def hy_compile(tree, module_name, root=ast.Module, get_expr=False):
    """
    Compile a HyObject tree into a Python AST Module.

    If `get_expr` is True, return a tuple (module, last_expression), where
    `last_expression` is the.
    """

    body = []
    expr = None

    if not isinstance(tree, HyObject):
        tree = wrap_value(tree)
        if not isinstance(tree, HyObject):
            raise HyCompileError(
                "`tree` must be a HyObject or capable of being promoted to one"
            )
        spoof_positions(tree)

    compiler = HyASTCompiler(module_name)
    result = compiler.compile(tree)
    expr = result.force_expr

    if not get_expr:
        result += result.expr_as_stmt()

    body = compiler.imports_as_stmts(tree) + result.stmts

    ret = root(body=body)

    if get_expr:
        expr = ast.Expression(body=expr)
        ret = (ret, expr)

    return ret
# Buggy code
def import_buffer_to_hst(buf):
    """Import content from buf and return a Hy AST."""
    return tokenize(buf + "\n")


# Traceback (TypeError)
=> (import numpy)


=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)

# Fixed code
def import_buffer_to_hst(buf):
    """Import content from buf and return a Hy AST."""
    return HyExpression([HySymbol("do")] + tokenize(buf + "\n"))
# Buggy code
def tag_macroexpand(tag, tree, compiler):
    """Expand the tag macro "tag" with argument `tree`."""
    load_macros(compiler.module_name)

    tag_macro = _hy_tag[compiler.module_name].get(tag)
    if tag_macro is None:
        try:
            tag_macro = _hy_tag[None][tag]
        except KeyError:
            raise HyTypeError(tag, "`{0}' is not a defined tag macro.".format(tag))

    expr = tag_macro(tree)
    return replace_hy_obj(wrap_value(expr), tree)


# Traceback (TypeError)
=> (import numpy)


=> (= "." (get (name numpy) 0)))
False
=> (eval '(= "." (get (name numpy) 0)))
False
=> (eval `(= "." ~(get (name numpy) 0)))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/importer.py", line 110, in hy_eval
hytree.replace(foo)
File "/Users/dg/anaconda3/lib/python3.5/site-packages/hy/models/list.py", line 31, in replace
x.replace(other)
TypeError: replace() takes at least 2 arguments (1 given)

# Fixed code
def tag_macroexpand(tag, tree, compiler):
    """Expand the tag macro "tag" with argument `tree`."""
    load_macros(compiler.module_name)

    tag_macro = _hy_tag[compiler.module_name].get(tag)
    if tag_macro is None:
        try:
            tag_macro = _hy_tag[None][tag]
        except KeyError:
            raise HyTypeError(tag, "`{0}' is not a defined tag macro.".format(tag))

    expr = tag_macro(tree)
    return replace_hy_obj(expr, tree)
# Buggy code
def tokenize(buf):
    """
    Tokenize a Lisp file or string buffer into internal Hy objects.
    """
    try:
        return parser.parse(lexer.lex(buf))
    except LexingError as e:
        pos = e.getsourcepos()
        raise LexException("Could not identify the next token.", pos.lineno, pos.colno)
    except LexException as e:
        if e.source is None:
            e.source = buf
        raise


# Traceback (AttributeError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "hy/cmdline.py", line 406, in hy2py_main
if stdin_text is None
File "hy/cmdline.py", line 186, in pretty_error
print(e, file=sys.stderr)
File "hy/lex/exceptions.py", line 43, in __str__
source = self.source.split("\n")
AttributeError: 'NoneType' object has no attribute 'split'

# Fixed code
def tokenize(buf):
    """
    Tokenize a Lisp file or string buffer into internal Hy objects.
    """
    try:
        return parser.parse(lexer.lex(buf))
    except LexingError as e:
        pos = e.getsourcepos()
        raise LexException(
            "Could not identify the next token.", pos.lineno, pos.colno, buf
        )
    except LexException as e:
        if e.source is None:
            e.source = buf
        raise
# Buggy code
def __init__(self, message, lineno, colno):
    super(LexException, self).__init__(message)
    self.message = message
    self.lineno = lineno
    self.colno = colno
    self.source = None
    self.filename = "<stdin>"


# Traceback (AttributeError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "hy/cmdline.py", line 406, in hy2py_main
if stdin_text is None
File "hy/cmdline.py", line 186, in pretty_error
print(e, file=sys.stderr)
File "hy/lex/exceptions.py", line 43, in __str__
source = self.source.split("\n")
AttributeError: 'NoneType' object has no attribute 'split'

# Fixed code
def __init__(self, message, lineno, colno, source=None):
    super(LexException, self).__init__(message)
    self.message = message
    self.lineno = lineno
    self.colno = colno
    self.source = source
    self.filename = "<stdin>"
# Buggy code
def runsource(self, source, filename="<input>", symbol="single"):
    global SIMPLE_TRACEBACKS
    try:
        tokens = tokenize(source)
    except PrematureEndOfInput:
        return True
    except LexException as e:
        if e.source is None:
            e.source = source
            e.filename = filename
        sys.stderr.write(str(e))
        return False

    try:
        _ast = hy_compile(tokens, "__console__", root=ast.Interactive)
        if self.spy:
            print_python_code(_ast)
        code = ast_compile(_ast, filename, symbol)
    except HyTypeError as e:
        if e.source is None:
            e.source = source
            e.filename = filename
        if SIMPLE_TRACEBACKS:
            sys.stderr.write(str(e))
        else:
            self.showtraceback()
        return False
    except Exception:
        self.showtraceback()
        return False

    self.runcode(code)
    return False


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)

# Fixed code
def runsource(self, source, filename="<input>", symbol="single"):
    global SIMPLE_TRACEBACKS
    try:
        tokens = tokenize(source)
    except PrematureEndOfInput:
        return True
    except LexException as e:
        if e.source is None:
            e.source = source
            e.filename = filename
        print(e, file=sys.stderr)
        return False

    try:
        _ast = hy_compile(tokens, "__console__", root=ast.Interactive)
        if self.spy:
            print_python_code(_ast)
        code = ast_compile(_ast, filename, symbol)
    except HyTypeError as e:
        if e.source is None:
            e.source = source
            e.filename = filename
        if SIMPLE_TRACEBACKS:
            print(e, file=sys.stderr)
        else:
            self.showtraceback()
        return False
    except Exception:
        self.showtraceback()
        return False

    self.runcode(code)
    return False
# Buggy code
def pretty_error(func, *args, **kw):
    try:
        return func(*args, **kw)
    except (HyTypeError, LexException) as e:
        if SIMPLE_TRACEBACKS:
            sys.stderr.write(str(e))
            sys.exit(1)
        raise


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)

# Fixed code
def pretty_error(func, *args, **kw):
    try:
        return func(*args, **kw)
    except (HyTypeError, LexException) as e:
        if SIMPLE_TRACEBACKS:
            print(e, file=sys.stderr)
            sys.exit(1)
        raise
# Buggy code
def run_module(mod_name):
    from hy.importer import MetaImporter

    pth = MetaImporter().find_on_path(mod_name)
    if pth is not None:
        sys.argv = [pth] + sys.argv
        return run_file(pth)

    sys.stderr.write("{0}: module '{1}' not found.\n".format(hy.__appname__, mod_name))
    return 1


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)

# Fixed code
def run_module(mod_name):
    from hy.importer import MetaImporter

    pth = MetaImporter().find_on_path(mod_name)
    if pth is not None:
        sys.argv = [pth] + sys.argv
        return run_file(pth)

    print(
        "{0}: module '{1}' not found.\n".format(hy.__appname__, mod_name),
        file=sys.stderr,
    )
    return 1
# Buggy code
def hyc_main():
    from hy.importer import write_hy_as_pyc

    parser = argparse.ArgumentParser(prog="hyc")
    parser.add_argument("files", metavar="FILE", nargs="+", help="file to compile")
    parser.add_argument("-v", action="version", version=VERSION)

    options = parser.parse_args(sys.argv[1:])

    for file in options.files:
        try:
            print("Compiling %s" % file)
            pretty_error(write_hy_as_pyc, file)
        except IOError as x:
            sys.stderr.write(
                "hyc: Can't open file '%s': [Errno %d] %s\n"
                % (x.filename, x.errno, x.strerror)
            )
            sys.exit(x.errno)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/usr/bin/hy", line 9, in <module>
load_entry_point('hy==0.11.0', 'console_scripts', 'hy')()
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 347, in hy_main
sys.exit(cmdline_handler("hy", sys.argv))
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 342, in cmdline_handler
return run_repl(spy=options.spy)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 240, in run_repl
os=platform.system()
File "/usr/lib64/python2.7/code.py", line 243, in interact
more = self.push(line)
File "/usr/lib64/python2.7/code.py", line 265, in push
more = self.runsource(source, self.filename)
File "/usr/lib/python2.7/site-packages/hy/cmdline.py", line 113, in runsource
sys.stderr.write(str(e))
File "/usr/lib/python2.7/site-packages/hy/errors.py", line 104, in __str__
self.message))
File "/usr/lib/python2.7/site-packages/clint/textui/colored.py", line 108, in __radd__
return str(other) + str(self.color_str)
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufdd0' in position 24: ordinal not in range(128)

# Fixed code
def hyc_main():
    from hy.importer import write_hy_as_pyc

    parser = argparse.ArgumentParser(prog="hyc")
    parser.add_argument("files", metavar="FILE", nargs="+", help="file to compile")
    parser.add_argument("-v", action="version", version=VERSION)

    options = parser.parse_args(sys.argv[1:])

    for file in options.files:
        try:
            print("Compiling %s" % file)
            pretty_error(write_hy_as_pyc, file)
        except IOError as x:
            print(
                "hyc: Can't open file '{0}': [Errno {1}] {2}\n".format(
                    x.filename, x.errno, x.strerror
                ),
                file=sys.stderr,
            )
            sys.exit(x.errno)
# Buggy code
def compile_list_comprehension(self, expr):
    # (list-comp expr (target iter) cond?)
    expr.pop(0)
    expression = expr.pop(0)

    gen_res, gen = self._compile_generator_iterables(expr)

    compiled_expression = self.compile(expression)
    ret = compiled_expression + gen_res
    ret += ast.ListComp(
        lineno=expr.start_line,
        col_offset=expr.start_column,
        elt=compiled_expression.force_expr,
        generators=gen,
    )

    return ret


# Traceback (ValueError)
ryan@DevPC-LX:~/stuff/hy$ ~/stuff/anaconda/bin/hy
hy 0.10.0 using CPython(default) 3.3.5 on Linux
=> (list-comp [x [1 2 3]] x)
Traceback (most recent call last):
File "/home/ryan/stuff/anaconda/lib/python3.3/site-packages/hy-0.10.0-py3.3.egg/hy/importer.py", line 42, in ast_compile
return compile(ast, filename, mode, flags)
ValueError: comprehension with no generators
=>

# Fixed code
def compile_list_comprehension(self, expr):
    # (list-comp expr (target iter) cond?)
    expr.pop(0)
    expression = expr.pop(0)
    gen_gen = expr[0]

    if not isinstance(gen_gen, HyList):
        raise HyTypeError(gen_gen, "Generator expression must be a list.")

    gen_res, gen = self._compile_generator_iterables(expr)

    if len(gen) == 0:
        raise HyTypeError(gen_gen, "Generator expression cannot be empty.")

    compiled_expression = self.compile(expression)
    ret = compiled_expression + gen_res
    ret += ast.ListComp(
        lineno=expr.start_line,
        col_offset=expr.start_column,
        elt=compiled_expression.force_expr,
        generators=gen,
    )

    return ret
# Buggy code
def other_package_info(info, desc):
    """Return information about another package supporting the device."""
    return "%s @ %s, check %s" % (info.name, ipaddress.ip_address(info.address), desc)


# Traceback (AttributeError)
INFO:miio.discovery:Discovering devices with mDNS, press any key to quit...
Exception in thread zeroconf-ServiceBrowser__miio._udp.local._229705:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1750, in run
self._service_state_changed.fire(
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1508, in fire
h(**kwargs)
File "/home/user/.local/lib/python3.9/site-packages/zeroconf/__init__.py", line 1606, in on_change
listener.add_service(*args)
File "/home/user/.local/lib/python3.9/site-packages/miio/discovery.py", line 256, in add_service
addr = str(ipaddress.ip_address(info.address))
AttributeError: 'ServiceInfo' object has no attribute 'address'

# Fixed code
def other_package_info(info, desc):
    """Return information about another package supporting the device."""
    return "Found %s at %s, check %s" % (info.name, get_addr_from_info(info), desc)