gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _get_time(self):
    time.tzset()
    now = datetime.now(utc).astimezone()
    return (now + self.DELTA).strftime(self.format)


# Traceback (TypeError)
Traceback (most recent call last):
File "/nix/store/vws161bihzlcxbiq17h63wdcdg12vrsc-python2.7-trollius-2.2/lib/python2.7/site-packages/trollius/events.py", line 136, in _run
self._callback(*self._args)
File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/manager.py", line 1197, in f
func(*args)
File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/base.py", line 428, in timer_setup
update_interval = self.tick()
File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/clock.py", line 76, in tick
self.update(self.poll())
File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/clock.py", line 91, in poll
return self._get_time()
File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/clock.py", line 83, in _get_time
now = datetime.now(utc).astimezone()
TypeError: Required argument 'tz' (pos 1) not found

# Fixed code
def _get_time(self):
    time.tzset()
    if six.PY3:
        now = datetime.now(timezone.utc).astimezone()
    else:
        now = datetime.now()
    return (now + self.DELTA).strftime(self.format)
# Buggy code
def framed(
    self,
    border_width,
    border_color,
    pad_x,
    pad_y,
    highlight_color=None,
    line_thickness=None,
):
    return TextFrame(
        self, border_width, border_color, pad_x, pad_y, highlight_color, line_thickness
    )


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def framed(self, border_width, border_color, pad_x, pad_y, highlight_color=None):
    return TextFrame(
        self, border_width, border_color, pad_x, pad_y, highlight_color=highlight_color
    )
# Buggy code
def __init__(
    self,
    layout,
    border_width,
    border_color,
    pad_x,
    pad_y,
    highlight_color,
    line_thickness,
):
    self.layout = layout
    self.border_width = border_width
    self.border_color = border_color
    self.drawer = self.layout.drawer
    self.highlight_color = highlight_color
    self.line_thickness = line_thickness

    if isinstance(pad_x, collections.Iterable):
        self.pad_left = pad_x[0]
        self.pad_right = pad_x[1]
    else:
        self.pad_left = self.pad_right = pad_x

    if isinstance(pad_y, collections.Iterable):
        self.pad_top = pad_y[0]
        self.pad_bottom = pad_y[1]
    else:
        self.pad_top = self.pad_bottom = pad_y


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def __init__(
    self, layout, border_width, border_color, pad_x, pad_y, highlight_color=None
):
    self.layout = layout
    self.border_width = border_width
    self.border_color = border_color
    self.drawer = self.layout.drawer
    self.highlight_color = highlight_color

    if isinstance(pad_x, collections.Iterable):
        self.pad_left = pad_x[0]
        self.pad_right = pad_x[1]
    else:
        self.pad_left = self.pad_right = pad_x

    if isinstance(pad_y, collections.Iterable):
        self.pad_top = pad_y[0]
        self.pad_bottom = pad_y[1]
    else:
        self.pad_top = self.pad_bottom = pad_y
# Buggy code
def draw(self, x, y, bar_height=None, rounded=True, fill=False, line=False):
    self.drawer.set_source_rgb(self.border_color)
    opts = [
        x,
        y,
        self.layout.width + self.pad_left + self.pad_right,
        self.layout.height + self.pad_top + self.pad_bottom,
        self.border_width,
    ]
    if line:
        if not bar_height:
            bar_height = self.layout.height + self.pad_top + self.pad_bottom
        highlight_opts = [
            x,
            0,
            self.layout.width + self.pad_left + self.pad_right,
            bar_height,
            self.border_width,
        ]
        self.drawer.set_source_rgb(self.highlight_color)
        self.drawer.fillrect(*highlight_opts)

        lineopts = [
            x,
            bar_height - self.line_thickness,
            self.layout.width + self.pad_left + self.pad_right,
            self.line_thickness,
            self.border_width,
        ]

        self.drawer.set_source_rgb(self.border_color)
        self.drawer.fillrect(*lineopts)
    elif fill:
        if rounded:
            self.drawer.rounded_fillrect(*opts)
        else:
            self.drawer.fillrect(*opts)
    else:
        if rounded:
            self.drawer.rounded_rectangle(*opts)
        else:
            self.drawer.rectangle(*opts)
    self.drawer.ctx.stroke()
    self.layout.draw(x + self.pad_left, y + self.pad_top)


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def draw(self, x, y, rounded=True, fill=False, line=False, highlight=False):
    self.drawer.set_source_rgb(self.border_color)
    opts = [
        x,
        y,
        self.layout.width + self.pad_left + self.pad_right,
        self.layout.height + self.pad_top + self.pad_bottom,
        self.border_width,
    ]
    if line:
        if highlight:
            self.drawer.set_source_rgb(self.highlight_color)
            self.drawer.fillrect(*opts)
            self.drawer.set_source_rgb(self.border_color)

        # change to only fill in bottom line
        opts[1] = self.height - self.border_width  # y
        opts[3] = self.border_width  # height

        self.drawer.fillrect(*opts)
    elif fill:
        if rounded:
            self.drawer.rounded_fillrect(*opts)
        else:
            self.drawer.fillrect(*opts)
    else:
        if rounded:
            self.drawer.rounded_rectangle(*opts)
        else:
            self.drawer.rectangle(*opts)
    self.drawer.ctx.stroke()
    self.layout.draw(x + self.pad_left, y + self.pad_top)
