gurudesh/pytracebugs huggingface dataset:
# Buggy code
def add_service(self, zeroconf, type, name):
    info = zeroconf.get_service_info(type, name)
    addr = str(ipaddress.ip_address(info.address))
    if addr not in self.found_devices:
        dev = self.check_and_create_device(info, addr)
        self.found_devices[addr] = dev


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

# Fixed code
def add_service(self, zeroconf, type, name):
    info = zeroconf.get_service_info(type, name)
    addr = get_addr_from_info(info)

    if addr not in self.found_devices:
        dev = self.check_and_create_device(info, addr)
        self.found_devices[addr] = dev
# Buggy code
def timezone(self):
    """Get the timezone."""
    return self.send("get_timezone")[0]


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 186, in _async_setup_platform
await asyncio.gather(*pending)
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 292, in async_add_entities
await asyncio.gather(*tasks)
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 451, in _async_add_entity
entity.async_write_ha_state()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 290, in async_write_ha_state
self._async_write_ha_state()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 317, in _async_write_ha_state
attr.update(self.device_state_attributes or {})
File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 333, in device_state_attributes
if self.timers:
File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 284, in timers
for timer in self._timers
File "/usr/src/homeassistant/homeassistant/components/xiaomi_miio/vacuum.py", line 284, in <listcomp>
for timer in self._timers
File "/usr/local/lib/python3.7/site-packages/miio/vacuumcontainers.py", line 444, in next_schedule
local_tz = timezone(self.timezone)
File "/usr/local/lib/python3.7/site-packages/pytz/__init__.py", line 163, in timezone
if zone.upper() == 'UTC':
AttributeError: 'dict' object has no attribute 'upper'

# Fixed code
def timezone(self):
    """Get the timezone."""
    res = self.send("get_timezone")[0]
    if isinstance(res, dict):
        # Xiaowa E25 example
        # {'olson': 'Europe/Berlin', 'posix': 'CET-1CEST,M3.5.0,M10.5.0/3'}
        if "olson" not in res:
            raise VacuumException("Unsupported timezone format: %s" % res)

        return res["olson"]

    # Gen1 vacuum: ['Europe/Berlin']
    return res
# Buggy code
def last_clean_details(self) -> CleaningDetails:
    """Return details from the last cleaning."""
    last_clean_id = self.clean_history().ids.pop(0)
    return self.clean_details(last_clean_id, return_list=False)


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity_platform.py", line 248, in _async_add_entity
await entity.async_device_update(warning=False)
File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 349, in async_device_update
await self.hass.async_add_executor_job(self.update)
File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/local/lib/python3.6/site-packages/homeassistant/components/vacuum/xiaomi_miio.py", line 378, in update
self.last_clean = self._vacuum.last_clean_details()
File "/usr/local/lib/python3.6/site-packages/miio/vacuum.py", line 194, in last_clean_details
last_clean_id = self.clean_history().ids.pop(0)
IndexError: pop from empty list

# Fixed code
def last_clean_details(self) -> Optional[CleaningDetails]:
    """Return details from the last cleaning.

    Returns None if there has been no cleanups."""
    history = self.clean_history()
    if not history.ids:
        return None

    last_clean_id = history.ids.pop(0)
    return self.clean_details(last_clean_id, return_list=False)
# Buggy code
def info(vac: miio.Vacuum):
    """Return device information."""
    res = vac.info()

    click.echo("%s" % res)
    _LOGGER.debug("Full response: %s", pf(res.raw))


