gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __truediv__(self, other):
    # there is no true divide if the rhs is not a scalar, although it
    # could return the first n elements of an infinite series.
    # It is hard to see where n would come from, though.
    if np.isscalar(other):
        # this might be overly restrictive
        coef = self.coef / other
        return self.__class__(coef, self.domain, self.window)
    else:
        return NotImplemented


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __truediv__(self, other):
    # there is no true divide if the rhs is not a Number, although it
    # could return the first n elements of an infinite series.
    # It is hard to see where n would come from, though.
    if not isinstance(other, Number) or isinstance(other, bool):
        form = "unsupported types for true division: '%s', '%s'"
        raise TypeError(form % (type(self), type(other)))
    return self.__floordiv__(other)
# Buggy code
def __floordiv__(self, other):
    if isinstance(other, ABCPolyBase):
        if not self.has_sametype(other):
            raise TypeError("Polynomial types differ")
        elif not self.has_samedomain(other):
            raise TypeError("Domains differ")
        elif not self.has_samewindow(other):
            raise TypeError("Windows differ")
        else:
            quo, rem = self._div(self.coef, other.coef)
    else:
        try:
            quo, rem = self._div(self.coef, other)
        except:
            return NotImplemented
    return self.__class__(quo, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __floordiv__(self, other):
    res = self.__divmod__(other)
    if res is NotImplemented:
        return res
    return res[0]
# Buggy code
def __mod__(self, other):
    if isinstance(other, ABCPolyBase):
        if not self.has_sametype(other):
            raise TypeError("Polynomial types differ")
        elif not self.has_samedomain(other):
            raise TypeError("Domains differ")
        elif not self.has_samewindow(other):
            raise TypeError("Windows differ")
        else:
            quo, rem = self._div(self.coef, other.coef)
    else:
        try:
            quo, rem = self._div(self.coef, other)
        except:
            return NotImplemented
    return self.__class__(rem, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __mod__(self, other):
    res = self.__divmod__(other)
    if res is NotImplemented:
        return res
    return res[1]
# Buggy code
def __divmod__(self, other):
    if isinstance(other, self.__class__):
        if not self.has_samedomain(other):
            raise TypeError("Domains are not equal")
        elif not self.has_samewindow(other):
            raise TypeError("Windows are not equal")
        else:
            quo, rem = self._div(self.coef, other.coef)
    else:
        try:
            quo, rem = self._div(self.coef, other)
        except:
            return NotImplemented
    quo = self.__class__(quo, self.domain, self.window)
    rem = self.__class__(rem, self.domain, self.window)
    return quo, rem


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __divmod__(self, other):
    try:
        othercoef = self._get_coefficients(other)
        quo, rem = self._div(self.coef, othercoef)
    except (TypeError, ZeroDivisionError) as e:
        raise e
    except:
        return NotImplemented
    quo = self.__class__(quo, self.domain, self.window)
    rem = self.__class__(rem, self.domain, self.window)
    return quo, rem
# Buggy code
def __pow__(self, other):
    try:
        coef = self._pow(self.coef, other, maxpower=self.maxpower)
    except:
        raise
    return self.__class__(coef, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __pow__(self, other):
    coef = self._pow(self.coef, other, maxpower=self.maxpower)
    res = self.__class__(coef, self.domain, self.window)
    return res
# Buggy code
def __rtruediv__(self, other):
    # there is no true divide if the rhs is not a scalar, although it
    # could return the first n elements of an infinite series.
    # It is hard to see where n would come from, though.
    if len(self.coef) == 1:
        try:
            quo, rem = self._div(other, self.coef[0])
        except:
            return NotImplemented
    return self.__class__(quo, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __rtruediv__(self, other):
    # An instance of ABCPolyBase is not considered a
    # Number.
    return NotImplemented
# Buggy code
def __rfloordiv__(self, other):
    try:
        quo, rem = self._div(other, self.coef)
    except:
        return NotImplemented
    return self.__class__(quo, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __rfloordiv__(self, other):
    res = self.__rdivmod__(other)
    if res is NotImplemented:
        return res
    return res[0]
# Buggy code
def __rmod__(self, other):
    try:
        quo, rem = self._div(other, self.coef)
    except:
        return NotImplemented
    return self.__class__(rem, self.domain, self.window)


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __rmod__(self, other):
    res = self.__rdivmod__(other)
    if res is NotImplemented:
        return res
    return res[1]
# Buggy code
def __rdivmod__(self, other):
    try:
        quo, rem = self._div(other, self.coef)
    except:
        return NotImplemented
    quo = self.__class__(quo, self.domain, self.window)
    rem = self.__class__(rem, self.domain, self.window)
    return quo, rem


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __rdivmod__(self, other):
    try:
        quo, rem = self._div(other, self.coef)
    except ZeroDivisionError as e:
        raise e
    except:
        return NotImplemented
    quo = self.__class__(quo, self.domain, self.window)
    rem = self.__class__(rem, self.domain, self.window)
    return quo, rem
# Buggy code
def __eq__(self, other):
    res = (
        isinstance(other, self.__class__)
        and self.has_samecoef(other)
        and self.has_samedomain(other)
        and self.has_samewindow(other)
    )
    return res


# Traceback (UnboundLocalError)
In [1]: import numpy.polynomial.polynomial as npp

In [2]: p1 = npp.Polynomial([1,2])

In [3]: p2 = npp.Polynomial([3,4])

In [4]: npp.polydiv(p1, p2)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-00c25f56fb20> in <module>()
----> 1 npp.polydiv(p1, p2)

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in polydiv(c1, c2)
406     len2 = len(c2)
407     if len2 == 1 :
--> 408         return c1/c2[-1], c1[:1]*0
409     elif len1 < len2 :
410         return c1[:1]*0, c1

/Users/warren/anaconda/lib/python2.7/site-packages/numpy/polynomial/polynomial.pyc in __rtruediv__(self, other)

UnboundLocalError: local variable 'quo' referenced before assignment

# Fixed code
def __eq__(self, other):
    res = (
        isinstance(other, self.__class__)
        and np.all(self.domain == other.domain)
        and np.all(self.window == other.window)
        and np.all(self.coef == other.coef)
    )
    return res
# Buggy code
def __init__(self, pyfunc, otypes="", doc=None, excluded=None, cache=False):
    self.pyfunc = pyfunc
    self.cache = cache

    if doc is None:
        self.__doc__ = pyfunc.__doc__
    else:
        self.__doc__ = doc

    if isinstance(otypes, str):
        self.otypes = otypes
        for char in self.otypes:
            if char not in typecodes["All"]:
                raise ValueError("Invalid otype specified: %s" % (char,))
    elif iterable(otypes):
        self.otypes = "".join([_nx.dtype(x).char for x in otypes])
    else:
        raise ValueError("Invalid otype specification")

    # Excluded variable support
    if excluded is None:
        excluded = set()
    self.excluded = set(excluded)

    if self.otypes and not self.excluded:
        self._ufunc = None  # Caching to improve default performance


# Traceback (AttributeError)
v = numpy.vectorize( lambda x: x )
v.otypes='i'
v( [1,2] )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/numpy/lib/function_base.py", line 1873, in __call__
return self._vectorize_call(func=func, args=vargs)
File "/usr/lib64/python2.7/site-packages/numpy/lib/function_base.py", line 1933, in _vectorize_call
ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
File "/usr/lib64/python2.7/site-packages/numpy/lib/function_base.py", line 1886, in _get_ufunc_and_otypes
if func is self.pyfunc and self._ufunc is not None:
AttributeError: 'vectorize' object has no attribute '_ufunc'

# Fixed code
def __init__(self, pyfunc, otypes="", doc=None, excluded=None, cache=False):
    self.pyfunc = pyfunc
    self.cache = cache
    self._ufunc = None  # Caching to improve default performance

    if doc is None:
        self.__doc__ = pyfunc.__doc__
    else:
        self.__doc__ = doc

    if isinstance(otypes, str):
        self.otypes = otypes
        for char in self.otypes:
            if char not in typecodes["All"]:
                raise ValueError("Invalid otype specified: %s" % (char,))
    elif iterable(otypes):
        self.otypes = "".join([_nx.dtype(x).char for x in otypes])
    else:
        raise ValueError("Invalid otype specification")

    # Excluded variable support
    if excluded is None:
        excluded = set()
    self.excluded = set(excluded)
# Buggy code
def __init__(self, methodname):
    self.__name__ = methodname
    self.__doc__ = self.getdoc()


# Traceback (ValueError)
In [14]: arr = np.arange(8)

In [15]: arr.shape = 4,2

In [16]: cond = np.array([True, False, True, True])

In [17]: np.ma.compress(cond, arr, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/efiring/<ipython-input-17-50a13b754f15> in <module>()
----> 1 np.ma.compress(cond, arr, axis=0)

/usr/local/lib/python2.7/dist-packages/numpy/ma/core.pyc in __call__(self, a, *args, **params)
5931         method = getattr(a, method_name, None)
5932         if method is not None:
-> 5933             return method(*args, **params)
5934         # Still here ? Then a is not a MaskedArray

5935         method = getattr(MaskedArray, method_name, None)

ValueError: condition must be 1-d array

# Fixed code
def __init__(self, methodname, reversed=False):
    self.__name__ = methodname
    self.__doc__ = self.getdoc()
    self.reversed = reversed
# Buggy code
def __call__(self, a, *args, **params):
    # Get the method from the array (if possible)
    method_name = self.__name__
    method = getattr(a, method_name, None)
    if method is not None:
        return method(*args, **params)
    # Still here ? Then a is not a MaskedArray
    method = getattr(MaskedArray, method_name, None)
    if method is not None:
        return method(MaskedArray(a), *args, **params)
    # Still here ? OK, let's call the corresponding np function
    method = getattr(np, method_name)
    return method(a, *args, **params)


# Traceback (ValueError)
In [14]: arr = np.arange(8)

In [15]: arr.shape = 4,2

In [16]: cond = np.array([True, False, True, True])

In [17]: np.ma.compress(cond, arr, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/efiring/<ipython-input-17-50a13b754f15> in <module>()
----> 1 np.ma.compress(cond, arr, axis=0)

/usr/local/lib/python2.7/dist-packages/numpy/ma/core.pyc in __call__(self, a, *args, **params)
5931         method = getattr(a, method_name, None)
5932         if method is not None:
-> 5933             return method(*args, **params)
5934         # Still here ? Then a is not a MaskedArray

5935         method = getattr(MaskedArray, method_name, None)

ValueError: condition must be 1-d array

# Fixed code
def __call__(self, a, *args, **params):
    if self.reversed:
        args = list(args)
        arr = args[0]
        args[0] = a
        a = arr
    # Get the method from the array (if possible)
    method_name = self.__name__
    method = getattr(a, method_name, None)
    if method is not None:
        return method(*args, **params)
    # Still here ? Then a is not a MaskedArray
    method = getattr(MaskedArray, method_name, None)
    if method is not None:
        return method(MaskedArray(a), *args, **params)
    # Still here ? OK, let's call the corresponding np function
    method = getattr(np, method_name)
    return method(a, *args, **params)
# Buggy code
def CCompiler_spawn(self, cmd, display=None):
    """
    Execute a command in a sub-process.

    Parameters
    ----------
    cmd : str
        The command to execute.
    display : str or sequence of str, optional
        The text to add to the log file kept by `numpy.distutils`.
        If not given, `display` is equal to `cmd`.

    Returns
    -------
    None

    Raises
    ------
    DistutilsExecError
        If the command failed, i.e. the exit status was not 0.

    """
    if display is None:
        display = cmd
        if is_sequence(display):
            display = " ".join(list(display))
    log.info(display)
    s, o = exec_command(cmd)
    if s:
        if is_sequence(cmd):
            cmd = " ".join(list(cmd))
        print(o)
        if re.search("Too many open files", o):
            msg = "\nTry rerunning setup command until build succeeds."
        else:
            msg = ""
        raise DistutilsExecError(
            'Command "%s" failed with exit status %d%s' % (cmd, s, msg)
        )


# Traceback (AssertionError)
x = np.array([-1j], '<c8')
>>> x.tostring().encode('hex')
'00000000000080bf'
# This is a little-endian representation, in the order (real, imag)

# When I swap the whole array, it swaps each of the (real, imag) parts
separately
>>> y = x.byteswap()
>>> y.tostring().encode('hex')
'00000000bf800000'
# and this round-trips fine
>>> z = np.fromstring(y.tostring(), dtype='>c8')
>>> assert z[0] == -1j
>>>

# When I swap the scalar, it seems to swap the entire 8 bytes
>>> y = x[0].byteswap()
>>> y.tostring().encode('hex')
'bf80000000000000'
# ...and this doesn't round-trip
>>> z = np.fromstring(y.tostring(), dtype='>c8')
>>> assert z[0] == -1j
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>>

# Fixed code
def CCompiler_spawn(self, cmd, display=None):
    """
    Execute a command in a sub-process.

    Parameters
    ----------
    cmd : str
        The command to execute.
    display : str or sequence of str, optional
        The text to add to the log file kept by `numpy.distutils`.
        If not given, `display` is equal to `cmd`.

    Returns
    -------
    None

    Raises
    ------
    DistutilsExecError
        If the command failed, i.e. the exit status was not 0.

    """
    if display is None:
        display = cmd
        if is_sequence(display):
            display = " ".join(list(display))
    log.info(display)
    s, o = exec_command(cmd)
    if s:
        if is_sequence(cmd):
            cmd = " ".join(list(cmd))
        try:
            print(o)
        except UnicodeError:
            # When installing through pip, `o` can contain non-ascii chars
            pass
        if re.search("Too many open files", o):
            msg = "\nTry rerunning setup command until build succeeds."
        else:
            msg = ""
        raise DistutilsExecError(
            'Command "%s" failed with exit status %d%s' % (cmd, s, msg)
        )
# Buggy code
def _raise_error():
    """
    Raises errors for inotify failures.
    """
    err = ctypes.get_errno()
    if err == errno.ENOSPC:
        raise OSError(errno.ENOSPC, "inotify watch limit reached")
    elif err == errno.EMFILE:
        raise OSError(errno.EMFILE, "inotify instance limit reached")
    else:
        raise OSError(err, os.strerror(err))


# Traceback (PermissionError)
$ watchmedo log --recursive /path
Traceback (most recent call last):
File ".local/bin/watchmedo", line 11, in <module>
sys.exit(main())
File "/home/user/.local/lib/python3.6/site-packages/watchdog/watchmedo.py", line 576, in main
parser.dispatch()
File "/home/user/.local/lib/python3.6/site-packages/argh/helpers.py", line 55, in dispatch
return dispatch(self, *args, **kwargs)
File "/home/user/.local/lib/python3.6/site-packages/argh/dispatching.py", line 174, in dispatch
for line in lines:
File "/home/user/.local/lib/python3.6/site-packages/argh/dispatching.py", line 277, in _execute_command
for line in result:
File "/home/user/.local/lib/python3.6/site-packages/argh/dispatching.py", line 231, in _call
result = function(namespace_obj)
File "/home/user/.local/lib/python3.6/site-packages/watchdog/watchmedo.py", line 350, in log
observe_with(observer, handler, args.directories, args.recursive)
File "/home/user/.local/lib/python3.6/site-packages/watchdog/watchmedo.py", line 116, in observe_with
observer.start()
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/api.py", line 253, in start
emitter.start()
File "/home/user/.local/lib/python3.6/site-packages/watchdog/utils/__init__.py", line 110, in start
self.on_thread_start()
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/inotify.py", line 121, in on_thread_start
self._inotify = InotifyBuffer(path, self.watch.is_recursive)
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/inotify_buffer.py", line 35, in __init__
self._inotify = Inotify(path, recursive)
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/inotify_c.py", line 200, in __init__
self._add_dir_watch(path, recursive, event_mask)
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/inotify_c.py", line 395, in _add_dir_watch
self._add_watch(full_path, mask)
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/inotify_c.py", line 409, in _add_watch
Inotify._raise_error()
File "/home/user/.local/lib/python3.6/site-packages/watchdog/observers/inotify_c.py", line 425, in _raise_error
raise OSError(err, os.strerror(err))
PermissionError: [Errno 13] Permission denied

# Fixed code
def _raise_error():
    """
    Raises errors for inotify failures.
    """
    err = ctypes.get_errno()
    if err == errno.ENOSPC:
        raise OSError(errno.ENOSPC, "inotify watch limit reached")
    elif err == errno.EMFILE:
        raise OSError(errno.EMFILE, "inotify instance limit reached")
    elif err == errno.EACCES:
        # Prevent raising an exception when a file with no permissions
        # changes
        pass
    else:
        raise OSError(err, os.strerror(err))
# Buggy code
def _encode_host(cls, host):
    try:
        ip, sep, zone = host.partition("%")
        ip = ip_address(ip)
    except ValueError:
        try:
            host = idna.encode(host, uts46=True).decode("ascii")
        except UnicodeError:
            host = host.encode("idna").decode("ascii")
    else:
        host = ip.compressed
        if sep:
            host += "%" + zone
        if ip.version == 6:
            host = "[" + host + "]"
    return host


# Traceback (ValueError)
Python 3.6.5 (default, May 24 2018, 08:58:10)
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
from yarl import URL
url = URL('https://www.python.org/~guido?arg=1#frag')
Traceback (most recent call last):
File "/tmp/foo/yarl/yarl/lib/python3.6/site-packages/yarl/__init__.py", line 667, in _encode_host
ip = ip_address(ip)
File "/home/mruf/local/opt/pyenv/versions/3.6.5/lib/python3.6/ipaddress.py", line 54, in ip_address
address)
ValueError: 'www.python.org' does not appear to be an IPv4 or IPv6 address

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/foo/yarl/yarl/lib/python3.6/site-packages/yarl/__init__.py", line 170, in __new__
val.username, val.password, host, port, encode=True
File "/tmp/foo/yarl/yarl/lib/python3.6/site-packages/yarl/__init__.py", line 688, in _make_netloc
ret = cls._encode_host(host)
File "/tmp/foo/yarl/yarl/lib/python3.6/site-packages/yarl/__init__.py", line 671, in _encode_host
if host.isascii():
AttributeError: 'str' object has no attribute 'isascii'


# Fixed code
def _encode_host(cls, host):
    try:
        ip, sep, zone = host.partition("%")
        ip = ip_address(ip)
    except ValueError:
        for char in host:
            if char > "\x7f":
                break
        else:
            return host
        try:
            host = idna.encode(host, uts46=True).decode("ascii")
        except UnicodeError:
            host = host.encode("idna").decode("ascii")
    else:
        host = ip.compressed
        if sep:
            host += "%" + zone
        if ip.version == 6:
            host = "[" + host + "]"
    return host
# Buggy code
def custom_format(slither, result):
    elements = result["elements"]
    for element in elements:
        if element["type"] != "function":
            # Skip variable elements
            continue
        target_contract = slither.get_contract_from_name(
            element["type_specific_fields"]["parent"]["name"]
        )
        if target_contract:
            function = target_contract.get_function_from_signature(
                element["type_specific_fields"]["signature"]
            )
            if function:
                _patch(
                    slither,
                    result,
                    element["source_mapping"]["filename_absolute"],
                    int(
                        function.parameters_src.source_mapping["start"]
                        + function.parameters_src.source_mapping["length"]
                    ),
                    int(function.returns_src.source_mapping["start"]),
                )


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/nataliechin/.virtualenvs/slither-dev/bin/slither-flat", line 33, in <module>
sys.exit(load_entry_point('slither-analyzer', 'console_scripts', 'slither-flat')())
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/__main__.py", line 100, in main
flat = Flattening(
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 67, in __init__
self._get_source_code(contract)
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 103, in _get_source_code
f.parameters_src.source_mapping["start"]
AttributeError: 'FunctionContract' object has no attribute 'parameters_src'

# Fixed code
def custom_format(slither, result):
    elements = result["elements"]
    for element in elements:
        if element["type"] != "function":
            # Skip variable elements
            continue
        target_contract = slither.get_contract_from_name(
            element["type_specific_fields"]["parent"]["name"]
        )
        if target_contract:
            function = target_contract.get_function_from_signature(
                element["type_specific_fields"]["signature"]
            )
            if function:
                _patch(
                    slither,
                    result,
                    element["source_mapping"]["filename_absolute"],
                    int(
                        function.parameters_src().source_mapping["start"]
                        + function.parameters_src().source_mapping["length"]
                    ),
                    int(function.returns_src().source_mapping["start"]),
                )
# Buggy code
def custom_format(slither, result):
    elements = result["elements"]
    for element in elements:
        target_contract = slither.get_contract_from_name(
            element["type_specific_fields"]["parent"]["name"]
        )
        if target_contract:
            function = target_contract.get_function_from_signature(
                element["type_specific_fields"]["signature"]
            )
            if function:
                _patch(
                    slither,
                    result,
                    element["source_mapping"]["filename_absolute"],
                    int(function.parameters_src.source_mapping["start"]),
                    int(function.returns_src.source_mapping["start"]),
                )


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/nataliechin/.virtualenvs/slither-dev/bin/slither-flat", line 33, in <module>
sys.exit(load_entry_point('slither-analyzer', 'console_scripts', 'slither-flat')())
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/__main__.py", line 100, in main
flat = Flattening(
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 67, in __init__
self._get_source_code(contract)
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 103, in _get_source_code
f.parameters_src.source_mapping["start"]
AttributeError: 'FunctionContract' object has no attribute 'parameters_src'

# Fixed code
def custom_format(slither, result):
    elements = result["elements"]
    for element in elements:
        target_contract = slither.get_contract_from_name(
            element["type_specific_fields"]["parent"]["name"]
        )
        if target_contract:
            function = target_contract.get_function_from_signature(
                element["type_specific_fields"]["signature"]
            )
            if function:
                _patch(
                    slither,
                    result,
                    element["source_mapping"]["filename_absolute"],
                    int(function.parameters_src().source_mapping["start"]),
                    int(function.returns_src().source_mapping["start"]),
                )
# Buggy code
def _parse_params(self, params: Dict):
    assert params[self.get_key()] == "ParameterList"

    self.parameters_src.set_offset(params["src"], self._function.slither)

    if self.is_compact_ast:
        params = params["parameters"]
    else:
        params = params[self.get_children("children")]

    for param in params:
        assert param[self.get_key()] == "VariableDeclaration"
        local_var = self._add_param(param)
        self._function.add_parameters(local_var.underlying_variable)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/nataliechin/.virtualenvs/slither-dev/bin/slither-flat", line 33, in <module>
sys.exit(load_entry_point('slither-analyzer', 'console_scripts', 'slither-flat')())
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/__main__.py", line 100, in main
flat = Flattening(
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 67, in __init__
self._get_source_code(contract)
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 103, in _get_source_code
f.parameters_src.source_mapping["start"]
AttributeError: 'FunctionContract' object has no attribute 'parameters_src'

# Fixed code
def _parse_params(self, params: Dict):
    assert params[self.get_key()] == "ParameterList"

    self._function.parameters_src().set_offset(params["src"], self._function.slither)

    if self.is_compact_ast:
        params = params["parameters"]
    else:
        params = params[self.get_children("children")]

    for param in params:
        assert param[self.get_key()] == "VariableDeclaration"
        local_var = self._add_param(param)
        self._function.add_parameters(local_var.underlying_variable)
# Buggy code
def _parse_returns(self, returns: Dict):
    assert returns[self.get_key()] == "ParameterList"

    self.returns_src.set_offset(returns["src"], self._function.slither)

    if self.is_compact_ast:
        returns = returns["parameters"]
    else:
        returns = returns[self.get_children("children")]

    for ret in returns:
        assert ret[self.get_key()] == "VariableDeclaration"
        local_var = self._add_param(ret)
        self._function.add_return(local_var.underlying_variable)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/nataliechin/.virtualenvs/slither-dev/bin/slither-flat", line 33, in <module>
sys.exit(load_entry_point('slither-analyzer', 'console_scripts', 'slither-flat')())
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/__main__.py", line 100, in main
flat = Flattening(
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 67, in __init__
self._get_source_code(contract)
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 103, in _get_source_code
f.parameters_src.source_mapping["start"]
AttributeError: 'FunctionContract' object has no attribute 'parameters_src'

# Fixed code
def _parse_returns(self, returns: Dict):
    assert returns[self.get_key()] == "ParameterList"

    self._function.returns_src().set_offset(returns["src"], self._function.slither)

    if self.is_compact_ast:
        returns = returns["parameters"]
    else:
        returns = returns[self.get_children("children")]

    for ret in returns:
        assert ret[self.get_key()] == "VariableDeclaration"
        local_var = self._add_param(ret)
        self._function.add_return(local_var.underlying_variable)
# Buggy code
def _export_from_type(self, t, contract, exported, list_contract):
    if isinstance(t, UserDefinedType):
        if isinstance(t.type, (Enum, Structure)):
            if t.type.contract != contract and t.type.contract not in exported:
                self._export_list_used_contracts(
                    t.type.contract, exported, list_contract
                )
        else:
            assert isinstance(t.type, Contract)
            if t.type != contract and t.type not in exported:
                self._export_list_used_contracts(t.type, exported, list_contract)
    elif isinstance(t, MappingType):
        self._export_from_type(t.type_from, contract, exported, list_contract)
        self._export_from_type(t.type_to, contract, exported, list_contract)
    elif isinstance(t, ArrayType):
        self._export_from_type(t.type, contract, exported, list_contract)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/nataliechin/.virtualenvs/slither-dev/bin/slither-flat", line 33, in <module>
sys.exit(load_entry_point('slither-analyzer', 'console_scripts', 'slither-flat')())
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/__main__.py", line 100, in main
flat = Flattening(
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 67, in __init__
self._get_source_code(contract)
File "/Users/nataliechin/GitHub/slither/slither/tools/flattening/flattening.py", line 103, in _get_source_code
f.parameters_src.source_mapping["start"]
AttributeError: 'FunctionContract' object has no attribute 'parameters_src'

# Fixed code
def _export_from_type(self, t, contract, exported, list_contract):
    if isinstance(t, UserDefinedType):
        if isinstance(t.type, (EnumContract, StructureContract)):
            if t.type.contract != contract and t.type.contract not in exported:
                self._export_list_used_contracts(
                    t.type.contract, exported, list_contract
                )
        else:
            assert isinstance(t.type, Contract)
            if t.type != contract and t.type not in exported:
                self._export_list_used_contracts(t.type, exported, list_contract)
    elif isinstance(t, MappingType):
        self._export_from_type(t.type_from, contract, exported, list_contract)
        self._export_from_type(t.type_to, contract, exported, list_contract)
    elif isinstance(t, ArrayType):
        self._export_from_type(t.type, contract, exported, list_contract)
# Buggy code
def __init__(self, values):
    # Note: Can return None
    # ex: return call()
    # where call() dont return
    if not isinstance(values, list):
        assert (
            is_valid_rvalue(values)
            or isinstance(values, TupleVariable)
            or values is None
        )
        if values is None:
            values = []
        else:
            values = [values]
    else:
        # Remove None
        # Prior Solidity 0.5
        # return (0,)
        # was valid for returns(uint)
        values = [v for v in values if not v is None]
        self._valid_value(values)
    super(Return, self).__init__()
    self._values = values


# Traceback (AssertionError)
ERROR:root:Error in .\function_returning_function.sol
ERROR:root:Traceback (most recent call last):
File "c:\users\x\documents\github\slither\slither\__main__.py", line 610, in main_impl
(slither_instances, results_detectors, results_printers, number_contracts) = process_all(filename, args,
File "c:\users\x\documents\github\slither\slither\__main__.py", line 67, in process_all
(slither, current_results_detectors, current_results_printers, current_analyzed_count) = process_single(
File "c:\users\x\documents\github\slither\slither\__main__.py", line 53, in process_single
slither = Slither(target,
File "c:\users\x\documents\github\slither\slither\slither.py", line 86, in __init__
self._parser.analyze_contracts()
File "c:\users\x\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 345, in analyze_contracts
self._convert_to_slithir()
File "c:\users\x\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 489, in _convert_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\x\documents\github\slither\slither\core\declarations\function.py", line 1652, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\x\documents\github\slither\slither\core\cfg\node.py", line 702, in slithir_generation
self._irs = convert_expression(expression, self)
File "c:\users\x\documents\github\slither\slither\slithir\convert.py", line 64, in convert_expression
visitor = ExpressionToSlithIR(expression, node)
File "c:\users\x\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 105, in __init__
r = Return(get(self.expression))
File "c:\users\x\documents\github\slither\slither\slithir\operations\return_operation.py", line 18, in __init__
assert is_valid_rvalue(values) or isinstance(values, TupleVariable) or values is None
AssertionError

# Fixed code
def __init__(self, values):
    # Note: Can return None
    # ex: return call()
    # where call() dont return
    if not isinstance(values, list):
        assert (
            is_valid_rvalue(values)
            or isinstance(values, (TupleVariable, Function))
            or values is None
        )
        if values is None:
            values = []
        else:
            values = [values]
    else:
        # Remove None
        # Prior Solidity 0.5
        # return (0,)
        # was valid for returns(uint)
        values = [v for v in values if not v is None]
        self._valid_value(values)
    super(Return, self).__init__()
    self._values = values
# Buggy code
def _valid_value(self, value):
    if isinstance(value, list):
        assert all(self._valid_value(v) for v in value)
    else:
        assert is_valid_rvalue(value) or isinstance(value, TupleVariable)
    return True


# Traceback (AssertionError)
ERROR:root:Error in .\function_returning_function.sol
ERROR:root:Traceback (most recent call last):
File "c:\users\x\documents\github\slither\slither\__main__.py", line 610, in main_impl
(slither_instances, results_detectors, results_printers, number_contracts) = process_all(filename, args,
File "c:\users\x\documents\github\slither\slither\__main__.py", line 67, in process_all
(slither, current_results_detectors, current_results_printers, current_analyzed_count) = process_single(
File "c:\users\x\documents\github\slither\slither\__main__.py", line 53, in process_single
slither = Slither(target,
File "c:\users\x\documents\github\slither\slither\slither.py", line 86, in __init__
self._parser.analyze_contracts()
File "c:\users\x\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 345, in analyze_contracts
self._convert_to_slithir()
File "c:\users\x\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 489, in _convert_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\x\documents\github\slither\slither\core\declarations\function.py", line 1652, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\x\documents\github\slither\slither\core\cfg\node.py", line 702, in slithir_generation
self._irs = convert_expression(expression, self)
File "c:\users\x\documents\github\slither\slither\slithir\convert.py", line 64, in convert_expression
visitor = ExpressionToSlithIR(expression, node)
File "c:\users\x\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 105, in __init__
r = Return(get(self.expression))
File "c:\users\x\documents\github\slither\slither\slithir\operations\return_operation.py", line 18, in __init__
assert is_valid_rvalue(values) or isinstance(values, TupleVariable) or values is None
AssertionError

# Fixed code
def _valid_value(self, value):
    if isinstance(value, list):
        assert all(self._valid_value(v) for v in value)
    else:
        assert is_valid_rvalue(value) or isinstance(value, (TupleVariable, Function))
    return True
# Buggy code
def __init__(self, called, arguments, type_call):
    assert isinstance(called, Expression)
    super(CallExpression, self).__init__()
    self._called = called
    self._arguments = arguments
    self._type_call = type_call
    # gas and value are only available if the syntax is {gas: , value: }
    # For the .gas().value(), the member are considered as function call
    # And converted later to the correct info (convert.py)
    self._gas = None
    self._value = None


# Traceback (AssertionError)
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError

# Fixed code
def __init__(self, called, arguments, type_call):
    assert isinstance(called, Expression)
    super(CallExpression, self).__init__()
    self._called = called
    self._arguments = arguments
    self._type_call = type_call
    # gas and value are only available if the syntax is {gas: , value: }
    # For the .gas().value(), the member are considered as function call
    # And converted later to the correct info (convert.py)
    self._gas = None
    self._value = None
    self._salt = None