# Buggy code
def draw_fill(self, x, y, rounded=True):
    self.draw(x, y, rounded, fill=True)


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def draw_fill(self, x, y, rounded=True):
    self.draw(x, y, rounded=rounded, fill=True)
# Buggy code
def draw_line(self, x, y, bar_height, rounded=False):
    self.draw(x, y, bar_height, rounded, line=True)


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def draw_line(self, x, y, highlighted):
    self.draw(x, y, line=True, highlight=highlighted)
# Buggy code
def drawbox(
    self,
    offset,
    text,
    bordercolor,
    textcolor,
    highlight_color,
    line_thickness,
    rounded=False,
    block=False,
    width=None,
    line=False,
):
    self.layout.text = text
    self.layout.font_family = self.font
    self.layout.font_size = self.fontsize
    self.layout.colour = textcolor
    if width is not None:
        self.layout.width = width
    framed = self.layout.framed(
        self.borderwidth,
        bordercolor,
        self.padding_x,
        self.padding_y,
        highlight_color,
        line_thickness,
    )
    y = self.margin_y
    if self.center_aligned:
        for t in base.MarginMixin.defaults:
            if t[0] == "margin":
                y += (self.bar.height - framed.height) / 2 - t[1]
                break
    if block:
        framed.draw_fill(offset, y, rounded)
    elif line:
        framed.draw_line(offset, y, self.bar.size, rounded)
    else:
        framed.draw(offset, y, rounded)


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def drawbox(
    self,
    offset,
    text,
    bordercolor,
    textcolor,
    width=None,
    rounded=False,
    block=False,
    line=False,
    highlighted=False,
):
    self.layout.text = text
    self.layout.font_family = self.font
    self.layout.font_size = self.fontsize
    self.layout.colour = textcolor
    if width is not None:
        self.layout.width = width
    if line:
        pad_y = (self.bar.height - self.layout.height) / 2
    else:
        pad_y = self.padding_y
    framed = self.layout.framed(
        self.borderwidth, bordercolor, self.padding_x, pad_y, self.highlight_color
    )
    y = self.margin_y
    if self.center_aligned:
        for t in base.MarginMixin.defaults:
            if t[0] == "margin":
                y += (self.bar.height - framed.height) / 2 - t[1]
                break
    if block:
        framed.draw_fill(offset, y, rounded)
    elif line:
        framed.draw_line(offset, y, highlighted)
    else:
        framed.draw(offset, y, rounded)
# Buggy code
def drawbox(
    self,
    offset,
    text,
    bordercolor,
    textcolor,
    rounded=False,
    block=False,
    width=None,
    icon=None,
):
    self.drawtext(text, textcolor, width)

    icon_padding = (self.icon_size + 4) if icon else 0
    padding_x = [self.padding_x + icon_padding, self.padding_x]

    framed = self.layout.framed(
        self.borderwidth, bordercolor, padding_x, self.padding_y
    )
    if block:
        framed.draw_fill(offset, self.margin_y, rounded)
    else:
        framed.draw(offset, self.margin_y, rounded)

    if icon:
        self.draw_icon(icon, offset)


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def drawbox(
    self,
    offset,
    text,
    bordercolor,
    textcolor,
    width=None,
    rounded=False,
    block=False,
    icon=None,
):
    self.drawtext(text, textcolor, width)

    icon_padding = (self.icon_size + 4) if icon else 0
    padding_x = [self.padding_x + icon_padding, self.padding_x]

    framed = self.layout.framed(
        self.borderwidth, bordercolor, padding_x, self.padding_y
    )
    if block:
        framed.draw_fill(offset, self.margin_y, rounded)
    else:
        framed.draw(offset, self.margin_y, rounded)

    if icon:
        self.draw_icon(icon, offset)