# Traceback (TypeError)
INFO:miio.vacuum_cli:Debug mode active
DEBUG:miio.vacuum_cli:Read stored sequence ids: {'seq': 645, 'manual_seq': 0}
DEBUG:miio.vacuum_cli:Connecting to 10.0.11.100 with token xxxxxxxxxxxxx
DEBUG:miio.protocol:Unable to decrypt, returning raw bytes: b''
DEBUG:miio.device:Got a response: Container:
data = Container:
data =  (total 0)
value =  (total 0)
offset1 = 32
offset2 = 32
length = 0
header = Container:
data = !1\x00 \x00\x00\x00\x00\x04m\xf8\xe2\x00\x00\x1e\xf1 (total 16)
value = Container:
length = 32
unknown = 0
device_id = 00aabbcc (total 8)
ts = 1970-01-01 02:12:01
offset1 = 0
offset2 = 16
length = 16
checksum = \xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff (total 16)
DEBUG:miio.device:Discovered b'00aabbcc' with ts: 1970-01-01 02:12:01, token: b'ffffffffffffffffffffffffffffffff'
DEBUG:miio.device:10.0.11.100:54321 >>: {'id': 646, 'method': 'miIO.info', 'params': []}
ERROR:miio.protocol:unable to parse json '': Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/usr/bin/mirobo", line 11, in <module>
load_entry_point('python-miio==0.3.3', 'console_scripts', 'mirobo')()
File "/usr/lib/python3/dist-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/python3/dist-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/usr/lib/python3/dist-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/lib/python3/dist-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib/python3/dist-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3/dist-packages/click/decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args[1:], **kwargs)
File "/usr/lib/python3/dist-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3/dist-packages/miio/vacuum_cli.py", line 391, in info
res = vac.info()
File "/usr/lib/python3/dist-packages/miio/device.py", line 271, in info
return DeviceInfo(self.send("miIO.info", []))
File "/usr/lib/python3/dist-packages/miio/device.py", line 239, in send
self.__id = m.data.value["id"]
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def info(vac: miio.Vacuum):
    """Return device information."""
    try:
        res = vac.info()

        click.echo("%s" % res)
        _LOGGER.debug("Full response: %s", pf(res.raw))
    except TypeError:
        click.echo(
            "Unable to fetch info, this can happen when the vacuum "
            "is not connected to the Xiaomi cloud."
        )
# Buggy code
def run(self, evidence, result):
    """Run the sshd_config analysis worker.

    Args:
        evidence (Evidence object):  The evidence we will process.
        result (TurbiniaTaskResult): The object to place task results into.

    Returns:
        TurbiniaTaskResult object.
    """
    # Where to store the resulting output file.
    output_file_name = "sshd_config_analysis.txt"
    output_file_path = os.path.join(self.output_dir, output_file_name)
    # Set the output file as the data source for the output evidence.
    output_evidence = ReportText(source_path=output_file_path)

    # Read the input file
    with open(evidence.local_path, "r") as input_file:
        sshd_config = input_file.read()

    (report, priority, summary) = self.analyse_sshd_config(sshd_config)
    output_evidence.text_data = report
    result.report_priority = priority
    result.report_data = report

    # Write the report to the output file.
    with open(output_file_path, "w") as fh:
        fh.write(output_evidence.text_data.encode("utf-8"))

    # Add the resulting evidence to the result object.
    result.add_evidence(output_evidence, evidence.config)
    result.close(self, success=True, status=summary)
    return result


# Traceback (TypeError)
Traceback (most recent call last):
File "/turbinia/turbinia/workers/__init__.py", line 719, in run_wrapper
self.result = self.run(evidence, self.result)
File "/turbinia/turbinia/workers/sshd.py", line 58, in run
fh.write(output_evidence.text_data.encode('utf-8'))
TypeError: write() argument must be str, not bytes

# Fixed code
def run(self, evidence, result):
    """Run the sshd_config analysis worker.

    Args:
        evidence (Evidence object):  The evidence we will process.
        result (TurbiniaTaskResult): The object to place task results into.

    Returns:
        TurbiniaTaskResult object.
    """
    # Where to store the resulting output file.
    output_file_name = "sshd_config_analysis.txt"
    output_file_path = os.path.join(self.output_dir, output_file_name)
    # Set the output file as the data source for the output evidence.
    output_evidence = ReportText(source_path=output_file_path)

    # Read the input file
    with open(evidence.local_path, "r") as input_file:
        sshd_config = input_file.read()

    (report, priority, summary) = self.analyse_sshd_config(sshd_config)
    output_evidence.text_data = report
    result.report_priority = priority
    result.report_data = report

    # Write the report to the output file.
    with open(output_file_path, "wb") as fh:
        fh.write(output_evidence.text_data.encode("utf-8"))

    # Add the resulting evidence to the result object.
    result.add_evidence(output_evidence, evidence.config)
    result.close(self, success=True, status=summary)
    return result
# Buggy code
def global_matches(self, text):
    """Compute matches when text is a simple name.

    Return a list of all keywords, built-in functions and names currently
    defined in self.namespace or self.global_namespace that match.

    """
    # print 'Completer->global_matches, txt=%r' % text # dbg
    matches = []
    match_append = matches.append
    n = len(text)
    for lst in [
        keyword.kwlist,
        builtin_mod.__dict__.keys(),
        self.namespace.keys(),
        self.global_namespace.keys(),
    ]:
        for word in lst:
            if word[:n] == text and word != "__builtins__":
                match_append(word)
    return matches


