gurudesh/pytracebugs huggingface dataset:
# Buggy code
def hold_to_lock_aspect_ratio(layer):
    """Hold to lock aspect ratio when resizing a shape."""
    # on key press
    layer._fixed_aspect = True
    box = layer._selected_box
    if box is not None:
        size = box[Box.BOTTOM_RIGHT] - box[Box.TOP_LEFT]
        if not np.any(size == np.zeros(2)):
            layer._aspect_ratio = abs(size[1] / size[0])
        else:
            layer._aspect_ratio = 1
    else:
        layer._aspect_ratio = 1
    if layer._is_moving:
        layer._move(layer.coordinates[layer.dims.displayed])

    yield

    # on key release
    layer._fixed_aspect = False
    if layer._is_moving:
        layer._move(layer.coordinates[layer.dims.displayed])


# Traceback (TypeError)
Traceback (most recent call last):
File "napdev/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 502, in keyPressEvent
self._keyEvent(self._vispy_canvas.events.key_press, ev)
File "napdev/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 551, in _keyEvent
func(native=ev, key=key, text=text_type(ev.text()), modifiers=mod)
File "napdev/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__
self._invoke_callback(cb, event)
File "napdev/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback
self, cb_event=(cb, event))
File "napdev/lib/python3.7/site-packages/vispy/util/event.py", line 471, in _invoke_callback
cb(event)
File "napari/napari/_qt/qt_viewer.py", line 394, in on_key_press
next(gen)
File "napari/napari/layers/shapes/keybindings.py", line 39, in hold_to_lock_aspect_ratio
layer._move(layer.coordinates[layer.dims.displayed])
TypeError: tuple indices must be integers or slices, not list

# Fixed code
def hold_to_lock_aspect_ratio(layer):
    """Hold to lock aspect ratio when resizing a shape."""
    # on key press
    layer._fixed_aspect = True
    box = layer._selected_box
    if box is not None:
        size = box[Box.BOTTOM_RIGHT] - box[Box.TOP_LEFT]
        if not np.any(size == np.zeros(2)):
            layer._aspect_ratio = abs(size[1] / size[0])
        else:
            layer._aspect_ratio = 1
    else:
        layer._aspect_ratio = 1
    if layer._is_moving:
        layer._move([layer.coordinates[i] for i in layer.dims.displayed])

    yield

    # on key release
    layer._fixed_aspect = False
    if layer._is_moving:
        layer._move([layer.coordinates[i] for i in layer.dims.displayed])
# Buggy code
def show(self):
    """Resize, show, and bring forward the window."""
    self._qt_window.resize(self._qt_window.layout().sizeHint())
    self._qt_window.show()
    # make sure window is not hidden, e.g. by browser window in Jupyter
    self._qt_window.raise_()


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def show(self):
    """Resize, show, and bring forward the window."""
    self._qt_window.resize(self._qt_window.layout().sizeHint())
    self._qt_window.show()
# Buggy code
def _update_palette(self, palette):
    # set window styles which don't use the primary stylesheet
    # FIXME: this is a problem with the stylesheet not using properties
    self._status_bar.setStyleSheet(
        template(
            "QStatusBar { background: {{ background }}; color: {{ text }}; }",
            **palette,
        )
    )
    self._qt_center.setStyleSheet(
        template("QWidget { background: {{ background }}; }", **palette)
    )
    self._qt_window.setStyleSheet(template(self.raw_stylesheet, **palette))


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def _update_palette(self, palette):
    # set window styles which don't use the primary stylesheet
    # FIXME: this is a problem with the stylesheet not using properties
    self._status_bar.setStyleSheet(
        template(
            "QStatusBar { background: {{ background }}; color: {{ text }}; }",
            **palette,
        )
    )
    self._qt_center.setStyleSheet(
        template("QWidget { background: {{ background }}; }", **palette)
    )
# Buggy code
def _update_camera(self):
    if self.viewer.dims.ndisplay == 3:
        # Set a 3D camera
        if not isinstance(self.view.camera, ArcballCamera):
            self.view.camera = ArcballCamera(name="ArcballCamera", fov=0)
            # flip y-axis to have correct alignment
            # self.view.camera.flip = (0, 1, 0)

            self.view.camera.viewbox_key_event = viewbox_key_event
            self.viewer.reset_view()
    else:
        # Set 2D camera
        if not isinstance(self.view.camera, PanZoomCamera):
            self.view.camera = PanZoomCamera(aspect=1, name="PanZoomCamera")
            # flip y-axis to have correct alignment
            self.view.camera.flip = (0, 1, 0)

            self.view.camera.viewbox_key_event = viewbox_key_event
            self.viewer.reset_view()


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def _update_camera(self):
    if self.viewer.dims.ndisplay == 3:
        # Set a 3D camera
        if not isinstance(self.view.camera, ArcballCamera):
            self.view.camera = ArcballCamera(name="ArcballCamera")
            # flip y-axis to have correct alignment
            # self.view.camera.flip = (0, 1, 0)

            self.view.camera.viewbox_key_event = viewbox_key_event
            self.viewer.reset_view()
    else:
        # Set 2D camera
        if not isinstance(self.view.camera, PanZoomCamera):
            self.view.camera = PanZoomCamera(aspect=1, name="PanZoomCamera")
            # flip y-axis to have correct alignment
            self.view.camera.flip = (0, 1, 0)

            self.view.camera.viewbox_key_event = viewbox_key_event
            self.viewer.reset_view()