# Buggy code
def draw(self):
    self.drawer.clear(self.background or self.bar.background)
    offset = 0

    for w in self.bar.screen.group.windows:
        state = ""
        if w is None:
            pass
        elif w.maximized:
            state = "[] "
        elif w.minimized:
            state = "_ "
        elif w.floating:
            state = "V "
        task = "%s%s" % (state, w.name if w and w.name else " ")

        if w.urgent:
            border = self.urgent_border
        elif w is w.group.currentWindow:
            border = self.border
        else:
            border = self.background or self.bar.background

        bw = self.box_width(task)
        self.drawbox(
            self.margin_x + offset,
            task,
            border,
            self.foreground,
            self.rounded,
            self.highlight_method == "block",
            bw - self.margin_x * 2 - self.padding_x * 2,
            icon=self.get_window_icon(w),
        )

        offset += bw + self.icon_size
    self.drawer.draw(offsetx=self.offset, width=self.width)


# Traceback (UnboundLocalError)
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run
self._callback(*self._args)
File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f
func(*args)
File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw
i.draw()
File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw
highlight_color,
UnboundLocalError: local variable 'highlight_color' referenced before assignment

# Fixed code
def draw(self):
    self.drawer.clear(self.background or self.bar.background)
    offset = 0

    for w in self.bar.screen.group.windows:
        state = ""
        if w is None:
            pass
        elif w.maximized:
            state = "[] "
        elif w.minimized:
            state = "_ "
        elif w.floating:
            state = "V "
        task = "%s%s" % (state, w.name if w and w.name else " ")

        if w.urgent:
            border = self.urgent_border
        elif w is w.group.currentWindow:
            border = self.border
        else:
            border = self.background or self.bar.background

        bw = self.box_width(task)
        self.drawbox(
            self.margin_x + offset,
            task,
            border,
            self.foreground,
            rounded=self.rounded,
            block=(self.highlight_method == "block"),
            width=(bw - self.margin_x * 2 - self.padding_x * 2),
            icon=self.get_window_icon(w),
        )

        offset += bw + self.icon_size
    self.drawer.draw(offsetx=self.offset, width=self.width)
# Buggy code
def alloc_color(self, color):
    """
    Flexible color allocation.
    """
    if color.startswith("#"):
        if len(color) != 7:
            raise ValueError("Invalid color: %s" % color)

        def x8to16(i):
            return 0xFFFF * (i & 0xFF) // 0xFF

        r = x8to16(int(color[1] + color[2], 16))
        g = x8to16(int(color[3] + color[4], 16))
        b = x8to16(int(color[5] + color[6], 16))
        return self.conn.conn.core.AllocColor(self.cid, r, g, b).reply()
    else:
        return self.conn.conn.core.AllocNamedColor(self.cid, len(color), color).reply()


# Traceback (xcb.xproto.NameError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 585, in _xpoll
r = h(e)
File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 892, in handle_UnmapNotify
self.unmanage(e.window)
File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 406, in unmanage
c.group.remove(c)
File "/usr/lib/python2.7/dist-packages/libqtile/group.py", line 215, in remove
self.focus(nextfocus, True)
File "/usr/lib/python2.7/dist-packages/libqtile/group.py", line 156, in focus
l.focus(win)
File "/usr/lib/python2.7/dist-packages/libqtile/layout/max.py", line 46, in focus
self.group.layoutAll()
File "/usr/lib/python2.7/dist-packages/libqtile/group.py", line 92, in layoutAll
self.layout.layout(normal, screen)
File "/usr/lib/python2.7/dist-packages/libqtile/layout/base.py", line 54, in layout
self.configure(i, screen)
File "/usr/lib/python2.7/dist-packages/libqtile/layout/tile.py", line 189, in configure
bc = self.group.qtile.colorPixel(self.border_focus)
File "/usr/lib/python2.7/dist-packages/libqtile/utils.py", line 99, in wrap
ret = f(self, *args)
File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 364, in colorPixel
return self.conn.screens[0].default_colormap.alloc_color(name).pixel
File "/usr/lib/python2.7/dist-packages/libqtile/xcbq.py", line 288, in alloc_color
self.cid, len(color), color
BadName: <xcb.xproto.NameError object at 0x319c908>