# Traceback (TypeError)
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.

IPython 5.0.0.dev -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str

# Fixed code
def global_matches(self, text):
    """Compute matches when text is a simple name.

    Return a list of all keywords, built-in functions and names currently
    defined in self.namespace or self.global_namespace that match.

    """
    # print 'Completer->global_matches, txt=%r' % text # dbg
    matches = []
    match_append = matches.append
    n = len(text)
    for lst in [
        keyword.kwlist,
        builtin_mod.__dict__.keys(),
        self.namespace.keys(),
        self.global_namespace.keys(),
    ]:
        for word in lst:
            if word[:n] == text and word != "__builtins__":
                match_append(word)
    return [cast_unicode_py2(m) for m in matches]
# Buggy code
def get__all__entries(obj):
    """returns the strings in the __all__ attribute"""
    try:
        words = getattr(obj, "__all__")
    except:
        return []

    return [w for w in words if isinstance(w, string_types)]


# Traceback (TypeError)
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.

IPython 5.0.0.dev -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str

# Fixed code
def get__all__entries(obj):
    """returns the strings in the __all__ attribute"""
    try:
        words = getattr(obj, "__all__")
    except:
        return []

    return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
# Buggy code
def magic_matches(self, text):
    """Match magics"""
    # print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
    # Get all shell magics now rather than statically, so magics loaded at
    # runtime show up too.
    lsm = self.shell.magics_manager.lsmagic()
    line_magics = lsm["line"]
    cell_magics = lsm["cell"]
    pre = self.magic_escape
    pre2 = pre + pre

    # Completion logic:
    # - user gives %%: only do cell magics
    # - user gives %: do both line and cell magics
    # - no prefix: do both
    # In other words, line magics are skipped if the user gives %% explicitly
    bare_text = text.lstrip(pre)
    comp = [pre2 + m for m in cell_magics if m.startswith(bare_text)]
    if not text.startswith(pre2):
        comp += [pre + m for m in line_magics if m.startswith(bare_text)]
    return comp


# Traceback (TypeError)
Python 2.7.11+ (default, Mar 30 2016, 21:00:42)
Type "copyright", "credits" or "license" for more information.

IPython 5.0.0.dev -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: dException in thread Thread-7:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/prompt_toolkit/interface.py", line 742, in run
completions = list(buffer.completer.get_completions(document, complete_event))
File "/home/bwillar0/projects/python/ipython/IPython/terminal/ptshell.py", line 55, in gets
m = unicodedata.normalize('NFC', m)
TypeError: normalize() argument 2 must be unicode, not str

# Fixed code
def magic_matches(self, text):
    """Match magics"""
    # print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
    # Get all shell magics now rather than statically, so magics loaded at
    # runtime show up too.
    lsm = self.shell.magics_manager.lsmagic()
    line_magics = lsm["line"]
    cell_magics = lsm["cell"]
    pre = self.magic_escape
    pre2 = pre + pre

    # Completion logic:
    # - user gives %%: only do cell magics
    # - user gives %: do both line and cell magics
    # - no prefix: do both
    # In other words, line magics are skipped if the user gives %% explicitly
    bare_text = text.lstrip(pre)
    comp = [pre2 + m for m in cell_magics if m.startswith(bare_text)]
    if not text.startswith(pre2):
        comp += [pre + m for m in line_magics if m.startswith(bare_text)]
    return [cast_unicode_py2(c) for c in comp]
# Buggy code
def head(self, kernel_name, path):
    self.get(kernel_name, path, include_body=False)


