gurudesh/pytracebugs huggingface dataset:
# Buggy code
def setSysKB(self, button):
    if self.ostype == "XFCE":
        Popen(["xfce4-keyboard-settings"])
    else:
        Popen(["gnome-control-center", "keyboard"])


# Traceback (NameError)
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 623, in setConfig
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 635, in setService
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 694, in setSysKB
Popen(['gnome-control-center','keyboard'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 700, in setRegion
Popen(['gnome-control-center','region'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'

# Fixed code
def setSysKB(self, button):
    if self.ostype == "XFCE":
        Popen(["xfce4-keyboard-settings"])
    elif self.ostype == "KDE":
        self.queryConfig(
            "systemsettings >/dev/null 2>&1 || systemsettings5 >/dev/null 2>&1"
        )
    else:
        Popen(["gnome-control-center", "keyboard"])
# Buggy code
def setRegion(self, button):
    if self.ostype == "XFCE":
        Popen(["gnome-language-selector"])
    else:
        Popen(["gnome-control-center", "region"])


# Traceback (NameError)
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 623, in setConfig
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 635, in setService
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 694, in setSysKB
Popen(['gnome-control-center','keyboard'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 700, in setRegion
Popen(['gnome-control-center','region'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'

# Fixed code
def setRegion(self, button):
    if self.ostype == "XFCE":
        Popen(["gnome-language-selector"])
    elif self.ostype == "KDE":
        self.queryConfig(
            "kcmshell4 kcm_translations >/dev/null 2>&1 || kcmshell5 kcm_translations >/dev/null 2>&1"
        )
    else:
        Popen(["gnome-control-center", "region"])
# Buggy code
def setConfig(self, button):
    try:
        if os.path.exists("/opt/sublime_text/sublime_text"):
            Popen(
                [
                    "/opt/sublime_text/sublime_text",
                    os.environ["HOME"] + "/.config/kinto/kinto.py",
                ]
            )
        elif which(gedit) is not None:
            Popen(["gedit", os.environ["HOME"] + "/.config/kinto/kinto.py"])
        elif which(mousepad) is not None:
            Popen(["mousepad", os.environ["HOME"] + "/.config/kinto/kinto.py"])

    except CalledProcessError:  # Notify user about error on running restart commands.
        Popen(["notify-send", "Kinto: Error could not open config file!"])


# Traceback (NameError)
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 623, in setConfig
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 635, in setService
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 694, in setSysKB
Popen(['gnome-control-center','keyboard'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 700, in setRegion
Popen(['gnome-control-center','region'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'

# Fixed code
def setConfig(self, button):
    try:
        if os.path.exists("/opt/sublime_text/sublime_text"):
            Popen(
                [
                    "/opt/sublime_text/sublime_text",
                    os.environ["HOME"] + "/.config/kinto/kinto.py",
                ]
            )
        elif which("gedit") is not None:
            Popen(["gedit", os.environ["HOME"] + "/.config/kinto/kinto.py"])
        elif which("mousepad") is not None:
            Popen(["mousepad", os.environ["HOME"] + "/.config/kinto/kinto.py"])
        elif which("kate") is not None:
            Popen(["kate", os.environ["HOME"] + "/.config/kinto/kinto.py"])
        elif which("kwrite") is not None:
            Popen(["kwrite", os.environ["HOME"] + "/.config/kinto/kinto.py"])

    except CalledProcessError:  # Notify user about error on running restart commands.
        Popen(["notify-send", "Kinto: Error could not open config file!"])
# Buggy code
def setService(self, button):
    try:
        if os.path.exists("/opt/sublime_text/sublime_text"):
            Popen(
                [
                    "/opt/sublime_text/sublime_text",
                    "/lib/systemd/system/xkeysnail.service",
                ]
            )
        elif which(gedit) is not None:
            Popen(["gedit", "/lib/systemd/system/xkeysnail.service"])
        elif which(mousepad) is not None:
            Popen(["mousepad", "/lib/systemd/system/xkeysnail.service"])

    except CalledProcessError:  # Notify user about error on running restart commands.
        Popen(["notify-send", "Kinto: Error could not open config file!"])


# Traceback (NameError)
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 623, in setConfig
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 635, in setService
elif which(gedit) is not None:
NameError: name 'gedit' is not defined
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 694, in setSysKB
Popen(['gnome-control-center','keyboard'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'
Traceback (most recent call last):
File "/home/nemokden/.config/kinto/kintotray.py", line 700, in setRegion
Popen(['gnome-control-center','region'])
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] 그런 파일이나 디렉터리가 없습니다: 'gnome-control-center'

# Fixed code
def setService(self, button):
    try:
        if os.path.exists("/opt/sublime_text/sublime_text"):
            Popen(
                [
                    "/opt/sublime_text/sublime_text",
                    "/lib/systemd/system/xkeysnail.service",
                ]
            )
        elif which("gedit") is not None:
            Popen(["gedit", "/lib/systemd/system/xkeysnail.service"])
        elif which("mousepad") is not None:
            Popen(["mousepad", "/lib/systemd/system/xkeysnail.service"])
        elif which("kate") is not None:
            Popen(["kate", "/lib/systemd/system/xkeysnail.service"])
        elif which("kwrite") is not None:
            Popen(["kwrite", "/lib/systemd/system/xkeysnail.service"])

    except CalledProcessError:  # Notify user about error on running restart commands.
        Popen(["notify-send", "Kinto: Error could not open config file!"])
# Buggy code
def create_archive(root, files=None, fileobj=None, gzip=False):
    if not fileobj:
        fileobj = tempfile.NamedTemporaryFile()
    t = tarfile.open(mode="w:gz" if gzip else "w", fileobj=fileobj)
    if files is None:
        files = build_file_list(root)
    for path in files:
        full_path = os.path.join(root, path)
        if not os.access(full_path, os.R_OK):
            raise IOError("Can not access file in context: {}".format(full_path))
        i = t.gettarinfo(full_path, arcname=path)
        if i is None:
            # This happens when we encounter a socket file. We can safely
            # ignore it and proceed.
            continue

        if constants.IS_WINDOWS_PLATFORM:
            # Windows doesn't keep track of the execute bit, so we make files
            # and directories executable by default.
            i.mode = i.mode & 0o755 | 0o111

        if i.isfile():
            try:
                with open(full_path, "rb") as f:
                    t.addfile(i, f)
            except IOError:
                t.addfile(i, None)
        else:
            # Directories, FIFOs, symlinks... don't need to be read.
            t.addfile(i, None)
    t.close()
    fileobj.seek(0)
    return fileobj


# Traceback (IOError)
$ python
Python 2.7.6 (default, Nov 23 2017, 15:49:48)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import docker
docker.__version__
'2.7.0'
docker.utils.create_archive(".", ['doesnt_exist'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/docker/utils/utils.py", line 103, in create_archive
'Can not access file in context: {}'.format(full_path)
IOError: Can not access file in context: ./doesnt_exist


# Fixed code
def create_archive(root, files=None, fileobj=None, gzip=False):
    if not fileobj:
        fileobj = tempfile.NamedTemporaryFile()
    t = tarfile.open(mode="w:gz" if gzip else "w", fileobj=fileobj)
    if files is None:
        files = build_file_list(root)
    for path in files:
        full_path = os.path.join(root, path)

        if os.lstat(full_path).st_mode & os.R_OK == 0:
            raise IOError("Can not access file in context: {}".format(full_path))
        i = t.gettarinfo(full_path, arcname=path)
        if i is None:
            # This happens when we encounter a socket file. We can safely
            # ignore it and proceed.
            continue

        if constants.IS_WINDOWS_PLATFORM:
            # Windows doesn't keep track of the execute bit, so we make files
            # and directories executable by default.
            i.mode = i.mode & 0o755 | 0o111

        if i.isfile():
            try:
                with open(full_path, "rb") as f:
                    t.addfile(i, f)
            except IOError:
                t.addfile(i, None)
        else:
            # Directories, FIFOs, symlinks... don't need to be read.
            t.addfile(i, None)
    t.close()
    fileobj.seek(0)
    return fileobj
# Buggy code
def update_headers(f):
    def inner(self, *args, **kwargs):
        if "HttpHeaders" in self._auth_configs:
            if "headers" not in kwargs:
                kwargs["headers"] = self._auth_configs["HttpHeaders"]
            else:
                kwargs["headers"].update(self._auth_configs["HttpHeaders"])
        return f(self, *args, **kwargs)

    return inner


# Traceback (AttributeError)
import docker

c = docker.Client()
c.build('https://github.com/docker/compose.git')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-d78c607c9627> in <module>()
----> 1 c.build('https://github.com/docker/compose.git')

/home/joffrey/.envs/pydocker/local/lib/python2.7/site-packages/docker/api/build.pyc in build(self, path, tag, quiet, fileobj, nocache, rm, stream, timeout, custom_context, encoding, pull, forcerm, dockerfile, container_limits, decode, buildargs, gzip)
102             headers=headers,
103             stream=stream,
--> 104             timeout=timeout,
105         )
106

/home/joffrey/.envs/pydocker/local/lib/python2.7/site-packages/docker/utils/decorators.pyc in inner(self, *args, **kwargs)
44                 kwargs['headers'] = self._auth_configs['HttpHeaders']
45             else:
---> 46                 kwargs['headers'].update(self._auth_configs['HttpHeaders'])
47         return f(self, *args, **kwargs)
48     return inner

AttributeError: 'NoneType' object has no attribute 'update'

# Fixed code
def update_headers(f):
    def inner(self, *args, **kwargs):
        if "HttpHeaders" in self._auth_configs:
            if not kwargs.get("headers"):
                kwargs["headers"] = self._auth_configs["HttpHeaders"]
            else:
                kwargs["headers"].update(self._auth_configs["HttpHeaders"])
        return f(self, *args, **kwargs)

    return inner
# Buggy code
def inner(self, *args, **kwargs):
    if "HttpHeaders" in self._auth_configs:
        if "headers" not in kwargs:
            kwargs["headers"] = self._auth_configs["HttpHeaders"]
        else:
            kwargs["headers"].update(self._auth_configs["HttpHeaders"])
    return f(self, *args, **kwargs)


# Traceback (AttributeError)
import docker

c = docker.Client()
c.build('https://github.com/docker/compose.git')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-d78c607c9627> in <module>()
----> 1 c.build('https://github.com/docker/compose.git')

/home/joffrey/.envs/pydocker/local/lib/python2.7/site-packages/docker/api/build.pyc in build(self, path, tag, quiet, fileobj, nocache, rm, stream, timeout, custom_context, encoding, pull, forcerm, dockerfile, container_limits, decode, buildargs, gzip)
102             headers=headers,
103             stream=stream,
--> 104             timeout=timeout,
105         )
106

/home/joffrey/.envs/pydocker/local/lib/python2.7/site-packages/docker/utils/decorators.pyc in inner(self, *args, **kwargs)
44                 kwargs['headers'] = self._auth_configs['HttpHeaders']
45             else:
---> 46                 kwargs['headers'].update(self._auth_configs['HttpHeaders'])
47         return f(self, *args, **kwargs)
48     return inner

AttributeError: 'NoneType' object has no attribute 'update'

# Fixed code
def inner(self, *args, **kwargs):
    if "HttpHeaders" in self._auth_configs:
        if not kwargs.get("headers"):
            kwargs["headers"] = self._auth_configs["HttpHeaders"]
        else:
            kwargs["headers"].update(self._auth_configs["HttpHeaders"])
    return f(self, *args, **kwargs)
# Buggy code
def _stream_helper(self, response):
    """Generator for data coming from a chunked-encoded HTTP response."""
    reader = response.raw
    assert reader._fp.chunked
    while not reader.closed:
        # this read call will block until we get a chunk
        data = reader.read(1)
        if not data:
            break
        if reader._fp.chunk_left:
            data += reader.read(reader._fp.chunk_left)
        yield data


# Traceback (AssertionError)
Traceback (most recent call last):
File "/Users/omrib/git/docker/main.py", line 6, in <module>
print "\n".join(client.build(fileobj=BytesIO(), tag="a/b/c"))
File "/Users/omrib/git/docker/env/lib/python2.7/site-packages/docker/client.py", line 295, in _stream_helper
assert reader._fp.chunked
AssertionError

# Fixed code
def _stream_helper(self, response):
    """Generator for data coming from a chunked-encoded HTTP response."""
    if response.raw._fp.chunked:
        reader = response.raw
        while not reader.closed:
            # this read call will block until we get a chunk
            data = reader.read(1)
            if not data:
                break
            if reader._fp.chunk_left:
                data += reader.read(reader._fp.chunk_left)
            yield data
    else:
        # Response isn't chunked, meaning we probably
        # encountered an error immediately
        yield self._result(response)
# Buggy code
def _stream_helper(self, response):
    """Generator for data coming from a chunked-encoded HTTP response."""
    socket_fp = self._get_raw_response_socket(response)
    socket_fp.setblocking(1)
    socket = socket_fp.makefile()
    while True:
        # Because Docker introduced newlines at the end of chunks in v0.9,
        # and only on some API endpoints, we have to cater for both cases.
        size_line = socket.readline()
        if size_line == "\r\n":
            size_line = socket.readline()

        size = int(size_line, 16)
        if size <= 0:
            break
        data = socket.readline()
        if not data:
            break
        yield data


# Traceback (ValueError)
$ python build.py
{"stream":" ---\u003e b750fe79269d\n"}

Traceback (most recent call last):
File "build.py", line 8, in <module>
for line in client.build('.', tag='atag', rm=True):
File "/Users/adam/PYTHON3/lib/python3.4/site-packages/docker/client.py", line 233, in _stream_helper
size = int(size_line, 16)
ValueError: invalid literal for int() with base 16: '\n'```

# Fixed code
def _stream_helper(self, response):
    """Generator for data coming from a chunked-encoded HTTP response."""
    socket_fp = self._get_raw_response_socket(response)
    socket_fp.setblocking(1)
    socket = socket_fp.makefile()
    while True:
        # Because Docker introduced newlines at the end of chunks in v0.9,
        # and only on some API endpoints, we have to cater for both cases.
        size_line = socket.readline()
        if size_line == "\r\n" or size_line == "\n":
            size_line = socket.readline()

        size = int(size_line, 16)
        if size <= 0:
            break
        data = socket.readline()
        if not data:
            break
        yield data
# Buggy code
def _stream_helper(self, response):
    """Generator for data coming from a chunked-encoded HTTP response."""
    socket_fp = self._get_raw_response_socket(response)
    socket_fp.setblocking(1)
    socket = socket_fp.makefile()
    while True:
        size = int(socket.readline(), 16)
        if size <= 0:
            break
        data = socket.readline()
        if not data:
            break
        yield data


# Traceback (ValueError)
ubuntu@ip-10-77-1-34:/tmp/foo$ python test.py
{"stream":" ---\u003e Using cache\n"}

Traceback (most recent call last):
File "test.py", line 5, in <module>
for line in gen:
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 239, in _stream_helper
size = int(socket.readline(), 16)
ValueError: invalid literal for int() with base 16: ''

# Fixed code
def _stream_helper(self, response):
    """Generator for data coming from a chunked-encoded HTTP response."""
    for line in response.iter_lines(chunk_size=32):
        yield line
# Buggy code
def build(
    self,
    path=None,
    tag=None,
    quiet=False,
    fileobj=None,
    nocache=False,
    rm=False,
    stream=False,
    timeout=None,
):
    remote = context = headers = None
    if path is None and fileobj is None:
        raise Exception("Either path or fileobj needs to be provided.")

    if fileobj is not None:
        context = utils.mkbuildcontext(fileobj)
    elif path.startswith(("http://", "https://", "git://", "github.com/")):
        remote = path
    else:
        context = utils.tar(path)

    u = self._url("/build")
    params = {"t": tag, "remote": remote, "q": quiet, "nocache": nocache, "rm": rm}
    if context is not None:
        headers = {"Content-Type": "application/tar"}

    response = self._post(
        u,
        data=context,
        params=params,
        headers=headers,
        stream=stream,
        timeout=timeout,
    )

    if context is not None:
        context.close()

    if stream or utils.compare_version("1.8", self._version) >= 0:
        return self._stream_helper(response)
    else:
        output = self._result(response)
        srch = r"Successfully built ([0-9a-f]+)"
        match = re.search(srch, output)
        if not match:
            return None, output
        return match.group(1), output


# Traceback (ValueError)
ubuntu@ip-10-77-1-34:/tmp/foo$ python test.py
{"stream":" ---\u003e Using cache\n"}

Traceback (most recent call last):
File "test.py", line 5, in <module>
for line in gen:
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 239, in _stream_helper
size = int(socket.readline(), 16)
ValueError: invalid literal for int() with base 16: ''

# Fixed code
def build(
    self,
    path=None,
    tag=None,
    quiet=False,
    fileobj=None,
    nocache=False,
    rm=False,
    stream=False,
    timeout=None,
):
    remote = context = headers = None
    if path is None and fileobj is None:
        raise Exception("Either path or fileobj needs to be provided.")

    if fileobj is not None:
        context = utils.mkbuildcontext(fileobj)
    elif path.startswith(("http://", "https://", "git://", "github.com/")):
        remote = path
    else:
        context = utils.tar(path)

    if utils.compare_version("1.8", self._version) >= 0:
        stream = True

    u = self._url("/build")
    params = {"t": tag, "remote": remote, "q": quiet, "nocache": nocache, "rm": rm}
    if context is not None:
        headers = {"Content-Type": "application/tar"}

    response = self._post(
        u,
        data=context,
        params=params,
        headers=headers,
        stream=stream,
        timeout=timeout,
    )

    if context is not None:
        context.close()

    if stream:
        return self._stream_helper(response)
    else:
        output = self._result(response)
        srch = r"Successfully built ([0-9a-f]+)"
        match = re.search(srch, output)
        if not match:
            return None, output
        return match.group(1), output
# Buggy code
def py_operation_function(self, code):
    is_unicode_concat = False
    if isinstance(self.operand1, FormattedValueNode) or isinstance(
        self.operand2, FormattedValueNode
    ):
        is_unicode_concat = True
    else:
        type1, type2 = self.operand1.type, self.operand2.type
        if type1 is unicode_type or type2 is unicode_type:
            is_unicode_concat = type1.is_builtin_type and type2.is_builtin_type

    if is_unicode_concat:
        if self.operand1.may_be_none() or self.operand2.may_be_none():
            return "__Pyx_PyUnicode_ConcatSafe"
        else:
            return "__Pyx_PyUnicode_Concat"
    return super(AddNode, self).py_operation_function(code)


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "concat.py", line 11, in concat.appendinline
y += 'ab'
TypeError: must be str, not list

# Fixed code
def py_operation_function(self, code):
    type1, type2 = self.operand1.type, self.operand2.type

    if type1 is unicode_type or type2 is unicode_type:
        if type1 in (unicode_type, str_type) and type2 in (unicode_type, str_type):
            is_unicode_concat = True
        elif isinstance(self.operand1, FormattedValueNode) or isinstance(
            self.operand2, FormattedValueNode
        ):
            # Assume that even if we don't know the second type, it's going to be a string.
            is_unicode_concat = True
        else:
            # Operation depends on the second type.
            is_unicode_concat = False

        if is_unicode_concat:
            if self.operand1.may_be_none() or self.operand2.may_be_none():
                return "__Pyx_PyUnicode_ConcatSafe"
            else:
                return "__Pyx_PyUnicode_Concat"

    return super(AddNode, self).py_operation_function(code)
# Buggy code
def analyse_types(self, env):
    if self.doc:
        self.doc = self.doc.analyse_types(env)
        self.doc = self.doc.coerce_to_pyobject(env)
    self.type = py_object_type
    self.is_temp = 1
    return self


# Traceback (AttributeError)
Compiling testfile.py because it changed.
[1/1] Cythonizing testfile.py
Traceback (most recent call last):
File "setup.py", line 12, in <module>
distutils.core.setup(ext_modules=Cython.Build.cythonize(packpaths, nthreads=buildthreads, compiler_directives={'language_level': 3, 'profile': True}, annotate=True))
File ".../Cython/Build/Dependencies.py", line 1096, in cythonize
cythonize_one(*args)
File ".../Cython/Build/Dependencies.py", line 1202, in cythonize_one
result = compile_single(pyx_file, options, full_module_name=full_module_name)
File ".../Cython/Compiler/Main.py", line 727, in compile_single
return run_pipeline(source, options, full_module_name)
File ".../Cython/Compiler/Main.py", line 515, in run_pipeline
err, enddata = Pipeline.run_pipeline(pipeline, source)
File ".../Cython/Compiler/Pipeline.py", line 355, in run_pipeline
data = run(phase, data)
File ".../Cython/Compiler/Pipeline.py", line 335, in run
return phase(data)
File ".../Cython/Compiler/Pipeline.py", line 52, in generate_pyx_code_stage
module_node.process_implementation(options, result)
File ".../Cython/Compiler/ModuleNode.py", line 143, in process_implementation
self.generate_c_code(env, options, result)
File ".../Cython/Compiler/ModuleNode.py", line 385, in generate_c_code
self.body.generate_function_definitions(env, code)
File ".../Cython/Compiler/Nodes.py", line 442, in generate_function_definitions
stat.generate_function_definitions(env, code)
File ".../Cython/Compiler/Nodes.py", line 442, in generate_function_definitions
stat.generate_function_definitions(env, code)
File ".../Cython/Compiler/Nodes.py", line 3176, in generate_function_definitions
FuncDefNode.generate_function_definitions(self, env, code)
File ".../Cython/Compiler/Nodes.py", line 1983, in generate_function_definitions
self.generate_function_body(env, code)
File ".../Cython/Compiler/Nodes.py", line 1745, in generate_function_body
self.body.generate_execution_code(code)
File ".../Cython/Compiler/Nodes.py", line 448, in generate_execution_code
stat.generate_execution_code(code)
File ".../Cython/Compiler/Nodes.py", line 4601, in generate_execution_code
self.class_result.generate_evaluation_code(code)
File ".../Cython/Compiler/ExprNodes.py", line 773, in generate_evaluation_code
self.generate_result_code(code)
File ".../Cython/Compiler/ExprNodes.py", line 9034, in generate_result_code
self.bases.py_result(),
File ".../Cython/Compiler/ExprNodes.py", line 525, in py_result
return self.result_as(py_object_type)
File ".../Cython/Compiler/ExprNodes.py", line 516, in result_as
if (self.is_temp and self.type.is_pyobject and
AttributeError: 'NoneType' object has no attribute 'is_pyobject'

# Fixed code
def analyse_types(self, env):
    if self.doc:
        self.doc = self.doc.analyse_types(env).coerce_to_pyobject(env)
    self.type = py_object_type
    self.is_temp = 1
    return self
# Buggy code
def file_reporter(self, filename):
    # TODO: let coverage.py handle .py files itself
    # ext = os.path.splitext(filename)[1].lower()
    # if ext == '.py':
    #    from coverage.python import PythonFileReporter
    #    return PythonFileReporter(filename)

    filename = canonical_filename(os.path.abspath(filename))
    if self._c_files_map and filename in self._c_files_map:
        c_file, rel_file_path, code = self._c_files_map[filename]
    else:
        c_file, _ = self._find_source_files(filename)
        if not c_file:
            return None  # unknown file
        rel_file_path, code = self._parse_lines(c_file, filename)
    return CythonModuleReporter(c_file, filename, rel_file_path, code)


# Traceback (TypeError)
$ coveralls
...
Traceback (most recent call last):
File "/home/travis/miniconda/envs/dplenv/bin/coveralls", line 6, in <module>
sys.exit(coveralls.wear())
File "/home/travis/miniconda/envs/dplenv/lib/python3.5/site-packages/coveralls/__init__.py", line 94, in wear
source_files=coverage.coveralls(args.base_dir, ignore_errors=args.ignore_errors, merge_file=args.merge_file),
File "/home/travis/miniconda/envs/dplenv/lib/python3.5/site-packages/coveralls/control.py", line 9, in coveralls
return reporter.report(base_dir, ignore_errors=ignore_errors, merge_file=merge_file)
File "/home/travis/miniconda/envs/dplenv/lib/python3.5/site-packages/coveralls/report.py", line 20, in report
analysis = self.coverage._analyze(fr)
File "/home/travis/miniconda/envs/dplenv/lib/python3.5/site-packages/coverage/control.py", line 891, in _analyze
return Analysis(self.data, it)
File "/home/travis/miniconda/envs/dplenv/lib/python3.5/site-packages/coverage/results.py", line 19, in __init__
self.statements = self.file_reporter.lines()
File "/home/travis/miniconda/envs/dplenv/lib/python3.5/site-packages/Cython/Coverage.py", line 276, in lines
return set(self._code)
TypeError: 'NoneType' object is not iterable

# Fixed code
def file_reporter(self, filename):
    # TODO: let coverage.py handle .py files itself
    # ext = os.path.splitext(filename)[1].lower()
    # if ext == '.py':
    #    from coverage.python import PythonFileReporter
    #    return PythonFileReporter(filename)

    filename = canonical_filename(os.path.abspath(filename))
    if self._c_files_map and filename in self._c_files_map:
        c_file, rel_file_path, code = self._c_files_map[filename]
    else:
        c_file, _ = self._find_source_files(filename)
        if not c_file:
            return None  # unknown file
        rel_file_path, code = self._parse_lines(c_file, filename)
        if code is None:
            return None  # no source found
    return CythonModuleReporter(c_file, filename, rel_file_path, code)
# Buggy code
def _handle_simple_method_dict_pop(self, node, function, args, is_unbound_method):
    """Replace dict.pop() by a call to _PyDict_Pop()."""
    if len(args) == 2:
        args.append(ExprNodes.NullNode(node.pos))
    elif len(args) != 3:
        self._error_wrong_arg_count("dict.pop", node, args, "2 or 3")
        return node

    return self._substitute_method_call(
        node,
        function,
        "__Pyx_PyDict_Pop",
        self.PyDict_Pop_func_type,
        "pop",
        is_unbound_method,
        args,
        utility_code=load_c_utility("py_dict_pop"),
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "run_cython.py", line 2, in <module>
main()
File "cython_ext_type_none.pyx", line 12, in cython_ext_type_none.main
A = MyClass()  # This doesn't work
File "cython_ext_type_none.pyx", line 7, in cython_ext_type_none.MyClass.__init__
self.attr = kwargs.pop('attr', None)
TypeError: Cannot convert NoneType to cython_ext_type_none.MyClass

# Fixed code
def _handle_simple_method_dict_pop(self, node, function, args, is_unbound_method):
    """Replace dict.pop() by a call to _PyDict_Pop()."""
    if len(args) == 2:
        args.append(ExprNodes.NullNode(node.pos))
    elif len(args) != 3:
        self._error_wrong_arg_count("dict.pop", node, args, "2 or 3")
        return node

    return self._substitute_method_call(
        node,
        function,
        "__Pyx_PyDict_Pop",
        self.PyDict_Pop_func_type,
        "pop",
        is_unbound_method,
        args,
        may_return_none=True,
        utility_code=load_c_utility("py_dict_pop"),
    )
# Buggy code
def getfield(self, pkt, s):
    tmp_len = self.length_from(pkt)
    if tmp_len is None:
        return s, []
    return s[tmp_len:], self.m2i(pkt, s[:tmp_len])


# Traceback (TypeError)
Traceback (most recent call last):
File "utils/poc.py", line 51, in <module>
test_failed_fn()
File "utils/poc.py", line 47, in test_failed_fn
extract_tls_payloads(os.path.join(data_root, fn), 900)
File "utils/poc.py", line 19, in extract_tls_payloads
payload = bytes(p[TLS])
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/layers/tls/session.py", line 966, in __bytes__
built_packet = super(_GenericTLSSessionInheritance, self).__bytes__()
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/packet.py", line 492, in __bytes__
return self.build()
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/packet.py", line 612, in build
p = self.do_build()
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/packet.py", line 594, in do_build
pkt = self.self_build()
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/packet.py", line 575, in self_build
p = f.addfield(self, p, val)
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/layers/tls/record.py", line 207, in addfield
res += self.i2m(pkt, p)
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/layers/tls/record.py", line 194, in i2m
cur = raw(p)
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/compat.py", line 53, in raw
return bytes(x)
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/layers/tls/session.py", line 966, in __bytes__
built_packet = super(_GenericTLSSessionInheritance, self).__bytes__()
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/packet.py", line 492, in __bytes__
return self.build()
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/layers/tls/handshake.py", line 1028, in build
m = s.client_random + s.server_random + raw(p)
File "/data1/wangqian/venv_py3/lib/python3.7/site-packages/scapy/compat.py", line 53, in raw
return bytes(x)
TypeError: 'NoneType' object cannot be interpreted as an integer

# Fixed code
def getfield(self, pkt, s):
    tmp_len = self.length_from(pkt) or 0
    if tmp_len <= 0:
        return s, []
    return s[tmp_len:], self.m2i(pkt, s[:tmp_len])
# Buggy code
def __init__(self, filename, fdesc, magic):
    RawPcapReader.__init__(self, filename, fdesc, magic)
    try:
        self.LLcls = conf.l2types[self.linktype]
    except KeyError:
        warning(
            "PcapReader: unknown LL type [%i]/[%#x]. Using Raw packets"
            % (self.linktype, self.linktype)
        )  # noqa: E501
        self.LLcls = conf.raw_layer


# Traceback (TypeError)
$ cat test.py
import sys
import scapy
import scapy.utils

scapy.utils.rdpcap(sys.argv[1])
$ python3 test.py sample.pcap
Traceback (most recent call last):
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1139, in read_packet
p = self.LLcls(s)
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "test.py", line 6, in <module>
scapy.utils.rdpcap(sys.argv[1])
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 951, in rdpcap
return fdesc.read_all(count=count)
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1154, in read_all
res = RawPcapReader.read_all(self, count)
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1094, in read_all
p = self.read_packet()
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1147, in read_packet
p = conf.raw_layer(s)
TypeError: 'NoneType' object is not callable
$

# Fixed code
def __init__(self, filename, fdesc, magic):
    RawPcapReader.__init__(self, filename, fdesc, magic)
    try:
        self.LLcls = conf.l2types[self.linktype]
    except KeyError:
        warning(
            "PcapReader: unknown LL type [%i]/[%#x]. Using Raw packets"
            % (self.linktype, self.linktype)
        )  # noqa: E501
        from scapy.packet import Raw

        self.LLcls = conf.raw_layer or Raw
# Buggy code
def read_packet(self, size=MTU):
    rp = super(PcapReader, self).read_packet(size=size)
    if rp is None:
        raise EOFError
    s, pkt_info = rp

    try:
        p = self.LLcls(s)
    except KeyboardInterrupt:
        raise
    except Exception:
        if conf.debug_dissector:
            from scapy.sendrecv import debug

            debug.crashed_on = (self.LLcls, s)
            raise
        p = conf.raw_layer(s)
    power = Decimal(10) ** Decimal(-9 if self.nano else -6)
    p.time = EDecimal(pkt_info.sec + power * pkt_info.usec)
    p.wirelen = pkt_info.wirelen
    return p


# Traceback (TypeError)
$ cat test.py
import sys
import scapy
import scapy.utils

scapy.utils.rdpcap(sys.argv[1])
$ python3 test.py sample.pcap
Traceback (most recent call last):
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1139, in read_packet
p = self.LLcls(s)
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "test.py", line 6, in <module>
scapy.utils.rdpcap(sys.argv[1])
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 951, in rdpcap
return fdesc.read_all(count=count)
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1154, in read_all
res = RawPcapReader.read_all(self, count)
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1094, in read_all
p = self.read_packet()
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1147, in read_packet
p = conf.raw_layer(s)
TypeError: 'NoneType' object is not callable
$

# Fixed code
def read_packet(self, size=MTU):
    rp = super(PcapReader, self).read_packet(size=size)
    if rp is None:
        raise EOFError
    s, pkt_info = rp

    try:
        p = self.LLcls(s)
    except KeyboardInterrupt:
        raise
    except Exception:
        if conf.debug_dissector:
            from scapy.sendrecv import debug

            debug.crashed_on = (self.LLcls, s)
            raise
        from scapy.packet import Raw

        p = (conf.raw_layer or Raw)(s)
    power = Decimal(10) ** Decimal(-9 if self.nano else -6)
    p.time = EDecimal(pkt_info.sec + power * pkt_info.usec)
    p.wirelen = pkt_info.wirelen
    return p
# Buggy code
def read_packet(self, size=MTU):
    rp = super(PcapNgReader, self).read_packet(size=size)
    if rp is None:
        raise EOFError
    s, (linktype, tsresol, tshigh, tslow, wirelen) = rp
    try:
        p = conf.l2types[linktype](s)
    except KeyboardInterrupt:
        raise
    except Exception:
        if conf.debug_dissector:
            raise
        p = conf.raw_layer(s)
    if tshigh is not None:
        p.time = EDecimal((tshigh << 32) + tslow) / tsresol
    p.wirelen = wirelen
    return p


# Traceback (TypeError)
$ cat test.py
import sys
import scapy
import scapy.utils

scapy.utils.rdpcap(sys.argv[1])
$ python3 test.py sample.pcap
Traceback (most recent call last):
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1139, in read_packet
p = self.LLcls(s)
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "test.py", line 6, in <module>
scapy.utils.rdpcap(sys.argv[1])
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 951, in rdpcap
return fdesc.read_all(count=count)
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1154, in read_all
res = RawPcapReader.read_all(self, count)
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1094, in read_all
p = self.read_packet()
File "/home/user/ven/lib/python3.8/site-packages/scapy/utils.py", line 1147, in read_packet
p = conf.raw_layer(s)
TypeError: 'NoneType' object is not callable
$

# Fixed code
def read_packet(self, size=MTU):
    rp = super(PcapNgReader, self).read_packet(size=size)
    if rp is None:
        raise EOFError
    s, (linktype, tsresol, tshigh, tslow, wirelen) = rp
    try:
        p = conf.l2types[linktype](s)
    except KeyboardInterrupt:
        raise
    except Exception:
        if conf.debug_dissector:
            raise
        from scapy.packet import Raw

        p = (conf.raw_layer or Raw)(s)
    if tshigh is not None:
        p.time = EDecimal((tshigh << 32) + tslow) / tsresol
    p.wirelen = wirelen
    return p
# Buggy code
def m2i(self, pkt, val):
    ret = []
    for v in val:
        byte = orb(v)
        left = byte >> 4
        right = byte & 0xF
        if left == 0xF:
            ret.append(TBCD_TO_ASCII[right : right + 1])
        else:
            ret += [TBCD_TO_ASCII[right : right + 1], TBCD_TO_ASCII[left : left + 1]]  # noqa: E501
    return b"".join(ret)


# Traceback (ValueError)
from scapy.contrib.gtp_v2 import IE_IMSI
ie = IE_IMSI(ietype='IMSI', length=8, IMSI='2080112345670000')
ie
<IE_IMSI  ietype=IMSI length=8 IMSI='2080112345670000' |>
len(ie)
Traceback (most recent call last):
File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 527, in __len__
return len(self.__bytes__())
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 492, in __bytes__
return self.build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 612, in build
p = self.do_build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 594, in do_build
pkt = self.self_build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 575, in self_build
p = f.addfield(self, p, val)
File "/root/Umakant/gtpv2/scapy-master/scapy/fields.py", line 1267, in addfield
return s + struct.pack("%is" % len_pkt, self.i2m(pkt, val))
File "/root/Umakant/gtpv2/scapy-master/scapy/contrib/gtp.py", line 179, in i2m
ret_string += chr(int(tmp[1] + tmp[0], 16))
ValueError: invalid literal for int() with base 16: "'b"

# Fixed code
def m2i(self, pkt, val):
    ret = []
    for v in val:
        byte = orb(v)
        left = byte >> 4
        right = byte & 0xF
        if left == 0xF:
            ret.append(TBCD_TO_ASCII[right : right + 1])
        else:
            ret += [TBCD_TO_ASCII[right : right + 1], TBCD_TO_ASCII[left : left + 1]]
    return b"".join(ret)
# Buggy code
def i2m(self, pkt, val):
    val = str(val)
    ret_string = ""
    for i in range(0, len(val), 2):
        tmp = val[i : i + 2]
        if len(tmp) == 2:
            ret_string += chr(int(tmp[1] + tmp[0], 16))
        else:
            ret_string += chr(int("F" + tmp[0], 16))
    return ret_string


# Traceback (ValueError)
from scapy.contrib.gtp_v2 import IE_IMSI
ie = IE_IMSI(ietype='IMSI', length=8, IMSI='2080112345670000')
ie
<IE_IMSI  ietype=IMSI length=8 IMSI='2080112345670000' |>
len(ie)
Traceback (most recent call last):
File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 527, in __len__
return len(self.__bytes__())
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 492, in __bytes__
return self.build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 612, in build
p = self.do_build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 594, in do_build
pkt = self.self_build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 575, in self_build
p = f.addfield(self, p, val)
File "/root/Umakant/gtpv2/scapy-master/scapy/fields.py", line 1267, in addfield
return s + struct.pack("%is" % len_pkt, self.i2m(pkt, val))
File "/root/Umakant/gtpv2/scapy-master/scapy/contrib/gtp.py", line 179, in i2m
ret_string += chr(int(tmp[1] + tmp[0], 16))
ValueError: invalid literal for int() with base 16: "'b"

# Fixed code
def i2m(self, pkt, val):
    if not isinstance(val, bytes):
        val = bytes_encode(val)
    ret_string = b""
    for i in range(0, len(val), 2):
        tmp = val[i : i + 2]
        if len(tmp) == 2:
            ret_string += chb(int(tmp[::-1], 16))
        else:
            ret_string += chb(int(b"F" + tmp[:1], 16))
    return ret_string
# Buggy code
def i2m(self, pkt, s):
    s = b"".join(chb(len(x)) + x for x in s.split("."))
    return s


# Traceback (ValueError)
from scapy.contrib.gtp_v2 import IE_IMSI
ie = IE_IMSI(ietype='IMSI', length=8, IMSI='2080112345670000')
ie
<IE_IMSI  ietype=IMSI length=8 IMSI='2080112345670000' |>
len(ie)
Traceback (most recent call last):
File "/usr/lib/python3.5/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 527, in __len__
return len(self.__bytes__())
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 492, in __bytes__
return self.build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 612, in build
p = self.do_build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 594, in do_build
pkt = self.self_build()
File "/root/Umakant/gtpv2/scapy-master/scapy/packet.py", line 575, in self_build
p = f.addfield(self, p, val)
File "/root/Umakant/gtpv2/scapy-master/scapy/fields.py", line 1267, in addfield
return s + struct.pack("%is" % len_pkt, self.i2m(pkt, val))
File "/root/Umakant/gtpv2/scapy-master/scapy/contrib/gtp.py", line 179, in i2m
ret_string += chr(int(tmp[1] + tmp[0], 16))
ValueError: invalid literal for int() with base 16: "'b"

# Fixed code
def i2m(self, pkt, s):
    if not isinstance(s, bytes):
        s = bytes_encode(s)
    s = b"".join(chb(len(x)) + x for x in s.split(b"."))
    return s
# Buggy code
def __add__(self, other, **kwargs):
    return EDecimal(Decimal.__add__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __add__(self, other, **kwargs):
    return EDecimal(Decimal.__add__(self, Decimal(other), **kwargs))
# Buggy code
def __sub__(self, other, **kwargs):
    return EDecimal(Decimal.__sub__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __sub__(self, other, **kwargs):
    return EDecimal(Decimal.__sub__(self, Decimal(other), **kwargs))
# Buggy code
def __mul__(self, other, **kwargs):
    return EDecimal(Decimal.__mul__(self, other, **kwargs))


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/scapy-2.4.3.dev227-py2.7.egg/scapy/utils.py", line 67, in __mul__
return EDecimal(Decimal.__mul__(self, other, **kwargs))
File "/usr/lib/python2.7/decimal.py", line 657, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert NotImplemented to Decimal

# Fixed code
def __mul__(self, other, **kwargs):
    return EDecimal(Decimal.__mul__(self, Decimal(other), **kwargs))