# Fixed code
def alloc_color(self, color):
    """
    Flexible color allocation.
    """
    try:
        return self.conn.conn.core.AllocNamedColor(self.cid, len(color), color).reply()
    except xcffib.xproto.NameError:

        def x8to16(i):
            return 0xFFFF * (i & 0xFF) // 0xFF

        r = x8to16(int(color[-6] + color[-5], 16))
        g = x8to16(int(color[-4] + color[-3], 16))
        b = x8to16(int(color[-2] + color[-1], 16))
        return self.conn.conn.core.AllocColor(self.cid, r, g, b).reply()
# Buggy code
def _receive(self):
    c = self.subclient
    ret = []
    try:
        ret.append(self._receive_one(c))
    except Empty:
        pass
    if c.connection is not None:
        while c.connection.can_read(timeout=0):
            ret.append(self._receive_one(c))
    return any(ret)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/venv/lib/python3.4/site-packages/celery/worker/worker.py", line 203, in start
self.blueprint.start(self)
File "/venv/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
step.start(parent)
File "/venv/lib/python3.4/site-packages/celery/bootsteps.py", line 370, in start
return self.obj.start()
File "/venv/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 318, in start
blueprint.start(self)
File "/venv/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
step.start(parent)
File "/venv/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 584, in start
c.loop(*c.loop_args())
File "/venv/lib/python3.4/site-packages/celery/worker/loops.py", line 88, in asynloop
next(loop)
File "/venv/lib/python3.4/site-packages/kombu/async/hub.py", line 345, in create_loop
cb(*cbargs)
File "/venv/lib/python3.4/site-packages/kombu/transport/redis.py", line 1038, in on_readable
self.cycle.on_readable(fileno)
File "/venv/lib/python3.4/site-packages/kombu/transport/redis.py", line 337, in on_readable
chan.handlers[type]()
File "/venv/lib/python3.4/site-packages/kombu/transport/redis.py", line 670, in _receive
while c.connection.can_read(timeout=0):
AttributeError: 'NoneType' object has no attribute 'can_read'

# Fixed code
def _receive(self):
    c = self.subclient
    ret = []
    try:
        ret.append(self._receive_one(c))
    except Empty:
        pass
    while c.connection is not None and c.connection.can_read(timeout=0):
        ret.append(self._receive_one(c))
    return any(ret)
# Buggy code
def _shrink_down(self, collect=True):
    resource = self._resource
    # Items to the left are last recently used, so we remove those first.
    with resource.mutex:
        while len(resource.queue) > self.limit:
            R = resource.queue.popleft()
            if collect:
                self.collect_resource(R)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/gunicorn/workers/async.py", line 56, in handle
self.handle_request(listener_name, req, client, addr)
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/gunicorn/workers/async.py", line 107, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/fga/workspace/kombu_eventlet_bug/wsgi.py", line 18, in app
add.delay(1,2)
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/task.py", line 412, in delay
return self.apply_async(args, kwargs)
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/task.py", line 535, in apply_async
**options
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 734, in send_task
with self.producer_or_acquire(producer) as P:
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 863, in producer_or_acquire
producer, self.producer_pool.acquire, block=True,
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 1232, in producer_pool
return self.amqp.producer_pool
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/amqp.py", line 610, in producer_pool
self._producer_pool.limit = self.app.pool.limit
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 1147, in pool
pools.set_limit(limit)
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/kombu/pools.py", line 137, in set_limit
pool.resize(limit)
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/kombu/resource.py", line 188, in resize
self._shrink_down()
File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/kombu/resource.py", line 193, in _shrink_down
with resource.mutex:
AttributeError: 'LifoQueue' object has no attribute 'mutex'