# Traceback (AttributeError)
[E 16:39:08.471 NotebookApp] Uncaught exception HEAD /kernelspecs/python3/kernel.css (::1)
HTTPServerRequest(protocol='http', host='localhost:8888', method='HEAD', uri='/kernelspecs/python3/kernel.css', version='HTTP/1.1', remote_ip='::1', headers={'Content-Length': '0', 'Accept-Language': 'en-US,en;q=0.8,gl;q=0.6,sq;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Host': 'localhost:8888', 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Connection': 'keep-alive', 'X-Requested-With': 'XMLHttpRequest', 'Referer': 'http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2'})
Traceback (most recent call last):
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 1338, in _execute
self.finish()
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 877, in finish
self.set_etag_header()
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 1257, in set_etag_header
etag = self.compute_etag()
File "/Users/bgranger/anaconda/lib/python2.7/site-packages/tornado/web.py", line 2185, in compute_etag
version_hash = self._get_cached_version(self.absolute_path)
AttributeError: 'KernelSpecResourceHandler' object has no attribute 'absolute_path'
[E 16:39:08.480 NotebookApp] {
"Content-Length": "0",
"Accept-Language": "en-US,en;q=0.8,gl;q=0.6,sq;q=0.4",
"Accept-Encoding": "gzip, deflate, sdch",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
"Host": "localhost:8888",
"X-Requested-With": "XMLHttpRequest",
"Referer": "http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2"
}
[E 16:39:08.480 NotebookApp] 500 HEAD /kernelspecs/python3/kernel.css (::1) 10.72ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2
[I 16:39:08.893 NotebookApp] Kernel shutdown: bd0457da-716d-4fe5-8f13-42614f444fe5
[W 16:39:08.899 NotebookApp] 404 GET /kernelspecs/python3/logo-64x64.png (::1) 3.82ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2
[W 16:39:08.902 NotebookApp] 404 GET /kernelspecs/python3/kernel.js (::1) 2.22ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2
[I 16:39:08.914 NotebookApp] Kernel started: 6875241d-5bbe-4291-8c8e-467867545143

# Fixed code
def head(self, kernel_name, path):
    return self.get(kernel_name, path, include_body=False)
# Buggy code
def check_pid(self, pid):
    if os.name == "nt":
        try:
            import ctypes

            # returns 0 if no such process (of ours) exists
            # positive int otherwise
            p = ctypes.windll.kernel32.OpenProcess(1, 0, pid)
        except Exception:
            self.log.warn(
                "Could not determine whether pid %i is running via `OpenProcess`. "
                " Making the likely assumption that it is." % pid
            )
            return True
        return bool(p)
    else:
        try:
            p = Popen(["ps", "x"], stdout=PIPE, stderr=PIPE)
            output, _ = p.communicate()
        except OSError:
            self.log.warn(
                "Could not determine whether pid %i is running via `ps x`. "
                " Making the likely assumption that it is." % pid
            )
            return True
        pids = list(map(int, re.findall(r"^\W*\d+", output, re.MULTILINE)))
        return pid in pids


# Traceback (TypeError)
Traceback (most recent call last):
File "/work/bin/ipcluster3", line 9, in <module>
load_entry_point('ipython==1.1.0', 'console_scripts', 'ipcluster3')()
File "/work/lib/python3.3/site-packages/IPython/config/application.py", line 545, in launch_instance
app.start()
File "/work/lib/python3.3/site-packages/IPython/parallel/apps/ipclusterapp.py", line 604, in start
return self.subapp.start()
File "/work/lib/python3.3/site-packages/IPython/parallel/apps/ipclusterapp.py", line 195, in start
if not self.check_pid(pid):
File "/work/lib/python3.3/site-packages/IPython/parallel/apps/baseapp.py", line 275, in check_pid
pids = list(map(int, re.findall(r'^\W*\d+', output, re.MULTILINE)))
File "/work/lib/python3.3/re.py", line 201, in findall
return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object

# Fixed code
def check_pid(self, pid):
    if os.name == "nt":
        try:
            import ctypes

            # returns 0 if no such process (of ours) exists
            # positive int otherwise
            p = ctypes.windll.kernel32.OpenProcess(1, 0, pid)
        except Exception:
            self.log.warn(
                "Could not determine whether pid %i is running via `OpenProcess`. "
                " Making the likely assumption that it is." % pid
            )
            return True
        return bool(p)
    else:
        try:
            p = Popen(["ps", "x"], stdout=PIPE, stderr=PIPE)
            output, _ = p.communicate()
        except OSError:
            self.log.warn(
                "Could not determine whether pid %i is running via `ps x`. "
                " Making the likely assumption that it is." % pid
            )
            return True
        pids = list(map(int, re.findall(rb"^\W*\d+", output, re.MULTILINE)))
        return pid in pids
# Buggy code
def init_kernel(self):
    """Create the Kernel object itself"""
    shell_stream = ZMQStream(self.shell_socket)
    control_stream = ZMQStream(self.control_socket)

    kernel_factory = import_item(str(self.kernel_class))

    kernel = kernel_factory(
        parent=self,
        session=self.session,
        shell_streams=[shell_stream, control_stream],
        iopub_socket=self.iopub_socket,
        stdin_socket=self.stdin_socket,
        log=self.log,
        profile_dir=self.profile_dir,
    )
    kernel.record_ports(self.ports)
    self.kernel = kernel


# Traceback (ImportError)
In [24]: IPython.start_kernel()
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-24-3a50fd41fe8b> in <module>()
----> 1 IPython.start_kernel()

/usr/local/lib/python2.7/site-packages/IPython/__init__.pyc in start_kernel(argv, **kwargs)
141         such as `config`.
142     """
--> 143     from IPython.kernel.zmq.kernelapp import launch_new_instance
144     return launch_new_instance(argv=argv, **kwargs)
145

ImportError: cannot import name launch_new_instance

# Fixed code
def init_kernel(self):
    """Create the Kernel object itself"""
    shell_stream = ZMQStream(self.shell_socket)
    control_stream = ZMQStream(self.control_socket)

    kernel_factory = import_item(str(self.kernel_class))

    kernel = kernel_factory(
        parent=self,
        session=self.session,
        shell_streams=[shell_stream, control_stream],
        iopub_socket=self.iopub_socket,
        stdin_socket=self.stdin_socket,
        log=self.log,
        profile_dir=self.profile_dir,
        user_ns=self.user_ns,
    )
    kernel.record_ports(self.ports)
    self.kernel = kernel
# Buggy code
def open(self, kernel_id):
    self.kernel_id = kernel_id.decode("ascii")
    self.session = Session(config=self.config)
    self.save_on_message = self.on_message
    self.on_message = self.on_first_message


# Traceback (zmq.ZMQError)
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-1-9b8a430d8199> in <module>()
----> 1 a = input()

/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/ipkernel.py in <lambda>(prompt)
353         # raw_input in the user namespace.
354         if content.get('allow_stdin', False):
--> 355             raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
356         else:
357             raw_input = lambda prompt='' : self._no_raw_input()

/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/ipkernel.py in _raw_input(self, prompt, ident, parent)
765         while True:
766             try:
--> 767                 ident, reply = self.session.recv(self.stdin_socket, 0)
768             except Exception:
769                 self.log.warn("Invalid Message:", exc_info=True)

/home/thomas/Code/virtualenvs/ipy-3/lib/python3.3/site-packages/ipython-1.0.dev-py3.3.egg/IPython/kernel/zmq/session.py in recv(self, socket, mode, content, copy)
657             socket = socket.socket
658         try:
--> 659             msg_list = socket.recv_multipart(mode, copy=copy)
660         except zmq.ZMQError as e:
661             if e.errno == zmq.EAGAIN:

/usr/lib/python3/dist-packages/zmq/core/pysocket.py in recv_multipart(self, flags, copy, track)
208
209     """
--> 210     parts = [self.recv(flags, copy=copy, track=track)]
211     # have first part already, only loop while more to receive
212     while self.getsockopt(zmq.RCVMORE):

/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5643)()

/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket.Socket.recv (zmq/core/socket.c:5465)()

/usr/lib/python3/dist-packages/zmq/core/socket.cpython-33m-i386-linux-gnu.so in zmq.core.socket._recv_copy (zmq/core/socket.c:1688)()

/usr/lib/python3/dist-packages/zmq/core/error.cpython-33m-i386-linux-gnu.so in zmq.core.error.ZMQError.__init__ (zmq/core/error.c:1059)()

KeyboardInterrupt:

# Fixed code
def open(self, kernel_id):
    self.kernel_id = cast_unicode(kernel_id, "ascii")
    self.session = Session(config=self.config)
    self.save_on_message = self.on_message
    self.on_message = self.on_first_message
# Buggy code
def _handle_kernel_died(self, kernel_id):
    """notice that a kernel died"""
    self.log.warn("Kernel %s died, removing from map.", kernel_id)
    self.delete_mapping_for_kernel(kernel_id)
    self.remove_kernel(kernel_id, now=True)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/IPython/kernel/restarter.py", line 85, in _fire_callbacks
callback()
File "/usr/local/lib/python2.7/dist-packages/IPython/frontend/html/notebook/services/kernels/kernelmanager.py", line 92, in <lambda>
lambda : self._handle_kernel_died(kernel_id),
File "/usr/local/lib/python2.7/dist-packages/IPython/frontend/html/notebook/services/kernels/kernelmanager.py", line 71, in _handle_kernel_died
self.remove_kernel(kernel_id, now=True)
TypeError: remove_kernel() got an unexpected keyword argument 'now'

# Fixed code
def _handle_kernel_died(self, kernel_id):
    """notice that a kernel died"""
    self.log.warn("Kernel %s died, removing from map.", kernel_id)
    self.delete_mapping_for_kernel(kernel_id)
    self.remove_kernel(kernel_id)
# Buggy code
def check_startup_dir(self):
    if not os.path.isdir(self.startup_dir):
        os.mkdir(self.startup_dir)
    readme = os.path.join(self.startup_dir, "README")
    src = os.path.join(get_ipython_package_dir(), "config", "profile", "README_STARTUP")
    if not os.path.exists(readme):
        shutil.copy(src, readme)


# Traceback (IOError)
Traceback (most recent call last):
[--snip--]
File "IPython\core\profiledir.pyc", line 106, in check_startup_dir
File "shutil.pyc", line 116, in copy
File "shutil.pyc", line 81, in copyfile
IOError: [Errno 2] No such file or directory: u'C:\\Documents and Settings\\User\\My Documents\\sofware\\dist\\library.zip\\IPython\\config\\profile\\README_STARTUP'

# Fixed code
def check_startup_dir(self):
    if not os.path.isdir(self.startup_dir):
        os.mkdir(self.startup_dir)
    readme = os.path.join(self.startup_dir, "README")
    src = os.path.join(get_ipython_package_dir(), "config", "profile", "README_STARTUP")

    if not os.path.exists(src):
        self.log.warn(
            "Could not copy README_STARTUP to startup dir. Source file %s does not exist."
            % src
        )

    if os.path.exists(src) and not os.path.exists(readme):
        shutil.copy(src, readme)
# Buggy code
def __init__(self, parent, lexer=None):
    super(PygmentsHighlighter, self).__init__(parent)

    self._document = QtGui.QTextDocument()
    self._formatter = HtmlFormatter(nowrap=True)
    self._lexer = lexer if lexer else PythonLexer()
    self.set_style("default")


# Traceback (AttributeError)
if 1:
print 1

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/IPython/frontend/qt/console/frontend_widget.py", line 59, in highlightBlock
super(FrontendHighlighter, self).highlightBlock(string)
File "/usr/lib/python2.7/dist-packages/IPython/frontend/qt/console/pygments_highlighter.py", line 109, in highlightBlock
self._lexer._saved_state_stack = prev_data.syntax_stack
AttributeError: 'QTextBlockUserData' object has no attribute 'syntax_stack'

# Fixed code
def __init__(self, parent, lexer=None):
    super(PygmentsHighlighter, self).__init__(parent)

    self._document = self.document()
    self._formatter = HtmlFormatter(nowrap=True)
    self._lexer = lexer if lexer else PythonLexer()
    self.set_style("default")
# Buggy code
def __init__(self, session, pub_socket, name):
    self.session = session
    self.pub_socket = pub_socket
    self.name = name
    self.parent_header = {}
    self._new_buffer()


# Traceback (AttributeError)
% ./ipython.py console
Python 2.7.2+ (default, Oct  4 2011, 20:06:09)
Type "copyright", "credits" or "license" for more information.

IPython 0.14.dev -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-8616.json

In [1]: import sys

In [2]: sys.stdout.encoding
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-18fba92f6a6c> in <module>()
----> 1 sys.stdout.encoding

AttributeError: 'OutStream' object has no attribute 'encoding'

# Fixed code
def __init__(self, session, pub_socket, name):
    self.encoding = "UTF-8"
    self.session = session
    self.pub_socket = pub_socket
    self.name = name
    self.parent_header = {}
    self._new_buffer()
# Buggy code
def write(self, string):
    if self.pub_socket is None:
        raise ValueError("I/O operation on closed file")
    else:
        # Make sure that we're handling unicode
        if not isinstance(string, unicode):
            enc = encoding.DEFAULT_ENCODING
            string = string.decode(enc, "replace")

        self._buffer.write(string)
        current_time = time.time()
        if self._start <= 0:
            self._start = current_time
        elif current_time - self._start > self.flush_interval:
            self.flush()


# Traceback (AttributeError)
% ./ipython.py console
Python 2.7.2+ (default, Oct  4 2011, 20:06:09)
Type "copyright", "credits" or "license" for more information.

IPython 0.14.dev -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-8616.json

In [1]: import sys

In [2]: sys.stdout.encoding
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-18fba92f6a6c> in <module>()
----> 1 sys.stdout.encoding

AttributeError: 'OutStream' object has no attribute 'encoding'

# Fixed code
def write(self, string):
    if self.pub_socket is None:
        raise ValueError("I/O operation on closed file")
    else:
        # Make sure that we're handling unicode
        if not isinstance(string, unicode):
            string = string.decode(self.encoding, "replace")

        self._buffer.write(string)
        current_time = time.time()
        if self._start <= 0:
            self._start = current_time
        elif current_time - self._start > self.flush_interval:
            self.flush()
# Buggy code
def print_list_lines(self, filename, first, last):
    """The printing (as opposed to the parsing part of a 'list'
    command."""
    try:
        Colors = self.color_scheme_table.active_colors
        ColorsNormal = Colors.Normal
        tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
        tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
        src = []
        for lineno in range(first, last + 1):
            line = linecache.getline(filename, lineno)
            if not line:
                break

            if lineno == self.curframe.f_lineno:
                line = self.__format_line(
                    tpl_line_em, filename, lineno, line, arrow=True
                )
            else:
                line = self.__format_line(tpl_line, filename, lineno, line, arrow=False)

            src.append(line)
            self.lineno = lineno

        print("".join(src), file=io.stdout)

    except KeyboardInterrupt:
        pass


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def print_list_lines(self, filename, first, last):
    """The printing (as opposed to the parsing part of a 'list'
    command."""
    try:
        Colors = self.color_scheme_table.active_colors
        ColorsNormal = Colors.Normal
        tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
        tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
        src = []
        if filename == "<string>" and hasattr(self, "_exec_filename"):
            filename = self._exec_filename

        for lineno in range(first, last + 1):
            line = ulinecache.getline(filename, lineno)
            if not line:
                break

            if lineno == self.curframe.f_lineno:
                line = self.__format_line(
                    tpl_line_em, filename, lineno, line, arrow=True
                )
            else:
                line = self.__format_line(tpl_line, filename, lineno, line, arrow=False)

            src.append(line)
            self.lineno = lineno

        print("".join(src), file=io.stdout)

    except KeyboardInterrupt:
        pass
# Buggy code
def getdoc(obj):
    """Stable wrapper around inspect.getdoc.

    This can't crash because of attribute problems.

    It also attempts to call a getdoc() method on the given object.  This
    allows objects which provide their docstrings via non-standard mechanisms
    (like Pyro proxies) to still be inspected by ipython's ? system."""
    # Allow objects to offer customized documentation via a getdoc method:
    try:
        ds = obj.getdoc()
    except Exception:
        pass
    else:
        # if we get extra info, we add it to the normal docstring.
        if isinstance(ds, basestring):
            return inspect.cleandoc(ds)

    try:
        return inspect.getdoc(obj)
    except Exception:
        # Harden against an inspect failure, which can occur with
        # SWIG-wrapped extensions.
        return None


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def getdoc(obj):
    """Stable wrapper around inspect.getdoc.

    This can't crash because of attribute problems.

    It also attempts to call a getdoc() method on the given object.  This
    allows objects which provide their docstrings via non-standard mechanisms
    (like Pyro proxies) to still be inspected by ipython's ? system."""
    # Allow objects to offer customized documentation via a getdoc method:
    try:
        ds = obj.getdoc()
    except Exception:
        pass
    else:
        # if we get extra info, we add it to the normal docstring.
        if isinstance(ds, basestring):
            return inspect.cleandoc(ds)

    try:
        docstr = inspect.getdoc(obj)
        encoding = get_encoding(obj)
        return py3compat.cast_unicode(docstr, encoding=encoding)
    except Exception:
        # Harden against an inspect failure, which can occur with
        # SWIG-wrapped extensions.
        raise
        return None
# Buggy code
def getsource(obj, is_binary=False):
    """Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Inputs:

    - obj: an object whose source code we will attempt to extract.

    Optional inputs:

    - is_binary: whether the object is known to come from a binary source.
    This implementation will skip returning any output for binary objects, but
    custom extractors may know how to meaningfully process them."""

    if is_binary:
        return None
    else:
        # get source if obj was decorated with @decorator
        if hasattr(obj, "__wrapped__"):
            obj = obj.__wrapped__
        try:
            src = inspect.getsource(obj)
        except TypeError:
            if hasattr(obj, "__class__"):
                src = inspect.getsource(obj.__class__)
        return src


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def getsource(obj, is_binary=False):
    """Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Inputs:

    - obj: an object whose source code we will attempt to extract.

    Optional inputs:

    - is_binary: whether the object is known to come from a binary source.
    This implementation will skip returning any output for binary objects, but
    custom extractors may know how to meaningfully process them."""

    if is_binary:
        return None
    else:
        # get source if obj was decorated with @decorator
        if hasattr(obj, "__wrapped__"):
            obj = obj.__wrapped__
        try:
            src = inspect.getsource(obj)
        except TypeError:
            if hasattr(obj, "__class__"):
                src = inspect.getsource(obj.__class__)
        encoding = get_encoding(obj)
        return cast_unicode(src, encoding=encoding)
# Buggy code
def _getdef(self, obj, oname=""):
    """Return the definition header for any callable object.

    If any exception is generated, None is returned instead and the
    exception is suppressed."""

    try:
        # We need a plain string here, NOT unicode!
        hdef = oname + inspect.formatargspec(*getargspec(obj))
        return py3compat.unicode_to_str(hdef, "ascii")
    except:
        return None


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def _getdef(self, obj, oname=""):
    """Return the definition header for any callable object.

    If any exception is generated, None is returned instead and the
    exception is suppressed."""

    try:
        hdef = oname + inspect.formatargspec(*getargspec(obj))
        return cast_unicode(hdef)
    except:
        return None
# Buggy code
def psource(self, obj, oname=""):
    """Print the source code for an object."""

    # Flush the source cache because inspect can return out-of-date source
    linecache.checkcache()
    try:
        src = getsource(obj)
    except:
        self.noinfo("source", oname)
    else:
        page.page(self.format(py3compat.unicode_to_str(src)))


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def psource(self, obj, oname=""):
    """Print the source code for an object."""

    # Flush the source cache because inspect can return out-of-date source
    linecache.checkcache()
    try:
        src = getsource(obj)
    except:
        self.noinfo("source", oname)
    else:
        page.page(self.format(src))
# Buggy code
def pfile(self, obj, oname=""):
    """Show the whole file where an object was defined."""

    lineno = find_source_lines(obj)
    if lineno is None:
        self.noinfo("file", oname)
        return

    ofile = find_file(obj)
    # run contents of file through pager starting at line where the object
    # is defined, as long as the file isn't binary and is actually on the
    # filesystem.
    if ofile.endswith((".so", ".dll", ".pyd")):
        print("File %r is binary, not printing." % ofile)
    elif not os.path.isfile(ofile):
        print("File %r does not exist, not printing." % ofile)
    else:
        # Print only text files, not extension binaries.  Note that
        # getsourcelines returns lineno with 1-offset and page() uses
        # 0-offset, so we must adjust.
        page.page(self.format(open(ofile).read()), lineno - 1)


# Traceback (ZeroDivisionError)
In [1]: %run err.py
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
C:\python\ipydevel\VENV\Py27\lib\site-packages\ipython-0.13.dev-py2.7.egg\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
166             else:
167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
169     else:
170         def execfile(fname, *where):

C:\python\ipydevel\err.py in <module>()
5     b=2+4
6
----> 7 a()

C:\python\ipydevel\err.py in a()
2 def a():
3     a=1+2
----> 4     1/0
5     b=2+4
6

ZeroDivisionError: integer division or modulo by zero

# Fixed code
def pfile(self, obj, oname=""):
    """Show the whole file where an object was defined."""

    lineno = find_source_lines(obj)
    if lineno is None:
        self.noinfo("file", oname)
        return

    ofile = find_file(obj)
    # run contents of file through pager starting at line where the object
    # is defined, as long as the file isn't binary and is actually on the
    # filesystem.
    if ofile.endswith((".so", ".dll", ".pyd")):
        print("File %r is binary, not printing." % ofile)
    elif not os.path.isfile(ofile):
        print("File %r does not exist, not printing." % ofile)
    else:
        # Print only text files, not extension binaries.  Note that
        # getsourcelines returns lineno with 1-offset and page() uses
        # 0-offset, so we must adjust.
        page.page(
            self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)),
            lineno - 1,
        )