# Buggy code
def screenshot(self):
    """Take currently displayed screen and convert to an image array.

    Returns
    -------
    image : array
        Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the
        upper-left corner of the rendered region.
    """
    img = self.canvas.native.grabFramebuffer()
    return QImg2array(img)


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def screenshot(self):
    """Take currently displayed screen and convert to an image array.

    Returns
    -------
    image : array
        Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the
        upper-left corner of the rendered region.
    """
    img = self.canvas.native.grabFramebuffer()
    b = img.constBits()
    h, w, c = img.height(), img.width(), 4

    # As vispy doesn't use qtpy we need to reconcile the differences
    # between the `QImage` API for `PySide2` and `PyQt5` on how to convert
    # a QImage to a numpy array.
    if API_NAME == "PySide2":
        arr = np.array(b).reshape(h, w, c)
    else:
        b.setsize(h * w * c)
        arr = np.frombuffer(b, np.uint8).reshape(h, w, c)

    # Format of QImage is ARGB32_Premultiplied, but color channels are
    # reversed.
    arr = arr[:, :, [2, 1, 0, 3]]
    return arr
# Buggy code
def _open_images(self):
    """Add image files from the menubar."""
    filenames, _ = QFileDialog.getOpenFileNames(
        parent=self,
        caption="Select image(s)...",
        directory=self._last_visited_dir,  # home dir by default
    )
    if (filenames != []) and (filenames is not None):
        self._add_files(filenames)


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def _open_images(self):
    """Add image files from the menubar."""
    filenames, _ = QFileDialog.getOpenFileNames(
        parent=self,
        caption="Select image(s)...",
        directory=self._last_visited_dir,  # home dir by default
    )
    if filenames is not None:
        self._add_files(filenames)
# Buggy code
def _open_folder(self):
    """Add a folder of files from the menubar."""
    folder = QFileDialog.getExistingDirectory(
        parent=self,
        caption="Select folder...",
        directory=self._last_visited_dir,  # home dir by default
    )
    if folder not in {"", None}:
        self._add_files([folder])


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def _open_folder(self):
    """Add a folder of files from the menubar."""
    folder = QFileDialog.getExistingDirectory(
        parent=self,
        caption="Select folder...",
        directory=self._last_visited_dir,  # home dir by default
    )
    if folder is not None:
        self._add_files([folder])
# Buggy code
def is_pyramid(data):
    """If shape of arrays along first axis is strictly decreasing."""
    size = np.array([np.prod(d.shape) for d in data])
    if len(size) > 1:
        return np.all(size[:-1] > size[1:])
    else:
        return False


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def is_pyramid(data):
    """If shape of arrays along first axis is strictly decreasing."""
    size = np.array([np.prod(d.shape, dtype=np.uint64) for d in data])
    if len(size) > 1:
        return np.all(size[:-1] > size[1:])
    else:
        return False