# Fixed code
def _shrink_down(self, collect=True):
    class Noop:
        def __enter__(self):
            pass

        def __exit__(self, type, value, traceback):
            pass

    resource = self._resource
    # Items to the left are last recently used, so we remove those first.
    with getattr(resource, "mutex", Noop()):
        while len(resource.queue) > self.limit:
            R = resource.queue.popleft()
            if collect:
                self.collect_resource(R)
# Buggy code
def __lt__(self, other):
    """Implement the less-than operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
    return str(self) < str(other)


# Traceback (TypeError)
from Bio.Seq import Seq
'A' > Seq('A')
False
Seq('A') > 'A'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'Seq' and 'str'

# Fixed code
def __lt__(self, other):
    """Implement the less-than operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
    if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
        return str(self) < str(other)
    raise TypeError(
        "'<' not supported between instances of '{}' and '{}'".format(
            type(self).__name__, type(other).__name__
        )
    )
# Buggy code
def __le__(self, other):
    """Implement the less-than or equal operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
    return str(self) <= str(other)


# Traceback (TypeError)
from Bio.Seq import Seq
'A' > Seq('A')
False
Seq('A') > 'A'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'Seq' and 'str'

# Fixed code
def __le__(self, other):
    """Implement the less-than or equal operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
    if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
        return str(self) <= str(other)
    raise TypeError(
        "'<=' not supported between instances of '{}' and '{}'".format(
            type(self).__name__, type(other).__name__
        )
    )
# Buggy code
def __lt__(self, other):
    """Implement the less-than operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
        if isinstance(other, MutableSeq):
            return self.data < other.data
    return str(self) < str(other)


# Traceback (TypeError)
from Bio.Seq import Seq
'A' > Seq('A')
False
Seq('A') > 'A'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'Seq' and 'str'

# Fixed code
def __lt__(self, other):
    """Implement the less-than operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
        if isinstance(other, MutableSeq):
            return self.data < other.data
    if isinstance(other, (str, Seq, UnknownSeq)):
        return str(self) < str(other)
    raise TypeError(
        "'<' not supported between instances of '{}' and '{}'".format(
            type(self).__name__, type(other).__name__
        )
    )
# Buggy code
def __le__(self, other):
    """Implement the less-than or equal operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
        if isinstance(other, MutableSeq):
            return self.data <= other.data
    return str(self) <= str(other)


# Traceback (TypeError)
from Bio.Seq import Seq
'A' > Seq('A')
False
Seq('A') > 'A'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'Seq' and 'str'

# Fixed code
def __le__(self, other):
    """Implement the less-than or equal operand."""
    if hasattr(other, "alphabet"):
        if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
            warnings.warn(
                "Incompatible alphabets {0!r} and {1!r}".format(
                    self.alphabet, other.alphabet
                ),
                BiopythonWarning,
            )
        if isinstance(other, MutableSeq):
            return self.data <= other.data
    if isinstance(other, (str, Seq, UnknownSeq)):
        return str(self) <= str(other)
    raise TypeError(
        "'<=' not supported between instances of '{}' and '{}'".format(
            type(self).__name__, type(other).__name__
        )
    )
# Buggy code
def upgrade():
    with op.batch_alter_table("sensor") as batch_op:
        batch_op.add_column(sa.Column("cmd_command", sa.TEXT))
        batch_op.add_column(sa.Column("cmd_measurement", sa.TEXT))
        batch_op.add_column(sa.Column("cmd_measurement_units", sa.TEXT))


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def upgrade():
    with op.batch_alter_table("sensor") as batch_op:
        batch_op.add_column(sa.Column("cmd_command", sa.TEXT))
        batch_op.add_column(sa.Column("cmd_measurement", sa.TEXT))
        batch_op.add_column(sa.Column("cmd_measurement_units", sa.TEXT))

    with op.batch_alter_table("pid") as batch_op:
        batch_op.drop_column("sensor_id")

    op.execute(
        """
        UPDATE pid
        SET measurement=''
        """
    )

    op.execute(
        """
        UPDATE pid
        SET is_activated=0
        """
    )
# Buggy code
def downgrade():
    with op.batch_alter_table("sensor") as batch_op:
        batch_op.drop_column("cmd_command")
        batch_op.drop_column("cmd_measurement")
        batch_op.drop_column("cmd_measurement_units")


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def downgrade():
    with op.batch_alter_table("sensor") as batch_op:
        batch_op.drop_column("cmd_command")
        batch_op.drop_column("cmd_measurement")
        batch_op.drop_column("cmd_measurement_units")

    with op.batch_alter_table("pid") as batch_op:
        batch_op.add_column(
            sa.Column("sensor_id", sa.Integer, sa.ForeignKey("sensor.id"))
        )
# Buggy code
def has_required_pid_values(pid_id):
    pid = PID.query.filter(PID.id == pid_id).first()
    error = False
    # TODO: Add more settings-checks before allowing controller to be activated
    if not pid.sensor_id:
        flash(gettext("A valid sensor is required"), "error")
        error = True
    if not pid.measurement:
        flash(gettext("A valid Measure Type is required"), "error")
        error = True
    if not pid.raise_relay_id and not pid.lower_relay_id:
        flash(gettext("A Raise Relay ID and/or a Lower Relay ID is required"), "error")
        error = True
    if error:
        return redirect("/pid")


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def has_required_pid_values(pid_id):
    pid = PID.query.filter(PID.id == pid_id).first()
    error = False
    if not pid.measurement:
        flash(gettext("A valid Measurement is required"), "error")
        error = True
    sensor_unique_id = pid.measurement.split(",")[0]
    sensor = Sensor.query.filter(Sensor.unique_id == sensor_unique_id).first()
    if not sensor:
        flash(gettext("A valid sensor is required"), "error")
        error = True
    if not pid.raise_relay_id and not pid.lower_relay_id:
        flash(gettext("A Raise Relay ID and/or a Lower Relay ID is required"), "error")
        error = True
    if error:
        return redirect("/pid")
# Buggy code
def sensor_deactivate_associated_controllers(sensor_id):
    pid = (
        PID.query.filter(PID.sensor_id == sensor_id).filter(PID.is_activated == True)
    ).all()
    if pid:
        for each_pid in pid:
            controller_activate_deactivate("deactivate", "PID", each_pid.id)
    lcd = LCD.query.filter(LCD.is_activated)
    for each_lcd in lcd:
        if sensor_id in [
            each_lcd.line_1_sensor_id,
            each_lcd.line_2_sensor_id,
            each_lcd.line_3_sensor_id,
            each_lcd.line_4_sensor_id,
        ]:
            controller_activate_deactivate("deactivate", "LCD", each_lcd.id)


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def sensor_deactivate_associated_controllers(sensor_id):
    sensor_unique_id = Sensor.query.filter(Sensor.id == sensor_id).first().unique_id
    pid = PID.query.filter(PID.is_activated == True).all()
    for each_pid in pid:
        if sensor_unique_id in each_pid.measurement:
            controller_activate_deactivate("deactivate", "PID", each_pid.id)

    lcd = LCD.query.filter(LCD.is_activated)
    for each_lcd in lcd:
        if sensor_id in [
            each_lcd.line_1_sensor_id,
            each_lcd.line_2_sensor_id,
            each_lcd.line_3_sensor_id,
            each_lcd.line_4_sensor_id,
        ]:
            controller_activate_deactivate("deactivate", "LCD", each_lcd.id)
# Buggy code
def get_measurement(self):
    """Determine if the return value of the command is a number"""
    out, err, status = cmd_output(self.command)
    if str_is_float(out):
        return float(out)
    else:
        return None


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def get_measurement(self):
    """Determine if the return value of the command is a number"""
    out, _, _ = cmd_output(self.command)
    if str_is_float(out):
        return float(out)
    else:
        return None
# Buggy code
def __init__(self, address, bus):
    super(TSL2591Sensor, self).__init__()
    self.logger = logging.getLogger(
        "mycodo.sensors.tsl2591_{bus}_{add}".format(bus=bus, add=address)
    )
    self.i2c_address = address
    self.i2c_bus = bus
    self._lux = 0.0


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def __init__(self, address, bus):
    super(TSL2591Sensor, self).__init__()
    self.logger = logging.getLogger(
        "mycodo.sensors.tsl2591_{bus}_{add}".format(bus=bus, add=address)
    )
    self.i2c_address = address
    self.i2c_bus = bus
    self._lux = 0.0
    self.tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
# Buggy code
def get_measurement(self):
    """Gets the TSL2591's lux"""
    tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
    full, ir = (
        tsl.get_full_luminosity()
    )  # read raw values (full spectrum and ir spectrum)
    lux = tsl.calculate_lux(full, ir)  # convert raw values to lux
    return lux