# Buggy code
def calc_data_range(data):
    """Calculate range of data values. If all values are equal return [0, 1].

    Parameters
    -------
    data : array
        Data to calculate range of values over.

    Returns
    -------
    values : list of float
        Range of values.

    Notes
    -----
    If the data type is uint8, no calculation is performed, and 0-255 is
    returned.
    """
    if data.dtype == np.uint8:
        return [0, 255]
    if np.prod(data.shape) > 1e6:
        # If data is very large take the average of the top, bottom, and
        # middle slices
        bottom_plane_idx = (0,) * (data.ndim - 2)
        middle_plane_idx = tuple(s // 2 for s in data.shape[:-2])
        top_plane_idx = tuple(s - 1 for s in data.shape[:-2])
        idxs = [bottom_plane_idx, middle_plane_idx, top_plane_idx]
        reduced_data = [
            [np.max(data[idx]) for idx in idxs],
            [np.min(data[idx]) for idx in idxs],
        ]
    else:
        reduced_data = data

    min_val = np.min(reduced_data)
    max_val = np.max(reduced_data)

    if min_val == max_val:
        min_val = 0
        max_val = 1
    return [float(min_val), float(max_val)]


# Traceback (AttributeError)
Traceback (most recent call last):

File "<ipython-input-48-ce4a0e063e17>", line 3, in <module>
napari.view_image(pyramid, is_pyramid=True)

File "C:\anaconda3\envs\nap\lib\site-packages\napari\view_layers.py", line 120, in view_image
path=path,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\components\viewer_model.py", line 509, in add_image
visible=visible,

File "C:\anaconda3\envs\nap\lib\site-packages\napari\layers\image\image.py", line 147, in __init__
data, pyramid=is_pyramid, rgb=rgb

File "C:\anaconda3\envs\nap\lib\site-packages\napari\util\misc.py", line 143, in get_pyramid_and_rgb
init_shape = data.shape

AttributeError: 'list' object has no attribute 'shape'

# Fixed code
def calc_data_range(data):
    """Calculate range of data values. If all values are equal return [0, 1].

    Parameters
    -------
    data : array
        Data to calculate range of values over.

    Returns
    -------
    values : list of float
        Range of values.
    """
    if np.prod(data.shape) > 1e6:
        # If data is very large take the average of the top, bottom, and
        # middle slices
        bottom_plane_idx = (0,) * (data.ndim - 2)
        middle_plane_idx = tuple(s // 2 for s in data.shape[:-2])
        top_plane_idx = tuple(s - 1 for s in data.shape[:-2])
        idxs = [bottom_plane_idx, middle_plane_idx, top_plane_idx]
        reduced_data = [
            [np.max(data[idx]) for idx in idxs],
            [np.min(data[idx]) for idx in idxs],
        ]
    else:
        reduced_data = data

    min_val = np.min(reduced_data)
    max_val = np.max(reduced_data)

    if min_val == max_val:
        min_val = 0
        max_val = 1
    return [float(min_val), float(max_val)]
# Buggy code
def __init__(self, layers):
    super().__init__()

    self.layers = layers
    self.setWidgetResizable(True)
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    scrollWidget = QWidget()
    self.setWidget(scrollWidget)
    self.vbox_layout = QVBoxLayout(scrollWidget)
    self.vbox_layout.addWidget(QtDivider())
    self.vbox_layout.addStretch(1)
    self.vbox_layout.setContentsMargins(0, 0, 0, 0)
    self.centers = []
    self.setAcceptDrops(True)
    self.setToolTip("Layer list")

    self.layers.events.added.connect(self._add)
    self.layers.events.removed.connect(self._remove)
    self.layers.events.reordered.connect(self._reorder)

    self.drag_start_position = (0, 0)
    self.drag_name = None


# Traceback (TypeError)
WARNING: Traceback (most recent call last):
File "/Users/kiraevans/Projects/napari/napari/components/_layers_list/view/main.py", line 115, in mouseMoveEvent
distance = (event.pos() - self.drag_start_position).manhattanLength()
TypeError: unsupported operand type(s) for -: 'QPoint' and 'tuple'

# Fixed code
def __init__(self, layers):
    super().__init__()

    self.layers = layers
    self.setWidgetResizable(True)
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    scrollWidget = QWidget()
    self.setWidget(scrollWidget)
    self.vbox_layout = QVBoxLayout(scrollWidget)
    self.vbox_layout.addWidget(QtDivider())
    self.vbox_layout.addStretch(1)
    self.vbox_layout.setContentsMargins(0, 0, 0, 0)
    self.centers = []
    self.setAcceptDrops(True)
    self.setToolTip("Layer list")

    self.layers.events.added.connect(self._add)
    self.layers.events.removed.connect(self._remove)
    self.layers.events.reordered.connect(self._reorder)

    self.drag_start_position = np.zeros(2)
    self.drag_name = None
# Buggy code
def mousePressEvent(self, event):
    # Check if mouse press happens on a layer properties widget or
    # a child of such a widget. If not, the press has happended on the
    # Layers Widget itself and should be ignored.
    widget = self.childAt(event.pos())
    layer = (
        getattr(widget, "layer", None)
        or getattr(widget.parentWidget(), "layer", None)
        or getattr(widget.parentWidget().parentWidget(), "layer", None)
    )

    if layer is not None:
        self.drag_start_position = event.pos()
        self.drag_name = layer.name
    else:
        self.drag_name = None


# Traceback (TypeError)
WARNING: Traceback (most recent call last):
File "/Users/kiraevans/Projects/napari/napari/components/_layers_list/view/main.py", line 115, in mouseMoveEvent
distance = (event.pos() - self.drag_start_position).manhattanLength()
TypeError: unsupported operand type(s) for -: 'QPoint' and 'tuple'

# Fixed code
def mousePressEvent(self, event):
    # Check if mouse press happens on a layer properties widget or
    # a child of such a widget. If not, the press has happended on the
    # Layers Widget itself and should be ignored.
    widget = self.childAt(event.pos())
    layer = (
        getattr(widget, "layer", None)
        or getattr(widget.parentWidget(), "layer", None)
        or getattr(widget.parentWidget().parentWidget(), "layer", None)
    )

    if layer is not None:
        self.drag_start_position = np.array([event.pos().x(), event.pos().y()])
        self.drag_name = layer.name
    else:
        self.drag_name = None
# Buggy code
def mouseMoveEvent(self, event):
    distance = (event.pos() - self.drag_start_position).manhattanLength()
    if distance < QApplication.startDragDistance():
        return
    mimeData = QMimeData()
    mimeData.setText(self.drag_name)
    drag = QDrag(self)
    drag.setMimeData(mimeData)
    drag.setHotSpot(event.pos() - self.rect().topLeft())
    dropAction = drag.exec_()


# Traceback (TypeError)
WARNING: Traceback (most recent call last):
File "/Users/kiraevans/Projects/napari/napari/components/_layers_list/view/main.py", line 115, in mouseMoveEvent
distance = (event.pos() - self.drag_start_position).manhattanLength()
TypeError: unsupported operand type(s) for -: 'QPoint' and 'tuple'

# Fixed code
def mouseMoveEvent(self, event):
    position = np.array([event.pos().x(), event.pos().y()])
    distance = np.linalg.norm(position - self.drag_start_position)
    if distance < QApplication.startDragDistance() or self.drag_name is None:
        return
    mimeData = QMimeData()
    mimeData.setText(self.drag_name)
    drag = QDrag(self)
    drag.setMimeData(mimeData)
    drag.setHotSpot(event.pos() - self.rect().topLeft())
    dropAction = drag.exec_()
# Buggy code
def dragEnterEvent(self, event):
    divs = []
    for i in range(0, self.vbox_layout.count(), 2):
        widget = self.vbox_layout.itemAt(i).widget()
        divs.append(widget.y() + widget.frameGeometry().height() / 2)
    self.centers = [(divs[i + 1] + divs[i]) / 2 for i in range(len(divs) - 1)]
    event.accept()


# Traceback (TypeError)
WARNING: Traceback (most recent call last):
File "/Users/kiraevans/Projects/napari/napari/components/_layers_list/view/main.py", line 115, in mouseMoveEvent
distance = (event.pos() - self.drag_start_position).manhattanLength()
TypeError: unsupported operand type(s) for -: 'QPoint' and 'tuple'

# Fixed code
def dragEnterEvent(self, event):
    if event.source() == self:
        event.accept()
        divs = []
        for i in range(0, self.vbox_layout.count(), 2):
            widget = self.vbox_layout.itemAt(i).widget()
            divs.append(widget.y() + widget.frameGeometry().height() / 2)
        self.centers = [(divs[i + 1] + divs[i]) / 2 for i in range(len(divs) - 1)]
    else:
        event.ignore()
# Buggy code
def clim(self, clim):
    self._clim_msg = f"{clim[0]: 0.3}, {clim[1]: 0.3}"
    self.status = self._clim_msg
    self._node.clim = clim
    self.events.clim()


# Traceback (ValueError)
from napari import Window, Viewer
viewer = Viewer()
window = Window(viewer)
viewer.add_image(data.camera())
viewer.layers[0].clim = [0, 255]

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-4d36bc0c2b58> in <module>()
----> 1 viewer.layers[0].clim = [0, 255]

~/Github/napari/napari/layers/_image_layer/model.py in clim(self, clim)
265     @clim.setter
266     def clim(self, clim):
--> 267         self._clim_msg = f'{clim[0]: 0.3}, {clim[1]: 0.3}'
268         self.status = self._clim_msg
269         self._node.clim = clim

ValueError: Precision not allowed in integer format specifier

# Fixed code
def clim(self, clim):
    self._clim_msg = f"{float(clim[0]): 0.3}, {float(clim[1]): 0.3}"
    self.status = self._clim_msg
    self._node.clim = clim
    self.events.clim()
# Buggy code
def screenshot(self, region=None, size=None, bgcolor=None, crop=None):
    """Render the scene to an offscreen buffer and return the image array.

    Parameters
    ----------
    region : tuple | None
        Specifies the region of the canvas to render. Format is
        (x, y, w, h). By default, the entire canvas is rendered.
    size : tuple | None
        Specifies the size of the image array to return. If no size is
        given, then the size of the *region* is used, multiplied by the
        pixel scaling factor of the canvas (see `pixel_scale`). This
        argument allows the scene to be rendered at resolutions different
        from the native canvas resolution.
    bgcolor : instance of Color | None
        The background color to use.
    crop : array-like | None
        If specified it determines the pixels read from the framebuffer.
        In the format (x, y, w, h), relative to the region being rendered.
    Returns
    -------
    image : array
        Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the
        upper-left corner of the rendered region.

    """
    return self._canvas.render(region=None, size=None, bgcolor=None, crop=None)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-1db5616997f4> in <module>()
----> 1 viewer.screenshot()

~/Github/napari/napari/components/_viewer/model.py in screenshot(self, region, size, bgcolor, crop)
156         """
157         return self._canvas.render(region=None, size=None, bgcolor=None,
--> 158                                    crop=None)
159
160     def add_layer(self, layer):

TypeError: render() got an unexpected keyword argument 'crop'

# Fixed code
def screenshot(self, region=None, size=None, bgcolor=None):
    """Render the scene to an offscreen buffer and return the image array.

    Parameters
    ----------
    region : tuple | None
        Specifies the region of the canvas to render. Format is
        (x, y, w, h). By default, the entire canvas is rendered.
    size : tuple | None
        Specifies the size of the image array to return. If no size is
        given, then the size of the *region* is used, multiplied by the
        pixel scaling factor of the canvas (see `pixel_scale`). This
        argument allows the scene to be rendered at resolutions different
        from the native canvas resolution.
    bgcolor : instance of Color | None
        The background color to use.

    Returns
    -------
    image : array
        Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the
        upper-left corner of the rendered region.
    """
    return self._canvas.render(region, size, bgcolor)
# Buggy code
def get_arena(self, arena_addr=None):
    """Read a malloc_state struct from the specified address, default to
    reading the current thread's arena. Return the main arena if the
    current thread is not attached to an arena.
    """
    if arena_addr is None:
        if self.multithreaded:
            arena_addr = pwndbg.memory.u(pwndbg.symbol.address("thread_arena"))
            if arena_addr != 0:
                return pwndbg.memory.poi(self.malloc_state, arena_addr)

        return self.main_arena

    try:
        return pwndbg.memory.poi(self.malloc_state, arena_addr)
    except gdb.MemoryError:
        # print(message.warn('Bad arena address {}'.format(arena_addr.address)))
        return None


# Traceback (gdb.MemoryError)
pwndbg> find_fake_fast &amp;__malloc_hook
FAKE CHUNKS
Traceback (most recent call last):
File "/home/ubuntu/pwndbg/pwndbg/commands/__init__.py", line 136, in __call__
return self.function(*args, **kwargs)
File "/home/ubuntu/pwndbg/pwndbg/commands/__init__.py", line 227, in _OnlyWhenRunning
return function(*a, **kw)
File "/home/ubuntu/pwndbg/pwndbg/commands/__init__.py", line 265, in _OnlyWithLibcDebugSyms
return function(*a, **kw)
File "/home/ubuntu/pwndbg/pwndbg/commands/__init__.py", line 245, in _OnlyWhenHeapIsInitialized
return function(*a, **kw)
File "/home/ubuntu/pwndbg/pwndbg/commands/heap.py", line 279, in malloc_chunk
if cursor == top_chunk:
gdb.MemoryError: Cannot access memory at address 0x30d7080900003131

# Fixed code
def get_arena(self, arena_addr=None):
    """Read a malloc_state struct from the specified address, default to
    reading the current thread's arena. Return the main arena if the
    current thread is not attached to an arena.
    """
    if arena_addr is None:
        if self.multithreaded:
            arena_addr = pwndbg.memory.u(pwndbg.symbol.address("thread_arena"))
            if arena_addr != 0:
                return pwndbg.memory.poi(self.malloc_state, arena_addr)

        return self.main_arena

    try:
        next(i for i in pwndbg.vmmap.get() if arena_addr in i)
        return pwndbg.memory.poi(self.malloc_state, arena_addr)
    except (gdb.MemoryError, StopIteration):
        # print(message.warn('Bad arena address {}'.format(arena_addr.address)))
        return None
# Buggy code
def get_containing_segments(elf_filepath, elf_loadaddr, vaddr):
    elf = get_elf_info_rebased(elf_filepath, elf_loadaddr)
    segments = []
    for seg in elf.segments:
        # disregard non-LOAD segments that are not file-backed (typically STACK)
        if "LOAD" not in seg["p_type"] and seg["p_filesz"] == 0:
            continue
        # disregard segments not containing vaddr
        if vaddr < seg["p_vaddr"] or vaddr >= seg["x_vaddr_mem_end"]:
            continue
        segments.append(dict(seg))
    return segments


# Traceback (TypeError)
pwndbg> set exception-verbose on
Set whether to print a full stacktracefor exceptions raised in Pwndbg commands to True
pwndbg> xinfo 0x7ffff7e33e10
Extended information for virtual address 0x7ffff7e33e10:

Containing mapping:
0x7ffff7df4000     0x7ffff7f6c000 r-xp   178000 25000  /usr/lib/x86_64-linux-gnu/libc-2.31.so

Offset information:
Mapped Area 0x7ffff7e33e10 = 0x7ffff7df4000 + 0x3fe10
File (Base) 0x7ffff7e33e10 = 0x7ffff7dcf000 + 0x64e10
'xinfo': Shows offsets of the specified address to useful other locations
Traceback (most recent call last):
File "/opt/pwndbg/pwndbg/commands/__init__.py", line 136, in __call__
return self.function(*args, **kwargs)
File "/opt/pwndbg/pwndbg/commands/__init__.py", line 227, in _OnlyWhenRunning
return function(*a, **kw)
File "/opt/pwndbg/pwndbg/commands/xinfo.py", line 126, in xinfo
xinfo_mmap_file(page, addr)
File "/opt/pwndbg/pwndbg/commands/xinfo.py", line 72, in xinfo_mmap_file
containing_loads = [seg for seg in pwndbg.elf.get_containing_segments(file_name, first.vaddr, addr)
File "/opt/pwndbg/pwndbg/elf.py", line 153, in get_containing_segments
if 'LOAD' not in seg['p_type'] and seg['p_filesz'] == 0:
TypeError: argument of type 'int' is not iterable

# Fixed code
def get_containing_segments(elf_filepath, elf_loadaddr, vaddr):
    elf = get_elf_info_rebased(elf_filepath, elf_loadaddr)
    segments = []
    for seg in elf.segments:
        # disregard segments which were unable to be named by pyelftools (see #777)
        # and non-LOAD segments that are not file-backed (typically STACK)
        if isinstance(seg["p_type"], int) or (
            "LOAD" not in seg["p_type"] and seg["p_filesz"] == 0
        ):
            continue
        # disregard segments not containing vaddr
        if vaddr < seg["p_vaddr"] or vaddr >= seg["x_vaddr_mem_end"]:
            continue
        segments.append(dict(seg))
    return segments
# Buggy code
def __getattr__(self, attr):
    attr = attr.lstrip("$")
    try:
        # Seriously, gdb? Only accepts uint32.
        if "eflags" in attr:
            value = gdb77_get_register(attr)
            value = value.cast(pwndbg.typeinfo.uint32)
        else:
            if attr.lower() == "xpsr":
                attr = "xPSR"
            value = get_register(attr)
            value = value.cast(pwndbg.typeinfo.ptrdiff)

        value = int(value)
        return value & pwndbg.arch.ptrmask
    except (ValueError, gdb.error):
        return None


# Traceback (TypeError)
0x0000005578b133a4 in memcmp@plt ()
'context': Print out the current register, instruction, and stack context.
Traceback (most recent call last):
File "/root/Pwn/Tools/pwndbg/pwndbg/commands/__init__.py", line 136, in __call__
return self.function(*args, **kwargs)
File "/root/Pwn/Tools/pwndbg/pwndbg/commands/__init__.py", line 227, in _OnlyWhenRunning
return function(*a, **kw)
File "/root/Pwn/Tools/pwndbg/pwndbg/commands/context.py", line 112, in context
result.extend(func())
File "/root/Pwn/Tools/pwndbg/pwndbg/commands/context.py", line 127, in context_regs
return [pwndbg.ui.banner("registers")] + get_regs()
File "/root/Pwn/Tools/pwndbg/pwndbg/commands/context.py", line 176, in get_regs
desc = pwndbg.chain.format(value)
File "/root/Pwn/Tools/pwndbg/pwndbg/chain.py", line 122, in format
enhanced = pwndbg.enhance.enhance(chain[-2] + offset, code=code)
File "/root/Pwn/Tools/pwndbg/pwndbg/enhance.py", line 102, in enhance
instr = pwndbg.disasm.one(value)
File "/root/Pwn/Tools/pwndbg/pwndbg/disasm/__init__.py", line 118, in one
for insn in get(address, 1):
File "/root/Pwn/Tools/pwndbg/pwndbg/disasm/__init__.py", line 138, in get
i = get_one_instruction(address)
File "/root/Pwn/Tools/pwndbg/pwndbg/memoize.py", line 48, in __call__
value = self.func(*args, **kwargs)
File "/root/Pwn/Tools/pwndbg/pwndbg/disasm/__init__.py", line 106, in get_one_instruction
md   = get_disassembler(address)
File "/root/Pwn/Tools/pwndbg/pwndbg/disasm/__init__.py", line 88, in get_disassembler
extra = CS_MODE_THUMB if (pwndbg.regs.cpsr &amp; (1<<5)) else CS_MODE_ARM
TypeError: unsupported operand type(s) for &amp;: 'NoneType' and 'int'

# Fixed code
def __getattr__(self, attr):
    attr = attr.lstrip("$")
    try:
        # Seriously, gdb? Only accepts uint32.
        if "eflags" in attr or "cpsr" in attr:
            value = gdb77_get_register(attr)
            value = value.cast(pwndbg.typeinfo.uint32)
        else:
            if attr.lower() == "xpsr":
                attr = "xPSR"
            value = get_register(attr)
            value = value.cast(pwndbg.typeinfo.ptrdiff)

        value = int(value)
        return value & pwndbg.arch.ptrmask
    except (ValueError, gdb.error):
        return None
# Buggy code
def get_raw_out():
    local_path = pwndbg.file.get_file(pwndbg.proc.exe)
    cmd = [get_raw_out.cmd_path, "--file", local_path]
    return pwndbg.wrappers.call_cmd(cmd)


# Traceback (subprocess.CalledProcessError)
pwndbg> checksec
Traceback (most recent call last):
File "/root/pwndbg/pwndbg/commands/__init__.py", line 109, in __call__
return self.function(*args, **kwargs)
File "/root/pwndbg/pwndbg/commands/__init__.py", line 189, in _OnlyWithFile
return function(*a, **kw)
File "/root/pwndbg/pwndbg/commands/checksec.py", line 16, in checksec
print(pwndbg.wrappers.checksec.get_raw_out())
File "/root/pwndbg/pwndbg/commands/__init__.py", line 189, in _OnlyWithFile
return function(*a, **kw)
File "/root/pwndbg/pwndbg/wrappers/__init__.py", line 28, in _OnlyWithCommand
return function(*a, **kw)
File "/root/pwndbg/pwndbg/memoize.py", line 48, in __call__
value = self.func(*args, **kwargs)
File "/root/pwndbg/pwndbg/wrappers/checksec.py", line 20, in get_raw_out
return pwndbg.wrappers.call_cmd(cmd)
File "/root/pwndbg/pwndbg/wrappers/__init__.py", line 35, in call_cmd
return subprocess.check_output(cmd, stderr=STDOUT).decode('utf-8')
File "/usr/lib/python3.7/subprocess.py", line 395, in check_output
**kwargs).stdout
File "/usr/lib/python3.7/subprocess.py", line 487, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['/usr/local/bin/checksec', '--file', '/tmp/forgot']' returned non-zero exit status 2.

# Fixed code
def get_raw_out():
    local_path = pwndbg.file.get_file(pwndbg.proc.exe)
    try:
        version_output = subprocess.check_output(
            [get_raw_out.cmd_path, "--version"], stderr=STDOUT
        ).decode("utf-8")
        match = search("checksec v([\\w.]+),", version_output)
        if match:
            version = tuple(map(int, (match.group(1).split("."))))
            if version >= (2, 0):
                return pwndbg.wrappers.call_cmd(
                    [get_raw_out.cmd_path, "--file=" + local_path]
                )
    except Exception:
        pass
    return pwndbg.wrappers.call_cmd([get_raw_out.cmd_path, "--file", local_path])
# Buggy code
def exe(self):
    for obj in gdb.objfiles():
        if obj.filename:
            return obj.filename
        break
    if self.alive:
        auxv = pwndbg.auxv.get()
        return auxv["AT_EXECFN"]


# Traceback (OSError)
pwndbg> got
Traceback (most recent call last):
File "/home/mzr/sources/pwndbg/pwndbg/commands/__init__.py", line 135,
in __call__
return self.function(*args, **kwargs)
File "/home/mzr/sources/pwndbg/pwndbg/commands/__init__.py", line 226,
in _OnlyWhenRunning
return function(*a, **kw)
File "/home/mzr/sources/pwndbg/pwndbg/commands/got.py", line 28, in got
relro_status = pwndbg.wrappers.checksec.relro_status()
File "/home/mzr/sources/pwndbg/pwndbg/commands/__init__.py", line 215,
in _OnlyWithFile
return function(*a, **kw)
File "/home/mzr/sources/pwndbg/pwndbg/wrappers/__init__.py", line 28, i
n _OnlyWithCommand
return function(*a, **kw)
File "/home/mzr/sources/pwndbg/pwndbg/wrappers/checksec.py", line 25, i
n relro_status
out = get_raw_out()
File "/home/mzr/sources/pwndbg/pwndbg/commands/__init__.py", line 215,
in _OnlyWithFile
return function(*a, **kw)
File "/home/mzr/sources/pwndbg/pwndbg/wrappers/__init__.py", line 28, i
n _OnlyWithCommand
return function(*a, **kw)
File "/home/mzr/sources/pwndbg/pwndbg/memoize.py", line 48, in __call__
value = self.func(*args, **kwargs)
File "/home/mzr/sources/pwndbg/pwndbg/wrappers/checksec.py", line 18, i
n get_raw_out
local_path = pwndbg.file.get_file(pwndbg.proc.exe)
File "/home/mzr/sources/pwndbg/pwndbg/file.py", line 48, in get_file
"Error: %s" % (path, error))
OSError: Could not download remote file 'target:/lib64/ld-linux-x86-64.so
.2':
Error: Remote I/O error: No such file or directory

# Fixed code
def exe(self):
    return gdb.current_progspace().filename
# Buggy code
def get_set_string(self):
    value = self.raw_value

    # For string value, convert utf8 byte string to unicode.
    if isinstance(value, six.binary_type):
        value = codecs.decode(value, "utf-8")

    # Remove surrounded ' and " characters
    if isinstance(value, six.string_types):
        # The first character must be ' or " and ends with the same character.
        # See PR #404 for more information
        pattern = r"^(?P<quote>[\"'])(?P<content>.*?)(?P=quote)$"

        value = re.sub(pattern, r"\g<content>", value)

    # Write back to self.value
    self.value = value

    for trigger in triggers[self.name]:
        trigger()

    return "Set %s to %r" % (self.docstring, self.value)


# Traceback (InterruptedError)
[!] Ida Pro xmlrpc error
Traceback (most recent call last):
File "/mnt/d/Uni/SS18/exploits/pwndbg/pwndbg/pwndbg/ida.py", line 64, in init_ida_rpc_client
_ida.here()
File "/usr/lib/python3.4/xmlrpc/client.py", line 1098, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1437, in __request
verbose=self.__verbose
File "/usr/lib/python3.4/xmlrpc/client.py", line 1140, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1152, in single_request
http_conn = self.send_request(host, handler, request_body, verbose)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1264, in send_request
self.send_content(connection, request_body)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1294, in send_content
connection.endheaders(request_body)
File "/usr/lib/python3.4/http/client.py", line 1121, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.4/http/client.py", line 951, in _send_output
self.send(msg)
File "/usr/lib/python3.4/http/client.py", line 886, in send
self.connect()
File "/usr/lib/python3.4/http/client.py", line 863, in connect
self.timeout, self.source_address)
File "/usr/lib/python3.4/socket.py", line 512, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 503, in create_connection
sock.connect(sa)
InterruptedError: [Errno 4] Unterbrechung während des Betriebssystemaufrufs

# Fixed code
def get_set_string(self):
    value = self.raw_value

    # For string value, convert utf8 byte string to unicode.
    if isinstance(value, six.binary_type):
        value = codecs.decode(value, "utf-8")

    # Remove surrounded ' and " characters
    if isinstance(value, six.string_types):
        # The first character must be ' or " and ends with the same character.
        # See PR #404 for more information
        pattern = r"^(?P<quote>[\"'])(?P<content>.*?)(?P=quote)$"

        value = re.sub(pattern, r"\g<content>", value)

    # Write back to self.value
    self.value = value

    for trigger in triggers[self.name]:
        trigger()

    if not pwndbg.decorators.first_prompt:
        # Remove the newline that gdb adds automatically
        return "\b"
    return "Set %s to %r" % (self.docstring, self.value)
# Buggy code
def __call__(self, *args, **kwargs):
    if not ida_enabled:
        return None
    if _ida is None:
        init_ida_rpc_client()
    if _ida is not None:
        return self.fn(*args, **kwargs)
    return None


# Traceback (InterruptedError)
[!] Ida Pro xmlrpc error
Traceback (most recent call last):
File "/mnt/d/Uni/SS18/exploits/pwndbg/pwndbg/pwndbg/ida.py", line 64, in init_ida_rpc_client
_ida.here()
File "/usr/lib/python3.4/xmlrpc/client.py", line 1098, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1437, in __request
verbose=self.__verbose
File "/usr/lib/python3.4/xmlrpc/client.py", line 1140, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1152, in single_request
http_conn = self.send_request(host, handler, request_body, verbose)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1264, in send_request
self.send_content(connection, request_body)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1294, in send_content
connection.endheaders(request_body)
File "/usr/lib/python3.4/http/client.py", line 1121, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.4/http/client.py", line 951, in _send_output
self.send(msg)
File "/usr/lib/python3.4/http/client.py", line 886, in send
self.connect()
File "/usr/lib/python3.4/http/client.py", line 863, in connect
self.timeout, self.source_address)
File "/usr/lib/python3.4/socket.py", line 512, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 503, in create_connection
sock.connect(sa)
InterruptedError: [Errno 4] Unterbrechung während des Betriebssystemaufrufs

# Fixed code
def __call__(self, *args, **kwargs):
    if _ida is None:
        init_ida_rpc_client()
    if _ida is not None:
        return self.fn(*args, **kwargs)
    return None
# Buggy code
def prompt_hook(*a):
    global cur
    new = (gdb.selected_inferior(), gdb.selected_thread())

    if cur != new:
        pwndbg.events.after_reload(start=False)
        cur = new

    if pwndbg.proc.alive and pwndbg.proc.thread_is_stopped:
        prompt_hook_on_stop(*a)


# Traceback (InterruptedError)
[!] Ida Pro xmlrpc error
Traceback (most recent call last):
File "/mnt/d/Uni/SS18/exploits/pwndbg/pwndbg/pwndbg/ida.py", line 64, in init_ida_rpc_client
_ida.here()
File "/usr/lib/python3.4/xmlrpc/client.py", line 1098, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1437, in __request
verbose=self.__verbose
File "/usr/lib/python3.4/xmlrpc/client.py", line 1140, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1152, in single_request
http_conn = self.send_request(host, handler, request_body, verbose)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1264, in send_request
self.send_content(connection, request_body)
File "/usr/lib/python3.4/xmlrpc/client.py", line 1294, in send_content
connection.endheaders(request_body)
File "/usr/lib/python3.4/http/client.py", line 1121, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.4/http/client.py", line 951, in _send_output
self.send(msg)
File "/usr/lib/python3.4/http/client.py", line 886, in send
self.connect()
File "/usr/lib/python3.4/http/client.py", line 863, in connect
self.timeout, self.source_address)
File "/usr/lib/python3.4/socket.py", line 512, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 503, in create_connection
sock.connect(sa)
InterruptedError: [Errno 4] Unterbrechung während des Betriebssystemaufrufs

# Fixed code
def prompt_hook(*a):
    global cur
    pwndbg.decorators.first_prompt = True

    new = (gdb.selected_inferior(), gdb.selected_thread())

    if cur != new:
        pwndbg.events.after_reload(start=False)
        cur = new

    if pwndbg.proc.alive and pwndbg.proc.thread_is_stopped:
        prompt_hook_on_stop(*a)
# Buggy code
def entry(*a):
    """
    Set a breakpoint at the first instruction executed in
    the target binary.
    """
    global break_on_first_instruction
    break_on_first_instruction = True
    run = "run " + " ".join(a)
    gdb.execute(run, from_tty=False)


# Traceback (gdb.error)
[dc@dc:pwndbg|dev *$%]$ gdb python
Loaded 113 commands. Type pwndbg [filter] for a list.
Reading symbols from python...(no debugging symbols found)...done.
pwndbg> set exception-verbose on
Set whether to print a full stacktracefor exceptions raised in Pwndbg commands to True
pwndbg> run -c "print(1); print(2)"
Starting program: /usr/bin/python -c "print(1); print(2)"
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
1
2
[Inferior 1 (process 20590) exited normally]
pwndbg> entry -c "print(1); print(2)"
('-c', 'print(1); print(2)')
Running '%s' run -c print(1); print(2)
/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `exec /usr/bin/python -c print(1); print(2)'
Traceback (most recent call last):
File "/home/dc/installed/pwndbg/pwndbg/commands/__init__.py", line 100, in __call__
return self.function(*args, **kwargs)
File "/home/dc/installed/pwndbg/pwndbg/commands/__init__.py", line 181, in _OnlyWithFile
return function(*a, **kw)
File "/home/dc/installed/pwndbg/pwndbg/commands/start.py", line 72, in entry
gdb.execute(run, from_tty=False)
gdb.error: During startup program exited with code 1.

If that is an issue, you can report it on https://github.com/pwndbg/pwndbg/issues
(Please don't forget to search if it hasn't been reported before)
PS: Pull requests are welcome

# Fixed code
def entry(*a):
    """
    Set a breakpoint at the first instruction executed in
    the target binary.
    """
    global break_on_first_instruction
    break_on_first_instruction = True
    run = "run " + " ".join(map(shlex.quote, a))
    gdb.execute(run, from_tty=False)