# Traceback (IOError)
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp'
2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file

========= Remote Traceback (1) =========
Traceback (most recent call last):
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request
File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off
File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off
File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off
self.check_conditionals(relay_id, duration)
File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals
for each_conditional in conditionals.all():

# Fixed code
def get_measurement(self):
    """Gets the TSL2591's lux"""
    full, ir = (
        self.tsl.get_full_luminosity()
    )  # read raw values (full spectrum and ir spectrum)
    lux = self.tsl.calculate_lux(full, ir)  # convert raw values to lux
    return lux
# Buggy code
def read(self):
    data, bad_format = None, False
    try:
        data = json.loads(self.file.read_text())
        logging.debug("got {} from %s".format(self.msg), *self.msg_args)
        return data
    except ValueError:
        bad_format = True
    except Exception:  # noqa
        pass
    if bad_format:
        self.remove()
    return None


# Traceback (PermissionError)
Traceback (most recent call last):
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 94, in _get
do_periodic_update=self.periodic_update,
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\acquire.py", line 25, in get_wheel
wheel = from_bundle(distribution, version, for_py_version, search_dirs, app_data, do_periodic_update)
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\bundle.py", line 20, in from_bundle
wheel = periodic_update(distribution, for_py_version, wheel, search_dirs, app_data, do_periodic_update)
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 41, in periodic_update
handle_auto_update(distribution, for_py_version, wheel, search_dirs, app_data)
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 62, in handle_auto_update
u_log = UpdateLog.from_dict(embed_update_log.read())
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 140, in read
self.remove()
File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 144, in remove
self.file.unlink()
File "C:\hostedtoolcache\windows\Python\3.6.8\x64\lib\pathlib.py", line 1284, in unlink
self._accessor.unlink(self)
File "C:\hostedtoolcache\windows\Python\3.6.8\x64\lib\pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\runneradmin\\AppData\\Local\\pypa\\virtualenv\\wheel\\3.8\\embed\\1\\wheel.json'
PermissionError(13, 'The process cannot access the file because it is being used by another process')
RuntimeError: seed failed due to failing to download wheels wheel

# Fixed code
def read(self):
    data, bad_format = None, False
    try:
        data = json.loads(self.file.read_text())
        logging.debug("got {} from %s".format(self.msg), *self.msg_args)
        return data
    except ValueError:
        bad_format = True
    except Exception:  # noqa
        pass
    if bad_format:
        try:
            self.remove()
        except (
            OSError
        ):  # reading and writing on the same file may cause race on multiple processes
            pass
    return None
# Buggy code
def generate_draft_news():
    root = Path(__file__).parents[1]
    exe = Path(sys.executable)
    towncrier = exe.with_name("towncrier{}".format(exe.suffix))
    new = subprocess.check_output(
        [str(towncrier), "--draft", "--version", "NEXT"],
        cwd=root,
        universal_newlines=True,
    )
    (root / "docs" / "_draft.rst").write_text(
        "" if "No significant changes" in new else new
    )


# Traceback (FileNotFoundError)
$ sphinx-build docs out
Running Sphinx v2.4.4

Configuration error:
There is a programmable error in your configuration file:

Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 348, in eval_config_file
execfile_(filename, namespace)
File "/usr/lib/python3.8/site-packages/sphinx/util/pycompat.py", line 81, in execfile_
exec(code, _globals)
File "/tmp/virtualenv/docs/conf.py", line 68, in <module>
generate_draft_news()
File "/tmp/virtualenv/docs/conf.py", line 64, in generate_draft_news
new = subprocess.check_output([str(towncrier), "--draft", "--version", "NEXT"], cwd=root, universal_newlines=True)
File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
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] No such file or directory: '/usr/bin/towncrier.8'

# Fixed code
def generate_draft_news():
    root = Path(__file__).parents[1]
    new = subprocess.check_output(
        [sys.executable, "-m", "towncrier", "--draft", "--version", "NEXT"],
        cwd=root,
        universal_newlines=True,
    )
    (root / "docs" / "_draft.rst").write_text(
        "" if "No significant changes" in new else new
    )