after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def console(self, console): self._console = console self.dockConsole.widget = console self._update_palette()
def console(self, console): self._console = console self.dockConsole.widget = console self._update_palette(None)
https://github.com/napari/napari/issues/1079
Traceback (most recent call last): File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 418, in _toggle_theme self.theme = theme_names[(cur_theme + 1) % len(theme_names)] File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 130, in theme self.palette = self.themes[theme] File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 114, in palette self.events.palette() File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/Users/gbokota/Documents/projekty/napari/napari/_qt/qt_main_window.py", line 99, in <lambda> lambda event: self._update_palette(event.palette) AttributeError: 'Event' object has no attribute 'palette'
AttributeError
def _update_palette(self, event=None): """Update the napari GUI theme.""" # template and apply the primary stylesheet themed_stylesheet = template(self.raw_stylesheet, **self.viewer.palette) if self._console is not None: self.console._update_palette(self.viewer.palette, themed_stylesheet) self.setStyleSheet(themed_stylesheet) self.canvas.bgcolor = self.viewer.palette["canvas"]
def _update_palette(self, event): """Update the napari GUI theme.""" # template and apply the primary stylesheet themed_stylesheet = template(self.raw_stylesheet, **self.viewer.palette) if self._console is not None: self.console._update_palette(self.viewer.palette, themed_stylesheet) self.setStyleSheet(themed_stylesheet) self.canvas.bgcolor = self.viewer.palette["canvas"]
https://github.com/napari/napari/issues/1079
Traceback (most recent call last): File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 418, in _toggle_theme self.theme = theme_names[(cur_theme + 1) % len(theme_names)] File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 130, in theme self.palette = self.themes[theme] File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 114, in palette self.events.palette() File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/Users/gbokota/Documents/projekty/napari/napari/_qt/qt_main_window.py", line 99, in <lambda> lambda event: self._update_palette(event.palette) AttributeError: 'Event' object has no attribute 'palette'
AttributeError
def toggle_console_visibility(self, event=None): """Toggle console visible and not visible. Imports the console the first time it is requested. """ # force instantiation of console if not already instantiated _ = self.console viz = not self.dockConsole.isVisible() # modulate visibility at the dock widget level as console is docakable self.dockConsole.setVisible(viz) if self.dockConsole.isFloating(): self.dockConsole.setFloating(True) self.viewerButtons.consoleButton.setProperty( "expanded", self.dockConsole.isVisible() ) self.viewerButtons.consoleButton.style().unpolish(self.viewerButtons.consoleButton) self.viewerButtons.consoleButton.style().polish(self.viewerButtons.consoleButton)
def toggle_console_visibility(self, event): """Toggle console visible and not visible. Imports the console the first time it is requested. """ # force instantiation of console if not already instantiated _ = self.console viz = not self.dockConsole.isVisible() # modulate visibility at the dock widget level as console is docakable self.dockConsole.setVisible(viz) if self.dockConsole.isFloating(): self.dockConsole.setFloating(True) self.viewerButtons.consoleButton.setProperty( "expanded", self.dockConsole.isVisible() ) self.viewerButtons.consoleButton.style().unpolish(self.viewerButtons.consoleButton) self.viewerButtons.consoleButton.style().polish(self.viewerButtons.consoleButton)
https://github.com/napari/napari/issues/1079
Traceback (most recent call last): File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 418, in _toggle_theme self.theme = theme_names[(cur_theme + 1) % len(theme_names)] File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 130, in theme self.palette = self.themes[theme] File "/Users/gbokota/Documents/projekty/napari/napari/components/viewer_model.py", line 114, in palette self.events.palette() File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/Users/gbokota/Documents/projekty/napari/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/Users/gbokota/Documents/projekty/napari/napari/_qt/qt_main_window.py", line 99, in <lambda> lambda event: self._update_palette(event.palette) AttributeError: 'Event' object has no attribute 'palette'
AttributeError
def __init__(self, layer): super().__init__(layer) self.layer.events.mode.connect(self.set_mode) self.layer.events.n_dimensional.connect(self._on_n_dim_change) self.layer.events.symbol.connect(self._on_symbol_change) self.layer.events.size.connect(self._on_size_change) self.layer.events.current_edge_color.connect(self._on_edge_color_change) self.layer.events.current_face_color.connect(self._on_face_color_change) self.layer.events.editable.connect(self._on_editable_change) sld = QSlider(Qt.Horizontal) sld.setFocusPolicy(Qt.NoFocus) sld.setMinimum(1) sld.setMaximum(100) sld.setSingleStep(1) value = self.layer.current_size sld.setValue(int(value)) sld.valueChanged.connect(self.changeSize) self.sizeSlider = sld face_comboBox = QComboBox() face_comboBox.addItems(self.layer._colors) face_comboBox.activated[str].connect(self.changeFaceColor) self.faceComboBox = face_comboBox self.faceColorSwatch = QFrame() self.faceColorSwatch.setObjectName("swatch") self.faceColorSwatch.setToolTip("Face color swatch") self._on_face_color_change() edge_comboBox = QComboBox() edge_comboBox.addItems(self.layer._colors) edge_comboBox.activated[str].connect(self.changeEdgeColor) self.edgeComboBox = edge_comboBox self.edgeColorSwatch = QFrame() self.edgeColorSwatch.setObjectName("swatch") self.edgeColorSwatch.setToolTip("Edge color swatch") self._on_edge_color_change() symbol_comboBox = QComboBox() symbol_comboBox.addItems([str(s) for s in Symbol]) index = symbol_comboBox.findText(self.layer.symbol, Qt.MatchFixedString) symbol_comboBox.setCurrentIndex(index) symbol_comboBox.activated[str].connect(self.changeSymbol) self.symbolComboBox = symbol_comboBox ndim_cb = QCheckBox() ndim_cb.setToolTip("N-dimensional points") ndim_cb.setChecked(self.layer.n_dimensional) ndim_cb.stateChanged.connect(self.change_ndim) self.ndimCheckBox = ndim_cb self.select_button = QtModeRadioButton( layer, "select_points", Mode.SELECT, tooltip="Select points" ) self.addition_button = QtModeRadioButton( layer, "add_points", Mode.ADD, tooltip="Add points" ) self.panzoom_button = QtModeRadioButton( layer, "pan_zoom", Mode.PAN_ZOOM, tooltip="Pan/zoom", checked=True ) self.delete_button = QtModePushButton( layer, "delete_shape", slot=self.layer.remove_selected, tooltip="Delete selected points", ) self.button_group = QButtonGroup(self) self.button_group.addButton(self.select_button) self.button_group.addButton(self.addition_button) self.button_group.addButton(self.panzoom_button) button_row = QHBoxLayout() button_row.addWidget(self.delete_button) button_row.addWidget(self.addition_button) button_row.addWidget(self.select_button) button_row.addWidget(self.panzoom_button) button_row.addStretch(1) button_row.setSpacing(4) # grid_layout created in QtLayerControls # addWidget(widget, row, column, [row_span, column_span]) self.grid_layout.addLayout(button_row, 0, 1, 1, 2) self.grid_layout.addWidget(QLabel("opacity:"), 1, 0) self.grid_layout.addWidget(self.opacitySlider, 1, 1, 1, 2) self.grid_layout.addWidget(QLabel("point size:"), 2, 0) self.grid_layout.addWidget(self.sizeSlider, 2, 1, 1, 2) self.grid_layout.addWidget(QLabel("blending:"), 3, 0) self.grid_layout.addWidget(self.blendComboBox, 3, 1, 1, 2) self.grid_layout.addWidget(QLabel("symbol:"), 4, 0) self.grid_layout.addWidget(self.symbolComboBox, 4, 1, 1, 2) self.grid_layout.addWidget(QLabel("face color:"), 5, 0) self.grid_layout.addWidget(self.faceComboBox, 5, 2) self.grid_layout.addWidget(self.faceColorSwatch, 5, 1) self.grid_layout.addWidget(QLabel("edge color:"), 6, 0) self.grid_layout.addWidget(self.edgeComboBox, 6, 2) self.grid_layout.addWidget(self.edgeColorSwatch, 6, 1) self.grid_layout.addWidget(QLabel("n-dim:"), 7, 0) self.grid_layout.addWidget(self.ndimCheckBox, 7, 1) self.grid_layout.setRowStretch(8, 1) self.grid_layout.setColumnStretch(1, 1) self.grid_layout.setSpacing(4)
def __init__(self, layer): super().__init__(layer) self.layer.events.mode.connect(self.set_mode) self.layer.events.n_dimensional.connect(self._on_n_dim_change) self.layer.events.symbol.connect(self._on_symbol_change) self.layer.events.size.connect(self._on_size_change) self.layer.events.edge_color.connect(self._on_edge_color_change) self.layer.events.face_color.connect(self._on_face_color_change) self.layer.events.editable.connect(self._on_editable_change) sld = QSlider(Qt.Horizontal) sld.setFocusPolicy(Qt.NoFocus) sld.setMinimum(1) sld.setMaximum(100) sld.setSingleStep(1) value = self.layer.current_size sld.setValue(int(value)) sld.valueChanged.connect(self.changeSize) self.sizeSlider = sld face_comboBox = QComboBox() face_comboBox.addItems(self.layer._colors) face_comboBox.activated[str].connect(self.changeFaceColor) self.faceComboBox = face_comboBox self.faceColorSwatch = QFrame() self.faceColorSwatch.setObjectName("swatch") self.faceColorSwatch.setToolTip("Face color swatch") self._on_face_color_change() edge_comboBox = QComboBox() edge_comboBox.addItems(self.layer._colors) edge_comboBox.activated[str].connect(self.changeEdgeColor) self.edgeComboBox = edge_comboBox self.edgeColorSwatch = QFrame() self.edgeColorSwatch.setObjectName("swatch") self.edgeColorSwatch.setToolTip("Edge color swatch") self._on_edge_color_change() symbol_comboBox = QComboBox() symbol_comboBox.addItems([str(s) for s in Symbol]) index = symbol_comboBox.findText(self.layer.symbol, Qt.MatchFixedString) symbol_comboBox.setCurrentIndex(index) symbol_comboBox.activated[str].connect(self.changeSymbol) self.symbolComboBox = symbol_comboBox ndim_cb = QCheckBox() ndim_cb.setToolTip("N-dimensional points") ndim_cb.setChecked(self.layer.n_dimensional) ndim_cb.stateChanged.connect(self.change_ndim) self.ndimCheckBox = ndim_cb self.select_button = QtModeRadioButton( layer, "select_points", Mode.SELECT, tooltip="Select points" ) self.addition_button = QtModeRadioButton( layer, "add_points", Mode.ADD, tooltip="Add points" ) self.panzoom_button = QtModeRadioButton( layer, "pan_zoom", Mode.PAN_ZOOM, tooltip="Pan/zoom", checked=True ) self.delete_button = QtModePushButton( layer, "delete_shape", slot=self.layer.remove_selected, tooltip="Delete selected points", ) self.button_group = QButtonGroup(self) self.button_group.addButton(self.select_button) self.button_group.addButton(self.addition_button) self.button_group.addButton(self.panzoom_button) button_row = QHBoxLayout() button_row.addWidget(self.delete_button) button_row.addWidget(self.addition_button) button_row.addWidget(self.select_button) button_row.addWidget(self.panzoom_button) button_row.addStretch(1) button_row.setSpacing(4) # grid_layout created in QtLayerControls # addWidget(widget, row, column, [row_span, column_span]) self.grid_layout.addLayout(button_row, 0, 1, 1, 2) self.grid_layout.addWidget(QLabel("opacity:"), 1, 0) self.grid_layout.addWidget(self.opacitySlider, 1, 1, 1, 2) self.grid_layout.addWidget(QLabel("point size:"), 2, 0) self.grid_layout.addWidget(self.sizeSlider, 2, 1, 1, 2) self.grid_layout.addWidget(QLabel("blending:"), 3, 0) self.grid_layout.addWidget(self.blendComboBox, 3, 1, 1, 2) self.grid_layout.addWidget(QLabel("symbol:"), 4, 0) self.grid_layout.addWidget(self.symbolComboBox, 4, 1, 1, 2) self.grid_layout.addWidget(QLabel("face color:"), 5, 0) self.grid_layout.addWidget(self.faceComboBox, 5, 2) self.grid_layout.addWidget(self.faceColorSwatch, 5, 1) self.grid_layout.addWidget(QLabel("edge color:"), 6, 0) self.grid_layout.addWidget(self.edgeComboBox, 6, 2) self.grid_layout.addWidget(self.edgeColorSwatch, 6, 1) self.grid_layout.addWidget(QLabel("n-dim:"), 7, 0) self.grid_layout.addWidget(self.ndimCheckBox, 7, 1) self.grid_layout.setRowStretch(8, 1) self.grid_layout.setColumnStretch(1, 1) self.grid_layout.setSpacing(4)
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def _on_display_change(self): parent = self.node.parent self.node.transforms = ChainTransform() self.node.parent = None if self.layer.dims.ndisplay == 2: self.node = Compound([Markers(), Markers(), Line()]) else: self.node = Compound([Markers(), Markers()]) self.node.parent = parent self._reset_base()
def _on_display_change(self): parent = self.node.parent self.node.transforms = ChainTransform() self.node.parent = None if self.layer.dims.ndisplay == 2: self.node = Compound([Markers(), Markers(), Line()]) else: self.node = Markers() self.node.parent = parent self._reset_base()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def _on_data_change(self, event=None): # Check if ndisplay has changed current node type needs updating if (self.layer.dims.ndisplay == 3 and len(self.node._subvisuals) != 2) or ( self.layer.dims.ndisplay == 2 and len(self.node._subvisuals) != 3 ): self._on_display_change() self._on_highlight_change() if len(self.layer._data_view) > 0: edge_color = self.layer.edge_color[self.layer._indices_view] face_color = self.layer.face_color[self.layer._indices_view] else: edge_color = np.array([[0.0, 0.0, 0.0, 1.0]], dtype=np.float32) face_color = np.array([[1.0, 1.0, 1.0, 1.0]], dtype=np.float32) # Set vispy data, noting that the order of the points needs to be # reversed to make the most recently added point appear on top # and the rows / columns need to be switch for vispys x / y ordering if len(self.layer._data_view) == 0: data = np.zeros((1, self.layer.dims.ndisplay)) size = [0] else: data = self.layer._data_view size = self.layer._size_view set_data = self.node._subvisuals[0].set_data set_data( data[:, ::-1] + 0.5, size=size, edge_width=self.layer.edge_width, symbol=self.layer.symbol, edge_color=edge_color, face_color=face_color, scaling=True, ) self.node.update()
def _on_data_change(self, event=None): # Check if ndisplay has changed current node type needs updating if (self.layer.dims.ndisplay == 3 and not isinstance(self.node, Markers)) or ( self.layer.dims.ndisplay == 2 and not isinstance(self.node, Compound) ): self._on_display_change() self._on_highlight_change() if len(self.layer._data_view) > 0: edge_color = self.layer.edge_color[self.layer._indices_view] face_color = self.layer.face_color[self.layer._indices_view] else: edge_color = np.array([[0.0, 0.0, 0.0, 1.0]], dtype=np.float32) face_color = np.array([[1.0, 1.0, 1.0, 1.0]], dtype=np.float32) # Set vispy data, noting that the order of the points needs to be # reversed to make the most recently added point appear on top # and the rows / columns need to be switch for vispys x / y ordering if len(self.layer._data_view) == 0: data = np.zeros((1, self.layer.dims.ndisplay)) size = [0] else: data = self.layer._data_view size = self.layer._size_view if self.layer.dims.ndisplay == 2: set_data = self.node._subvisuals[0].set_data else: set_data = self.node.set_data set_data( data[:, ::-1] + 0.5, size=size, edge_width=self.layer.edge_width, symbol=self.layer.symbol, edge_color=edge_color, face_color=face_color, scaling=True, ) self.node.update()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def _on_highlight_change(self, event=None): if len(self.layer._highlight_index) > 0: # Color the hovered or selected points data = self.layer._data_view[self.layer._highlight_index] if data.ndim == 1: data = np.expand_dims(data, axis=0) size = self.layer._size_view[self.layer._highlight_index] else: data = np.zeros((1, self.layer.dims.ndisplay)) size = 0 self.node._subvisuals[1].set_data( data[:, ::-1] + 0.5, size=size, edge_width=self._highlight_width, symbol=self.layer.symbol, edge_color=self._highlight_color, face_color=transform_color("transparent"), scaling=True, ) # only draw a box in 2D if self.layer.dims.ndisplay == 2: if self.layer._highlight_box is None or 0 in self.layer._highlight_box.shape: pos = np.zeros((1, self.layer.dims.ndisplay)) width = 0 else: pos = self.layer._highlight_box width = self._highlight_width self.node._subvisuals[2].set_data( pos=pos[:, ::-1] + 0.5, color=self._highlight_color, width=width, ) self.node.update()
def _on_highlight_change(self, event=None): if self.layer.dims.ndisplay == 3: return if len(self.layer._highlight_index) > 0: # Color the hovered or selected points data = self.layer._data_view[self.layer._highlight_index] if data.ndim == 1: data = np.expand_dims(data, axis=0) size = self.layer._size_view[self.layer._highlight_index] face_color = self.layer.face_color[ self.layer._indices_view[self.layer._highlight_index] ] else: data = np.zeros((1, self.layer.dims.ndisplay)) size = 0 face_color = np.array([[1.0, 1.0, 1.0, 1.0]], dtype=np.float32) self.node._subvisuals[1].set_data( data[:, ::-1] + 0.5, size=size, edge_width=self._highlight_width, symbol=self.layer.symbol, edge_color=self._highlight_color, face_color=face_color, scaling=True, ) if self.layer._highlight_box is None or 0 in self.layer._highlight_box.shape: pos = np.zeros((1, self.layer.dims.ndisplay)) width = 0 else: pos = self.layer._highlight_box width = self._highlight_width self.node._subvisuals[2].set_data( pos=pos[:, ::-1] + 0.5, color=self._highlight_color, width=width )
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def __init__( self, data=None, *, properties=None, symbol="o", size=10, edge_width=1, edge_color="black", edge_color_cycle=None, edge_colormap="viridis", edge_contrast_limits=None, face_color="white", face_color_cycle=None, face_colormap="viridis", face_contrast_limits=None, n_dimensional=False, name=None, metadata=None, scale=None, translate=None, opacity=1, blending="translucent", visible=True, ): if data is None: data = np.empty((0, 2)) else: data = np.atleast_2d(data) ndim = data.shape[1] super().__init__( ndim, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.events.add( mode=Event, size=Event, edge_width=Event, face_color=Event, current_face_color=Event, edge_color=Event, current_edge_color=Event, symbol=Event, n_dimensional=Event, highlight=Event, ) # update highlights when the layer is selected/deselected self.events.select.connect(self._set_highlight) self.events.deselect.connect(self._set_highlight) self._colors = get_color_namelist() # Save the point coordinates self._data = np.asarray(data) self.dims.clip = False # Save the properties if properties is None: properties = {} elif not isinstance(properties, dict): properties = dataframe_to_properties(properties) self._properties = self._validate_properties(properties) # Save the point style params self.symbol = symbol self._n_dimensional = n_dimensional self.edge_width = edge_width # The following point properties are for the new points that will # be added. For any given property, if a list is passed to the # constructor so each point gets its own value then the default # value is used when adding new points if np.isscalar(size): self._current_size = np.asarray(size) else: self._current_size = 10 # Indices of selected points self._selected_data = [] self._selected_data_stored = [] self._selected_data_history = [] # Indices of selected points within the currently viewed slice self._selected_view = [] # Index of hovered point self._value = None self._value_stored = None self._mode = Mode.PAN_ZOOM self._mode_history = self._mode self._status = self.mode self._highlight_index = [] self._highlight_box = None self._drag_start = None # Nx2 array of points in the currently viewed slice self._data_view = np.empty((0, 2)) # Sizes of points in the currently viewed slice self._size_view = 0 # Full data indices of points located in the currently viewed slice self._indices_view = [] self._drag_box = None self._drag_box_stored = None self._is_selecting = False self._clipboard = {} with self.block_update_properties(): self.edge_color_property = "" self.edge_color = edge_color if edge_color_cycle is None: edge_color_cycle = DEFAULT_COLOR_CYCLE self.edge_color_cycle = edge_color_cycle self.edge_colormap = edge_colormap self._edge_contrast_limits = edge_contrast_limits self._face_color_property = "" self.face_color = face_color if face_color_cycle is None: face_color_cycle = DEFAULT_COLOR_CYCLE self.face_color_cycle = face_color_cycle self.face_colormap = face_colormap self._face_contrast_limits = face_contrast_limits self.refresh_colors() # set the current_* properties self._current_edge_color = self.edge_color[-1] self._current_face_color = self.face_color[-1] self.size = size self.current_properties = { k: np.asarray([v[-1]]) for k, v in self.properties.items() } # Trigger generation of view slice and thumbnail self._update_dims()
def __init__( self, data=None, *, properties=None, symbol="o", size=10, edge_width=1, edge_color="black", edge_color_cycle=None, edge_colormap="viridis", edge_contrast_limits=None, face_color="white", face_color_cycle=None, face_colormap="viridis", face_contrast_limits=None, n_dimensional=False, name=None, metadata=None, scale=None, translate=None, opacity=1, blending="translucent", visible=True, ): if data is None: data = np.empty((0, 2)) else: data = np.atleast_2d(data) ndim = data.shape[1] super().__init__( ndim, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.events.add( mode=Event, size=Event, edge_width=Event, face_color=Event, edge_color=Event, symbol=Event, n_dimensional=Event, highlight=Event, ) self._colors = get_color_namelist() # Save the point coordinates self._data = np.asarray(data) self.dims.clip = False # Save the properties if properties is None: properties = {} elif not isinstance(properties, dict): properties = dataframe_to_properties(properties) self._properties = self._validate_properties(properties) # Save the point style params self.symbol = symbol self._n_dimensional = n_dimensional self.edge_width = edge_width # The following point properties are for the new points that will # be added. For any given property, if a list is passed to the # constructor so each point gets its own value then the default # value is used when adding new points if np.isscalar(size): self._current_size = np.asarray(size) else: self._current_size = 10 # Indices of selected points self._selected_data = [] self._selected_data_stored = [] self._selected_data_history = [] # Indices of selected points within the currently viewed slice self._selected_view = [] # Index of hovered point self._value = None self._value_stored = None self._selected_box = None self._mode = Mode.PAN_ZOOM self._mode_history = self._mode self._status = self.mode self._highlight_index = [] self._highlight_box = None self._drag_start = None # Nx2 array of points in the currently viewed slice self._data_view = np.empty((0, 2)) # Sizes of points in the currently viewed slice self._size_view = 0 # Full data indices of points located in the currently viewed slice self._indices_view = [] self._drag_box = None self._drag_box_stored = None self._is_selecting = False self._clipboard = {} with self.block_update_properties(): self.edge_color_property = "" self.edge_color = edge_color if edge_color_cycle is None: edge_color_cycle = DEFAULT_COLOR_CYCLE self.edge_color_cycle = edge_color_cycle self.edge_colormap = edge_colormap self._edge_contrast_limits = edge_contrast_limits self._face_color_property = "" self.face_color = face_color if face_color_cycle is None: face_color_cycle = DEFAULT_COLOR_CYCLE self.face_color_cycle = face_color_cycle self.face_colormap = face_colormap self._face_contrast_limits = face_contrast_limits self.refresh_colors() # set the current_* properties self._current_edge_color = self.edge_color[-1] self._current_face_color = self.face_color[-1] self.size = size self.current_properties = { k: np.asarray([v[-1]]) for k, v in self.properties.items() } # Trigger generation of view slice and thumbnail self._update_dims()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def data(self, data: np.ndarray): cur_npoints = len(self._data) self._data = data # Adjust the size array when the number of points has changed if len(data) < cur_npoints: # If there are now fewer points, remove the size and colors of the # extra ones with self.events.set_data.blocker(): self._edge_color = self.edge_color[: len(data)] self._face_color = self.face_color[: len(data)] self._size = self._size[: len(data)] for k in self.properties: self.properties[k] = self.properties[k][: len(data)] elif len(data) > cur_npoints: # If there are now more points, add the size and colors of the # new ones with self.events.set_data.blocker(): adding = len(data) - cur_npoints if len(self._size) > 0: new_size = copy(self._size[-1]) for i in self.dims.displayed: new_size[i] = self.current_size else: # Add the default size, with a value for each dimension new_size = np.repeat(self.current_size, self._size.shape[1]) size = np.repeat([new_size], adding, axis=0) for k in self.properties: new_property = np.repeat(self.current_properties[k], adding, axis=0) self.properties[k] = np.concatenate( (self.properties[k], new_property), axis=0 ) # add new edge colors if self._edge_color_mode == ColorMode.DIRECT: new_edge_colors = np.tile(self._current_edge_color, (adding, 1)) elif self._edge_color_mode == ColorMode.CYCLE: edge_color_property = self.current_properties[ self._edge_color_property ][0] new_edge_colors = np.tile( self.edge_color_cycle_map[edge_color_property], (adding, 1), ) elif self._edge_color_mode == ColorMode.COLORMAP: edge_color_property_value = self.current_properties[ self._edge_color_property ][0] ec, _ = map_property( prop=edge_color_property_value, colormap=self.edge_colormap[1], contrast_limits=self._edge_contrast_limits, ) new_edge_colors = np.tile(ec, (adding, 1)) self._edge_color = np.vstack((self.edge_color, new_edge_colors)) # add new face colors if self._face_color_mode == ColorMode.DIRECT: new_face_colors = np.tile(self._current_face_color, (adding, 1)) elif self._face_color_mode == ColorMode.CYCLE: face_color_property_value = self.current_properties[ self._face_color_property ][0] new_face_colors = np.tile( self.face_color_cycle_map[face_color_property_value], (adding, 1), ) elif self._face_color_mode == ColorMode.COLORMAP: face_color_property_value = self.current_properties[ self._face_color_property ][0] fc, _ = map_property( prop=face_color_property_value, colormap=self.face_colormap[1], contrast_limits=self._face_contrast_limits, ) new_face_colors = np.tile(fc, (adding, 1)) self._face_color = np.vstack((self.face_color, new_face_colors)) self.size = np.concatenate((self._size, size), axis=0) self.selected_data = list(np.arange(cur_npoints, len(data))) self._update_dims() self.events.data()
def data(self, data: np.ndarray): cur_npoints = len(self._data) self._data = data # Adjust the size array when the number of points has changed if len(data) < cur_npoints: # If there are now fewer points, remove the size and colors of the # extra ones with self.events.set_data.blocker(): self._edge_color = self.edge_color[: len(data)] self._face_color = self.face_color[: len(data)] self._size = self._size[: len(data)] for k in self.properties: self.properties[k] = self.properties[k][: len(data)] elif len(data) > cur_npoints: # If there are now more points, add the size and colors of the # new ones with self.events.set_data.blocker(): adding = len(data) - cur_npoints if len(self._size) > 0: new_size = copy(self._size[-1]) for i in self.dims.displayed: new_size[i] = self.current_size else: # Add the default size, with a value for each dimension new_size = np.repeat(self.current_size, self._size.shape[1]) size = np.repeat([new_size], adding, axis=0) for k in self.properties: new_property = np.repeat(self.current_properties[k], adding, axis=0) self.properties[k] = np.concatenate( (self.properties[k], new_property), axis=0 ) # add new edge colors if self._edge_color_mode == ColorMode.DIRECT: new_edge_colors = np.tile(self._current_edge_color, (adding, 1)) elif self._edge_color_mode == ColorMode.CYCLE: edge_color_property = self.current_properties[ self._edge_color_property ][0] new_edge_colors = np.tile( self.edge_color_cycle_map[edge_color_property], (adding, 1), ) elif self._edge_color_mode == ColorMode.COLORMAP: edge_color_property_value = self.current_properties[ self._edge_color_property ][0] ec, _ = map_property( prop=edge_color_property_value, colormap=self.edge_colormap[1], contrast_limits=self._edge_contrast_limits, ) new_edge_colors = np.tile(ec, (adding, 1)) self._edge_color = np.vstack((self.edge_color, new_edge_colors)) # add new face colors if self._face_color_mode == ColorMode.DIRECT: new_face_colors = np.tile(self._current_face_color, (adding, 1)) elif self._face_color_mode == ColorMode.CYCLE: face_color_property_value = self.current_properties[ self._face_color_property ][0] new_face_colors = np.tile( self.face_color_cycle_map[face_color_property_value], (adding, 1), ) elif self._face_color_mode == ColorMode.COLORMAP: face_color_property_value = self.current_properties[ self._face_color_property ][0] fc, _ = map_property( prop=face_color_property_value, colormap=self.face_colormap[1], contrast_limits=self._face_contrast_limits, ) new_face_colors = np.tile(fc, (adding, 1)) self._face_color = np.vstack((self.face_color, new_face_colors)) self.size = np.concatenate((self._size, size), axis=0) self._update_dims() self.events.data()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def current_size(self, size: Union[None, float]) -> None: self._current_size = size if ( self._update_properties and len(self.selected_data) > 0 and self._mode != Mode.ADD ): for i in self.selected_data: self.size[i, :] = (self.size[i, :] > 0) * size self.refresh() self.events.size() self.status = format_float(self.current_size)
def current_size(self, size: Union[None, float]) -> None: self._current_size = size if self._update_properties and len(self.selected_data) > 0: for i in self.selected_data: self.size[i, :] = (self.size[i, :] > 0) * size self.refresh() self.status = format_float(self.current_size) self.events.size()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def edge_width(self, edge_width: Union[None, float]) -> None: self._edge_width = edge_width self.status = format_float(self.edge_width) self.events.edge_width()
def edge_width(self, edge_width: Union[None, float]) -> None: self._edge_width = edge_width self.status = format_float(self.edge_width) self.events.edge_width() self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def edge_color(self, edge_color): # if the provided face color is a string, first check if it is a key in the properties. # otherwise, assume it is the name of a color if self._is_color_mapped(edge_color): if guess_continuous(self.properties[edge_color]): self._edge_color_mode = ColorMode.COLORMAP else: self._edge_color_mode = ColorMode.CYCLE self._edge_color_property = edge_color self.refresh_colors() else: transformed_color = transform_color_with_defaults( num_entries=len(self.data), colors=edge_color, elem_name="edge_color", default="white", ) self._edge_color = normalize_and_broadcast_colors( len(self.data), transformed_color ) self.edge_color_mode = ColorMode.DIRECT self._edge_color_property = "" self.events.edge_color()
def edge_color(self, edge_color): # if the provided face color is a string, first check if it is a key in the properties. # otherwise, assume it is the name of a color if self._is_color_mapped(edge_color): if guess_continuous(self.properties[edge_color]): self._edge_color_mode = ColorMode.COLORMAP else: self._edge_color_mode = ColorMode.CYCLE self._edge_color_property = edge_color self.refresh_colors() else: transformed_color = transform_color_with_defaults( num_entries=len(self.data), colors=edge_color, elem_name="edge_color", default="white", ) self._edge_color = normalize_and_broadcast_colors( len(self.data), transformed_color ) self.edge_color_mode = ColorMode.DIRECT self._edge_color_property = "" self.events.edge_color() self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def current_edge_color(self, edge_color: ColorType) -> None: self._current_edge_color = transform_color(edge_color) if ( self._update_properties and len(self.selected_data) > 0 and self._mode != Mode.ADD ): cur_colors: np.ndarray = self.edge_color cur_colors[self.selected_data] = self._current_edge_color self.edge_color = cur_colors self.events.current_edge_color()
def current_edge_color(self, edge_color: ColorType) -> None: self._current_edge_color = transform_color(edge_color) if self._update_properties and len(self.selected_data) > 0: cur_colors: np.ndarray = self.edge_color cur_colors[self.selected_data] = self._current_edge_color self.edge_color = cur_colors self.events.edge_color() self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def face_color(self, face_color): # if the provided face color is a string, first check if it is a key in the properties. # otherwise, assume it is the name of a color if self._is_color_mapped(face_color): if guess_continuous(self.properties[face_color]): self._face_color_mode = ColorMode.COLORMAP else: self._face_color_mode = ColorMode.CYCLE self._face_color_property = face_color self.refresh_colors() else: transformed_color = transform_color_with_defaults( num_entries=len(self.data), colors=face_color, elem_name="face_color", default="white", ) self._face_color = normalize_and_broadcast_colors( len(self.data), transformed_color ) self.face_color_mode = ColorMode.DIRECT self.events.face_color()
def face_color(self, face_color): # if the provided face color is a string, first check if it is a key in the properties. # otherwise, assume it is the name of a color if self._is_color_mapped(face_color): if guess_continuous(self.properties[face_color]): self._face_color_mode = ColorMode.COLORMAP else: self._face_color_mode = ColorMode.CYCLE self._face_color_property = face_color self.refresh_colors() else: transformed_color = transform_color_with_defaults( num_entries=len(self.data), colors=face_color, elem_name="face_color", default="white", ) self._face_color = normalize_and_broadcast_colors( len(self.data), transformed_color ) self.face_color_mode = ColorMode.DIRECT self.events.face_color() self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def current_face_color(self, face_color: ColorType) -> None: self._current_face_color = transform_color(face_color) if ( self._update_properties and len(self.selected_data) > 0 and self._mode != Mode.ADD ): cur_colors: np.ndarray = self.face_color cur_colors[self.selected_data] = self._current_face_color self.face_color = cur_colors self.events.current_face_color()
def current_face_color(self, face_color: ColorType) -> None: self._current_face_color = transform_color(face_color) if self._update_properties and len(self.selected_data) > 0: cur_colors: np.ndarray = self.face_color cur_colors[self.selected_data] = self._current_face_color self.face_color = cur_colors self.events.face_color() self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def refresh_colors(self, update_color_mapping: bool = True): """Calculate and update face and edge colors if using a cycle or color map Parameters ---------- update_color_mapping : bool If set to True, the function will recalculate the color cycle map or colormap (whichever is being used). If set to False, the function will use the current color cycle map or color map. For example, if you are adding/modifying points and want them to be colored with the same mapping as the other points (i.e., the new points shouldn't affect the color cycle map or colormap), set update_color_mapping=False. Default value is True. """ if self._update_properties: if self._face_color_mode == ColorMode.CYCLE: face_color_properties = self.properties[self._face_color_property] if update_color_mapping: self.face_color_cycle_map = { k: c for k, c in zip( np.unique(face_color_properties), self.face_color_cycle, ) } face_colors = np.array( [self.face_color_cycle_map[x] for x in face_color_properties] ) self._face_color = face_colors self.events.face_color() elif self._face_color_mode == ColorMode.COLORMAP: face_color_properties = self.properties[self._face_color_property] if update_color_mapping: face_colors, contrast_limits = map_property( prop=face_color_properties, colormap=self.face_colormap[1], ) self.face_contrast_limits = contrast_limits else: face_colors, _ = map_property( prop=face_color_properties, colormap=self.face_colormap[1], contrast_limits=self.face_contrast_limits, ) self._face_color = face_colors if self._edge_color_mode == ColorMode.CYCLE: edge_color_properties = self.properties[self._edge_color_property] if update_color_mapping: self.edge_color_cycle_map = { k: c for k, c in zip( np.unique(edge_color_properties), self.edge_color_cycle, ) } edge_colors = np.array( [self.edge_color_cycle_map[x] for x in edge_color_properties] ) self._edge_color = edge_colors elif self._edge_color_mode == ColorMode.COLORMAP: edge_color_properties = self.properties[self._edge_color_property] if update_color_mapping: edge_colors, contrast_limits = map_property( prop=edge_color_properties, colormap=self.edge_colormap[1], ) self.edge_contrast_limits = contrast_limits else: edge_colors, _ = map_property( prop=edge_color_properties, colormap=self.edge_colormap[1], contrast_limits=self.edge_contrast_limits, ) self._edge_color = edge_colors self.events.face_color() self.events.edge_color()
def refresh_colors(self, update_color_mapping: bool = True): """Calculate and update face and edge colors if using a cycle or color map Parameters ---------- update_color_mapping : bool If set to True, the function will recalculate the color cycle map or colormap (whichever is being used). If set to False, the function will use the current color cycle map or color map. For example, if you are adding/modifying points and want them to be colored with the same mapping as the other points (i.e., the new points shouldn't affect the color cycle map or colormap), set update_color_mapping=False. Default value is True. """ if self._update_properties: if self._face_color_mode == ColorMode.CYCLE: face_color_properties = self.properties[self._face_color_property] if update_color_mapping: self.face_color_cycle_map = { k: c for k, c in zip( np.unique(face_color_properties), self.face_color_cycle, ) } face_colors = np.array( [self.face_color_cycle_map[x] for x in face_color_properties] ) self._face_color = face_colors self.events.face_color() self.events.highlight() elif self._face_color_mode == ColorMode.COLORMAP: face_color_properties = self.properties[self._face_color_property] if update_color_mapping: face_colors, contrast_limits = map_property( prop=face_color_properties, colormap=self.face_colormap[1], ) self.face_contrast_limits = contrast_limits else: face_colors, _ = map_property( prop=face_color_properties, colormap=self.face_colormap[1], contrast_limits=self.face_contrast_limits, ) self._face_color = face_colors if self._edge_color_mode == ColorMode.CYCLE: edge_color_properties = self.properties[self._edge_color_property] if update_color_mapping: self.edge_color_cycle_map = { k: c for k, c in zip( np.unique(edge_color_properties), self.edge_color_cycle, ) } edge_colors = np.array( [self.edge_color_cycle_map[x] for x in edge_color_properties] ) self._edge_color = edge_colors elif self._edge_color_mode == ColorMode.COLORMAP: edge_color_properties = self.properties[self._edge_color_property] if update_color_mapping: edge_colors, contrast_limits = map_property( prop=edge_color_properties, colormap=self.edge_colormap[1], ) self.edge_contrast_limits = contrast_limits else: edge_colors, _ = map_property( prop=edge_color_properties, colormap=self.edge_colormap[1], contrast_limits=self.edge_contrast_limits, ) self._edge_color = edge_colors self.events.face_color() self.events.edge_color() self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def selected_data(self, selected_data): self._selected_data = list(selected_data) selected = [] for c in self._selected_data: if c in self._indices_view: ind = list(self._indices_view).index(c) selected.append(ind) self._selected_view = selected # Update properties based on selected points if len(self._selected_data) == 0: return index = self._selected_data edge_colors = np.unique(self.edge_color[index], axis=0) if len(edge_colors) == 1: edge_color = edge_colors[0] with self.block_update_properties(): self.current_edge_color = edge_color face_colors = np.unique(self.face_color[index], axis=0) if len(face_colors) == 1: face_color = face_colors[0] with self.block_update_properties(): self.current_face_color = face_color size = list(set([self.size[i, self.dims.displayed].mean() for i in index])) if len(size) == 1: size = size[0] with self.block_update_properties(): self.current_size = size properties = {k: np.unique(v[index], axis=0) for k, v in self.properties.items()} n_unique_properties = np.array([len(v) for v in properties.values()]) if np.all(n_unique_properties == 1): self.current_properties = properties
def selected_data(self, selected_data): self._selected_data = list(selected_data) selected = [] for c in self._selected_data: if c in self._indices_view: ind = list(self._indices_view).index(c) selected.append(ind) self._selected_view = selected self._selected_box = self.interaction_box(self._selected_view) # Update properties based on selected points if len(self._selected_data) == 0: return index = self._selected_data edge_colors = np.unique(self.edge_color[index], axis=0) if len(edge_colors) == 1: edge_color = edge_colors[0] with self.block_update_properties(): self.current_edge_color = edge_color face_colors = np.unique(self.face_color[index], axis=0) if len(face_colors) == 1: face_color = face_colors[0] with self.block_update_properties(): self.current_face_color = face_color size = list(set([self.size[i, self.dims.displayed].mean() for i in index])) if len(size) == 1: size = size[0] with self.block_update_properties(): self.current_size = size properties = {k: np.unique(v[index], axis=0) for k, v in self.properties.items()} n_unique_properties = np.array([len(v) for v in properties.values()]) if np.all(n_unique_properties == 1): self.current_properties = properties
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def mode(self, mode): if isinstance(mode, str): mode = Mode(mode) if not self.editable: mode = Mode.PAN_ZOOM if mode == self._mode: return old_mode = self._mode if mode == Mode.ADD: self.cursor = "pointing" self.interactive = False self.help = "hold <space> to pan/zoom" self.selected_data = [] self._set_highlight() elif mode == Mode.SELECT: self.cursor = "standard" self.interactive = False self.help = "hold <space> to pan/zoom" elif mode == Mode.PAN_ZOOM: self.cursor = "standard" self.interactive = True self.help = "" else: raise ValueError("Mode not recognized") if not (mode == Mode.SELECT and old_mode == Mode.SELECT): self._selected_data_stored = [] self.status = str(mode) self._mode = mode self._set_highlight() self.events.mode(mode=mode)
def mode(self, mode): if isinstance(mode, str): mode = Mode(mode) if not self.editable: mode = Mode.PAN_ZOOM if mode == self._mode: return old_mode = self._mode if mode == Mode.ADD: self.cursor = "pointing" self.interactive = False self.help = "hold <space> to pan/zoom" elif mode == Mode.SELECT: self.cursor = "standard" self.interactive = False self.help = "hold <space> to pan/zoom" elif mode == Mode.PAN_ZOOM: self.cursor = "standard" self.interactive = True self.help = "" else: raise ValueError("Mode not recognized") if not (mode == Mode.SELECT and old_mode == Mode.SELECT): self.selected_data = [] self._set_highlight() self.status = str(mode) self._mode = mode self.events.mode(mode=mode)
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def _set_view_slice(self): """Sets the view given the indices to slice with.""" in_slice_data, indices, scale = self._slice_data(self.dims.indices) # Display points if there are any in this slice if len(in_slice_data) > 0: # Get the point sizes sizes = self.size[np.ix_(indices, self.dims.displayed)].mean(axis=1) * scale # Update the points node data = np.array(in_slice_data) else: # if no points in this slice send dummy data data = np.zeros((0, self.dims.ndisplay)) sizes = [0] self._data_view = data self._size_view = sizes self._indices_view = indices # Make sure if changing planes any selected points not in the current # plane are removed selected = [] for c in self.selected_data: if c in self._indices_view: ind = list(self._indices_view).index(c) selected.append(ind) self._selected_view = selected self._set_highlight()
def _set_view_slice(self): """Sets the view given the indices to slice with.""" in_slice_data, indices, scale = self._slice_data(self.dims.indices) # Display points if there are any in this slice if len(in_slice_data) > 0: # Get the point sizes sizes = self.size[np.ix_(indices, self.dims.displayed)].mean(axis=1) * scale # Update the points node data = np.array(in_slice_data) else: # if no points in this slice send dummy data data = np.zeros((0, self.dims.ndisplay)) sizes = [0] self._data_view = data self._size_view = sizes self._indices_view = indices # Make sure if changing planes any selected points not in the current # plane are removed selected = [] for c in self.selected_data: if c in self._indices_view: ind = list(self._indices_view).index(c) selected.append(ind) self._selected_view = selected if self.dims.ndisplay == 2: self._selected_box = self.interaction_box(self._selected_view) else: self._selected_box = None
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def _set_highlight(self, force=False): """Render highlights of shapes including boundaries, vertices, interaction boxes, and the drag selection box when appropriate. Highlighting only occurs in Mode.SELECT. Parameters ---------- force : bool Bool that forces a redraw to occur when `True` """ # if self._mode == Mode.SELECT: # Check if any point ids have changed since last call if self.selected: if ( self.selected_data == self._selected_data_stored and self._value == self._value_stored and np.all(self._drag_box == self._drag_box_stored) ) and not force: return self._selected_data_stored = copy(self.selected_data) self._value_stored = copy(self._value) self._drag_box_stored = copy(self._drag_box) if self._value is not None or len(self._selected_view) > 0: if len(self._selected_view) > 0: index = copy(self._selected_view) # highlight the hovered point if not in adding mode if self._value is not None and self._mode != Mode.ADD: hover_point = list(self._indices_view).index(self._value) if hover_point in index: pass else: index.append(hover_point) index.sort() else: # don't highlight hovered points in add mode if self._mode != Mode.ADD: hover_point = list(self._indices_view).index(self._value) index = [hover_point] else: index = [] self._highlight_index = index else: self._highlight_index = [] # only display dragging selection box in 2D if self.dims.ndisplay == 2 and self._is_selecting: pos = create_box(self._drag_box) pos = pos[list(range(4)) + [0]] else: pos = None self._highlight_box = pos self.events.highlight() else: self._highlight_box = None self._highlight_index = [] self.events.highlight()
def _set_highlight(self, force=False): """Render highlights of shapes including boundaries, vertices, interaction boxes, and the drag selection box when appropriate Parameters ---------- force : bool Bool that forces a redraw to occur when `True` """ # Check if any point ids have changed since last call if ( self.selected_data == self._selected_data_stored and self._value == self._value_stored and np.all(self._drag_box == self._drag_box_stored) ) and not force: return self._selected_data_stored = copy(self.selected_data) self._value_stored = copy(self._value) self._drag_box_stored = copy(self._drag_box) if self._mode == Mode.SELECT and ( self._value is not None or len(self._selected_view) > 0 ): if len(self._selected_view) > 0: index = copy(self._selected_view) if self._value is not None: hover_point = list(self._indices_view).index(self._value) if hover_point in index: pass else: index.append(hover_point) index.sort() else: hover_point = list(self._indices_view).index(self._value) index = [hover_point] self._highlight_index = index else: self._highlight_index = [] pos = self._selected_box if pos is None and not self._is_selecting: pos = np.zeros((0, 2)) elif self._is_selecting: pos = create_box(self._drag_box) pos = pos[list(range(4)) + [0]] else: pos = pos[list(range(4)) + [0]] self._highlight_box = pos self.events.highlight()
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def add(self, coord): """Adds point at coordinate. Parameters ---------- coord : sequence of indices to add point at """ self.data = np.append(self.data, np.atleast_2d(coord), axis=0)
def add(self, coord): """Adds point at coordinate. Parameters ---------- coord : sequence of indices to add point at """ self.data = np.append(self.data, [coord], axis=0)
https://github.com/napari/napari/issues/901
WARNING: Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2) WARNING:vispy:Traceback (most recent call last): File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1037, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/components/dims.py", line 296, in ndisplay self.events.ndisplay() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/utils/event.py", line 523, in _invoke_callback cb(event) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 180, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 383, in _update_dims self.refresh() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/base/base.py", line 600, in refresh self._set_view_slice() File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 654, in _set_view_slice self._selected_box = self.interaction_box(self._selected_view) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 480, in interaction_box data = points_to_squares(data, size) File "/home/hagai/.conda/envs/ncd/lib/python3.7/site-packages/napari/layers/points/points.py", line 972, in points_to_squares points + np.sqrt(2) / 2 * np.array([sizes, sizes]).T, ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
ValueError
def on_mouse_press(self, event): """Called whenever mouse pressed in canvas. Parameters ---------- event : Event Vispy event """ if self._mode == Mode.PAN_ZOOM: # If in pan/zoom mode do nothing pass elif self._mode == Mode.PICKER: self.selected_label = self._value or 0 elif self._mode == Mode.PAINT: # Start painting with new label self._save_history() self._block_saving = True self.paint(self.coordinates, self.selected_label) self._last_cursor_coord = copy(self.coordinates) elif self._mode == Mode.FILL: # Fill clicked on region with new label self.fill(self.coordinates, self._value, self.selected_label) else: raise ValueError("Mode not recongnized")
def on_mouse_press(self, event): """Called whenever mouse pressed in canvas. Parameters ---------- event : Event Vispy event """ if self._mode == Mode.PAN_ZOOM: # If in pan/zoom mode do nothing pass elif self._mode == Mode.PICKER: self.selected_label = self._value elif self._mode == Mode.PAINT: # Start painting with new label self._save_history() self._block_saving = True self.paint(self.coordinates, self.selected_label) self._last_cursor_coord = copy(self.coordinates) elif self._mode == Mode.FILL: # Fill clicked on region with new label self.fill(self.coordinates, self._value, self.selected_label) else: raise ValueError("Mode not recongnized")
https://github.com/napari/napari/issues/857
Traceback (most recent call last): File "~/miniconda3/envs/napdev/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 447, in mousePressEvent modifiers=self._modifiers(ev), File "~/miniconda3/envs/napdev/lib/python3.7/site-packages/vispy/app/base.py", line 181, in _vispy_mouse_press ev = self._vispy_canvas.events.mouse_press(**kwargs) File "~/miniconda3/envs/napdev/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "~/miniconda3/envs/napdev/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) File "~/miniconda3/envs/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 338, in on_mouse_press self.layer_to_visual[layer].on_mouse_press(event) File "~/napari/napari/_vispy/vispy_base_layer.py", line 194, in on_mouse_press self.layer.on_mouse_press(event) File "~/napari/napari/layers/labels/labels.py", line 542, in on_mouse_press self.selected_label = self._value File "~/napari/napari/layers/labels/labels.py", line 270, in selected_label if selected_label < 0: TypeError: '<' not supported between instances of 'NoneType' and 'int'
TypeError
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])
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])
https://github.com/napari/napari/issues/870
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
TypeError
def show_at(self, position="top", *, width_ratio=0.9): if not self.parent(): raise NotImplementedError("cannot show_at without parent") main_window = self.parent().window() xy = main_window.pos() if position == "top": width = main_window.width() * width_ratio height = self.sizeHint().height() xy = xy + QPoint(main_window.width() * (1 - width_ratio) / 2, 24) elif position == "bottom": width = main_window.width() * width_ratio height = self.sizeHint().height() y = main_window.height() - self.height() - 2 xy = xy + QPoint(main_window.width() * (1 - width_ratio) / 2, y) elif position == "left": width = self.sizeHint().width() height = main_window.height() * width_ratio xy = xy + QPoint(12, main_window.height() * (1 - width_ratio) / 2) elif position == "right": width = self.sizeHint().width() height = main_window.height() * width_ratio x = main_window.width() - width - 12 xy = xy + QPoint(x, main_window.height() * (1 - width_ratio) / 2) else: raise ValueError('position must be one of ["top", "left", "bottom", "right"]') # necessary for transparent round corners self.resize(self.sizeHint()) self.setGeometry(xy.x(), xy.y(), max(width, 20), max(height, 20)) self.show()
def show_at(self, position="top", *, width_ratio=0.9): if not self.parent(): raise NotImplementedError("cannot show_at without parent") main_window = self.parent().window() xy = main_window.pos() if position == "top": width = main_window.width() * width_ratio height = self.sizeHint().height() xy = xy + QPoint(main_window.width() * (1 - width_ratio) / 2, 24) elif position == "bottom": width = main_window.width() * width_ratio height = self.sizeHint().height() y = main_window.height() - self.height() - 2 xy = xy + QPoint(main_window.width() * (1 - width_ratio) / 2, y) elif position == "left": width = self.sizeHint().width() height = main_window.height() * width_ratio xy = xy + QPoint(12, main_window.height() * (1 - width_ratio) / 2) elif position == "right": width = self.sizeHint().width() height = main_window.height() * width_ratio x = main_window.width() - width - 12 xy = xy + QPoint(x, main_window.height() * (1 - width_ratio) / 2) else: raise ValueError('position must be one of ["top", "left", "bottom", "right"]') # necessary for transparent round corners self.resize(self.sizeHint()) self.setGeometry(*xy.toTuple(), max(width, 20), max(height, 20)) self.show()
https://github.com/napari/napari/issues/865
WARNING: Traceback (most recent call last): File "c:\users\nico\anaconda3\lib\site-packages\napari\_qt\layers\qt_image_base_layer.py", line 78, in _clim_mousepress self.clim_pop.show_at('top') File "c:\users\nico\anaconda3\lib\site-packages\napari\_qt\qt_modal.py", line 72, in show_at self.setGeometry(*xy.toTuple(), max(width, 20), max(height, 20)) AttributeError: 'QPoint' object has no attribute 'toTuple' WARNING:vispy:Traceback (most recent call last): File "c:\users\nico\anaconda3\lib\site-packages\napari\_qt\layers\qt_image_base_layer.py", line 78, in _clim_mousepress self.clim_pop.show_at('top') File "c:\users\nico\anaconda3\lib\site-packages\napari\_qt\qt_modal.py", line 72, in show_at self.setGeometry(*xy.toTuple(), max(width, 20), max(height, 20)) AttributeError: 'QPoint' object has no attribute 'toTuple'
AttributeError
def __init__( self, ndim, *, name=None, metadata=None, scale=None, translate=None, opacity=1, blending="translucent", visible=True, ): super().__init__() self.metadata = metadata or {} self._opacity = opacity self._blending = Blending(blending) self._visible = visible self._selected = True self._freeze = False self._status = "Ready" self._help = "" self._cursor = "standard" self._cursor_size = None self._interactive = True self._value = None self.scale_factor = 1 self.dims = Dims(ndim) if scale is None: self._scale = [1] * ndim else: # covers list and array-like inputs self._scale = list(scale) if translate is None: self._translate = [0] * ndim else: # covers list and array-like inputs self._translate = list(translate) self._scale_view = np.ones(ndim) self._translate_view = np.zeros(ndim) self._translate_grid = np.zeros(ndim) self.coordinates = (0,) * ndim self._position = (0,) * self.dims.ndisplay self.is_pyramid = False self._editable = True self._thumbnail_shape = (32, 32, 4) self._thumbnail = np.zeros(self._thumbnail_shape, dtype=np.uint8) self._update_properties = True self._name = "" self.events = EmitterGroup( source=self, auto_connect=True, refresh=Event, set_data=Event, blending=Event, opacity=Event, visible=Event, select=Event, deselect=Event, scale=Event, translate=Event, data=Event, name=Event, thumbnail=Event, status=Event, help=Event, interactive=Event, cursor=Event, cursor_size=Event, editable=Event, ) self.name = name self.events.data.connect(lambda e: self._set_editable()) self.dims.events.ndisplay.connect(lambda e: self._set_editable()) self.dims.events.order.connect(lambda e: self._set_view_slice()) self.dims.events.ndisplay.connect(lambda e: self._update_dims()) self.dims.events.order.connect(lambda e: self._update_dims()) self.dims.events.axis.connect(lambda e: self._set_view_slice()) self.mouse_move_callbacks = [] self.mouse_drag_callbacks = [] self._persisted_mouse_event = {} self._mouse_drag_gen = {}
def __init__( self, ndim, *, name=None, metadata=None, scale=None, translate=None, opacity=1, blending="translucent", visible=True, ): super().__init__() self.metadata = metadata or {} self._opacity = opacity self._blending = Blending(blending) self._visible = visible self._selected = True self._freeze = False self._status = "Ready" self._help = "" self._cursor = "standard" self._cursor_size = None self._interactive = True self._value = None self.scale_factor = 1 self.dims = Dims(ndim) self._scale = scale or [1] * ndim self._translate = translate or [0] * ndim self._scale_view = np.ones(ndim) self._translate_view = np.zeros(ndim) self._translate_grid = np.zeros(ndim) self.coordinates = (0,) * ndim self._position = (0,) * self.dims.ndisplay self.is_pyramid = False self._editable = True self._thumbnail_shape = (32, 32, 4) self._thumbnail = np.zeros(self._thumbnail_shape, dtype=np.uint8) self._update_properties = True self._name = "" self.events = EmitterGroup( source=self, auto_connect=True, refresh=Event, set_data=Event, blending=Event, opacity=Event, visible=Event, select=Event, deselect=Event, scale=Event, translate=Event, data=Event, name=Event, thumbnail=Event, status=Event, help=Event, interactive=Event, cursor=Event, cursor_size=Event, editable=Event, ) self.name = name self.events.data.connect(lambda e: self._set_editable()) self.dims.events.ndisplay.connect(lambda e: self._set_editable()) self.dims.events.order.connect(lambda e: self._set_view_slice()) self.dims.events.ndisplay.connect(lambda e: self._update_dims()) self.dims.events.order.connect(lambda e: self._update_dims()) self.dims.events.axis.connect(lambda e: self._set_view_slice()) self.mouse_move_callbacks = [] self.mouse_drag_callbacks = [] self._persisted_mouse_event = {} self._mouse_drag_gen = {}
https://github.com/napari/napari/issues/751
Traceback (most recent call last): File "test_array_spacing.py", line 9, in <module> napari.view_image(camera, scale=np.array([1, 1])) File "/home/jni/projects/napari/napari/view_layers.py", line 130, in view_image path=path, File "/home/jni/projects/napari/napari/components/viewer_model.py", line 512, in add_image visible=visible, File "/home/jni/projects/napari/napari/layers/image/image.py", line 163, in __init__ visible=visible, File "/home/jni/projects/napari/napari/layers/base/base.py", line 133, in __init__ self._scale = scale or [1] * ndim ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
ValueError
def __init__(self, qt_viewer, *, show=True): self.qt_viewer = qt_viewer self._qt_window = QMainWindow() self._qt_window.setUnifiedTitleAndToolBarOnMac(True) self._qt_center = QWidget() self._qt_window.setCentralWidget(self._qt_center) self._qt_window.setWindowTitle(self.qt_viewer.viewer.title) self._qt_center.setLayout(QHBoxLayout()) self._status_bar = QStatusBar() self._qt_window.setStatusBar(self._status_bar) self._qt_window.closeEvent = self.closeEvent self.close = self._qt_window.close self._add_menubar() self._add_file_menu() self._add_view_menu() self._add_window_menu() self._add_help_menu() self._status_bar.showMessage("Ready") self._help = QLabel("") self._status_bar.addPermanentWidget(self._help) self._qt_center.layout().addWidget(self.qt_viewer) self._qt_center.layout().setContentsMargins(4, 0, 4, 0) self._update_palette(qt_viewer.viewer.palette) self.qt_viewer.viewer.events.status.connect(self._status_changed) self.qt_viewer.viewer.events.help.connect(self._help_changed) self.qt_viewer.viewer.events.title.connect(self._title_changed) self.qt_viewer.viewer.events.palette.connect( lambda event: self._update_palette(event.palette) ) if show: self.show()
def __init__(self, qt_viewer, *, show=True): self.qt_viewer = qt_viewer self._qt_window = QMainWindow() self._qt_window.setUnifiedTitleAndToolBarOnMac(True) self._qt_center = QWidget(self._qt_window) self._qt_window.setCentralWidget(self._qt_center) self._qt_window.setWindowTitle(self.qt_viewer.viewer.title) self._qt_center.setLayout(QHBoxLayout()) self._status_bar = QStatusBar() self._qt_window.setStatusBar(self._status_bar) self._qt_window.closeEvent = self.closeEvent self.close = self._qt_window.close self._add_menubar() self._add_file_menu() self._add_view_menu() self._add_window_menu() self._add_help_menu() self._status_bar.showMessage("Ready") self._help = QLabel("") self._status_bar.addPermanentWidget(self._help) self._qt_center.layout().addWidget(self.qt_viewer) self._qt_center.layout().setContentsMargins(4, 0, 4, 0) self._update_palette(qt_viewer.viewer.palette) if self.qt_viewer.console.shell is not None: self._add_viewer_dock_widget(self.qt_viewer.dockConsole) self.qt_viewer.viewer.events.status.connect(self._status_changed) self.qt_viewer.viewer.events.help.connect(self._help_changed) self.qt_viewer.viewer.events.title.connect(self._title_changed) self.qt_viewer.viewer.events.palette.connect( lambda event: self._update_palette(event.palette) ) if show: self.show()
https://github.com/napari/napari/issues/691
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'
AttributeError
def show(self): """Resize, show, and bring forward the window.""" self._qt_window.resize(self._qt_window.layout().sizeHint()) self._qt_window.show()
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_()
https://github.com/napari/napari/issues/691
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'
AttributeError
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) )
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))
https://github.com/napari/napari/issues/691
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'
AttributeError
def __init__(self, viewer): super().__init__() self.pool = QThreadPool() QCoreApplication.setAttribute(Qt.AA_UseStyleSheetPropagationInWidgetStyles, True) self.viewer = viewer self.dims = QtDims(self.viewer.dims) self.controls = QtControls(self.viewer) self.layers = QtLayerList(self.viewer.layers) self.layerButtons = QtLayerButtons(self.viewer) self.viewerButtons = QtViewerButtons(self.viewer) self.console = QtConsole({"viewer": self.viewer}) # This dictionary holds the corresponding vispy visual for each layer self.layer_to_visual = {} if self.console.shell is not None: self.console.style().unpolish(self.console) self.console.style().polish(self.console) self.console.hide() self.viewerButtons.consoleButton.clicked.connect(lambda: self._toggle_console()) else: self.viewerButtons.consoleButton.setEnabled(False) self.canvas = SceneCanvas(keys=None, vsync=True) self.canvas.events.ignore_callback_errors = False self.canvas.events.draw.connect(self.dims.enable_play) self.canvas.native.setMinimumSize(QSize(200, 200)) self.canvas.context.set_depth_func("lequal") self.canvas.connect(self.on_mouse_move) self.canvas.connect(self.on_mouse_press) self.canvas.connect(self.on_mouse_release) self.canvas.connect(self.on_key_press) self.canvas.connect(self.on_key_release) self.canvas.connect(self.on_draw) self.view = self.canvas.central_widget.add_view() self._update_camera() main_widget = QWidget() main_layout = QGridLayout() main_layout.setContentsMargins(15, 20, 15, 10) main_layout.addWidget(self.canvas.native, 0, 1, 3, 1) main_layout.addWidget(self.dims, 3, 1) main_layout.addWidget(self.controls, 0, 0) main_layout.addWidget(self.layerButtons, 1, 0) main_layout.addWidget(self.layers, 2, 0) main_layout.addWidget(self.viewerButtons, 3, 0) main_layout.setColumnStretch(1, 1) main_layout.setSpacing(10) main_widget.setLayout(main_layout) self.setOrientation(Qt.Vertical) self.addWidget(main_widget) if self.console.shell is not None: self.addWidget(self.console) self._last_visited_dir = str(Path.home()) self._cursors = { "disabled": QCursor( QPixmap(":/icons/cursor/cursor_disabled.png").scaled(20, 20) ), "cross": Qt.CrossCursor, "forbidden": Qt.ForbiddenCursor, "pointing": Qt.PointingHandCursor, "standard": QCursor(), } self._update_palette(viewer.palette) self._key_release_generators = {} self.viewer.events.interactive.connect(self._on_interactive) self.viewer.events.cursor.connect(self._on_cursor) self.viewer.events.reset_view.connect(self._on_reset_view) self.viewer.events.palette.connect( lambda event: self._update_palette(event.palette) ) self.viewer.layers.events.reordered.connect(self._reorder_layers) self.viewer.layers.events.added.connect(self._add_layer) self.viewer.layers.events.removed.connect(self._remove_layer) self.viewer.dims.events.camera.connect(lambda event: self._update_camera()) # stop any animations whenever the layers change self.viewer.events.layers_change.connect(lambda x: self.dims.stop()) self.setAcceptDrops(True)
def __init__(self, viewer): super().__init__() self.pool = QThreadPool() QCoreApplication.setAttribute(Qt.AA_UseStyleSheetPropagationInWidgetStyles, True) self.viewer = viewer self.dims = QtDims(self.viewer.dims) self.controls = QtControls(self.viewer) self.layers = QtLayerList(self.viewer.layers) self.layerButtons = QtLayerButtons(self.viewer) self.viewerButtons = QtViewerButtons(self.viewer) self.console = QtConsole({"viewer": self.viewer}) self.dockConsole = QtViewerDockWidget(self, self.console, name="console") self.dockConsole.setVisible(False) # This dictionary holds the corresponding vispy visual for each layer self.layer_to_visual = {} if self.console.shell is not None: self.viewerButtons.consoleButton.clicked.connect(lambda: self.toggle_console()) else: self.viewerButtons.consoleButton.setEnabled(False) self.canvas = SceneCanvas(keys=None, vsync=True) self.canvas.events.ignore_callback_errors = False self.canvas.events.draw.connect(self.dims.enable_play) self.canvas.native.setMinimumSize(QSize(200, 200)) self.canvas.context.set_depth_func("lequal") self.canvas.connect(self.on_mouse_move) self.canvas.connect(self.on_mouse_press) self.canvas.connect(self.on_mouse_release) self.canvas.connect(self.on_key_press) self.canvas.connect(self.on_key_release) self.canvas.connect(self.on_draw) self.view = self.canvas.central_widget.add_view() self._update_camera() main_widget = QWidget() main_layout = QGridLayout() main_layout.setContentsMargins(15, 20, 15, 10) main_layout.addWidget(self.canvas.native, 0, 1, 3, 1) main_layout.addWidget(self.dims, 3, 1) main_layout.addWidget(self.controls, 0, 0) main_layout.addWidget(self.layerButtons, 1, 0) main_layout.addWidget(self.layers, 2, 0) main_layout.addWidget(self.viewerButtons, 3, 0) main_layout.setColumnStretch(1, 1) main_layout.setSpacing(10) main_widget.setLayout(main_layout) self.setOrientation(Qt.Vertical) self.addWidget(main_widget) self._last_visited_dir = str(Path.home()) self._cursors = { "disabled": QCursor( QPixmap(":/icons/cursor/cursor_disabled.png").scaled(20, 20) ), "cross": Qt.CrossCursor, "forbidden": Qt.ForbiddenCursor, "pointing": Qt.PointingHandCursor, "standard": QCursor(), } self._update_palette(viewer.palette) self._key_release_generators = {} self.viewer.events.interactive.connect(self._on_interactive) self.viewer.events.cursor.connect(self._on_cursor) self.viewer.events.reset_view.connect(self._on_reset_view) self.viewer.events.palette.connect( lambda event: self._update_palette(event.palette) ) self.viewer.layers.events.reordered.connect(self._reorder_layers) self.viewer.layers.events.added.connect(self._add_layer) self.viewer.layers.events.removed.connect(self._remove_layer) self.viewer.dims.events.camera.connect(lambda event: self._update_camera()) # stop any animations whenever the layers change self.viewer.events.layers_change.connect(lambda x: self.dims.stop()) self.setAcceptDrops(True)
https://github.com/napari/napari/issues/691
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'
AttributeError
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()
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()
https://github.com/napari/napari/issues/691
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'
AttributeError
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
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)
https://github.com/napari/napari/issues/691
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'
AttributeError
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)
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)
https://github.com/napari/napari/issues/691
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'
AttributeError
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])
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])
https://github.com/napari/napari/issues/691
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'
AttributeError
def add_image( self, data=None, *, channel_axis=None, rgb=None, is_pyramid=None, colormap=None, contrast_limits=None, gamma=1, interpolation="nearest", rendering="mip", name=None, metadata=None, scale=None, translate=None, opacity=1, blending=None, visible=True, path=None, ): """Add an image layer to the layers list. Parameters ---------- data : array or list of array Image data. Can be N dimensional. If the last dimension has length 3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a list and arrays are decreasing in shape then the data is treated as an image pyramid. channel_axis : int, optional Axis to expand image along. rgb : bool Whether the image is rgb RGB or RGBA. If not specified by user and the last dimension of the data has length 3 or 4 it will be set as `True`. If `False` the image is interpreted as a luminance image. is_pyramid : bool Whether the data is an image pyramid or not. Pyramid data is represented by a list of array like image data. If not specified by the user and if the data is a list of arrays that decrease in shape then it will be taken to be a pyramid. The first image in the list should be the largest. colormap : str, vispy.Color.Colormap, tuple, dict, list Colormaps to use for luminance images. If a string must be the name of a supported colormap from vispy or matplotlib. If a tuple the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict the key must be a string to assign as a name to a colormap and the value must be a Colormap. If a list then must be same length as the axis that is being expanded as channels, and each colormap is applied to each new image layer. contrast_limits : list (2,) Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image. If list of lists then must be same length as the axis that is being expanded and then each colormap is applied to each image. gamma : list, float Gamma correction for determining colormap linearity. Defaults to 1. If a list then must be same length as the axis that is being expanded and then each entry in the list is applied to each image. interpolation : str Interpolation mode used by vispy. Must be one of our supported modes. name : str Name of the layer. metadata : dict Layer metadata. scale : tuple of float Scale factors for the layer. translate : tuple of float Translation values for the layer. opacity : float Opacity of the layer visual, between 0.0 and 1.0. blending : str One of a list of preset blending modes that determines how RGB and alpha values of the layer visual get mixed. Allowed values are {'opaque', 'translucent', and 'additive'}. visible : bool Whether the layer visual is currently being displayed. path : str or list of str Path or list of paths to image data. Returns ------- layer : :class:`napari.layers.Image` or list The newly-created image layer or list of image layers. """ if data is None and path is None: raise ValueError("One of either data or path must be provided") elif data is not None and path is not None: raise ValueError("Only one of data or path can be provided") elif data is None: data = io.magic_imread(path) if channel_axis is None: if colormap is None: colormap = "gray" if blending is None: blending = "translucent" layer = layers.Image( data, rgb=rgb, is_pyramid=is_pyramid, colormap=colormap, contrast_limits=contrast_limits, gamma=gamma, interpolation=interpolation, rendering=rendering, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.add_layer(layer) return layer else: if is_pyramid: n_channels = data[0].shape[channel_axis] else: n_channels = data.shape[channel_axis] name = ensure_iterable(name) if blending is None: blending = "additive" if colormap is None: if n_channels < 3: colormap = colormaps.MAGENTA_GREEN else: colormap = itertools.cycle(colormaps.CYMRGB) else: colormap = ensure_iterable(colormap) # If one pair of clim values is passed then need to iterate them to # all layers. if contrast_limits is not None and not is_iterable(contrast_limits[0]): contrast_limits = itertools.repeat(contrast_limits) else: contrast_limits = ensure_iterable(contrast_limits) gamma = ensure_iterable(gamma) layer_list = [] zipped_args = zip(range(n_channels), colormap, contrast_limits, gamma, name) for i, cmap, clims, _gamma, name in zipped_args: if is_pyramid: image = [data[j].take(i, axis=channel_axis) for j in range(len(data))] else: image = data.take(i, axis=channel_axis) layer = layers.Image( image, rgb=rgb, colormap=cmap, contrast_limits=clims, gamma=_gamma, interpolation=interpolation, rendering=rendering, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.add_layer(layer) layer_list.append(layer) return layer_list
def add_image( self, data=None, *, channel_axis=None, rgb=None, is_pyramid=None, colormap=None, contrast_limits=None, gamma=1, interpolation="nearest", rendering="mip", name=None, metadata=None, scale=None, translate=None, opacity=1, blending=None, visible=True, path=None, ): """Add an image layer to the layers list. Parameters ---------- data : array or list of array Image data. Can be N dimensional. If the last dimension has length 3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a list and arrays are decreasing in shape then the data is treated as an image pyramid. channel_axis : int, optional Axis to expand image along. rgb : bool Whether the image is rgb RGB or RGBA. If not specified by user and the last dimension of the data has length 3 or 4 it will be set as `True`. If `False` the image is interpreted as a luminance image. is_pyramid : bool Whether the data is an image pyramid or not. Pyramid data is represented by a list of array like image data. If not specified by the user and if the data is a list of arrays that decrease in shape then it will be taken to be a pyramid. The first image in the list should be the largest. colormap : str, vispy.Color.Colormap, tuple, dict, list Colormaps to use for luminance images. If a string must be the name of a supported colormap from vispy or matplotlib. If a tuple the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict the key must be a string to assign as a name to a colormap and the value must be a Colormap. If a list then must be same length as the axis that is being expanded as channels, and each colormap is applied to each new image layer. contrast_limits : list (2,) Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image. If list of lists then must be same length as the axis that is being expanded and then each colormap is applied to each image. gamma : list, float Gamma correction for determining colormap linearity. Defaults to 1. If a list then must be same length as the axis that is being expanded and then each entry in the list is applied to each image. interpolation : str Interpolation mode used by vispy. Must be one of our supported modes. name : str Name of the layer. metadata : dict Layer metadata. scale : tuple of float Scale factors for the layer. translate : tuple of float Translation values for the layer. opacity : float Opacity of the layer visual, between 0.0 and 1.0. blending : str One of a list of preset blending modes that determines how RGB and alpha values of the layer visual get mixed. Allowed values are {'opaque', 'translucent', and 'additive'}. visible : bool Whether the layer visual is currently being displayed. path : str or list of str Path or list of paths to image data. Paths can be passed as strings or `pathlib.Path` instances. Returns ------- layer : :class:`napari.layers.Image` or list The newly-created image layer or list of image layers. """ if data is None and path is None: raise ValueError("One of either data or path must be provided") elif data is not None and path is not None: raise ValueError("Only one of data or path can be provided") elif data is None: data = io.magic_imread(path) if channel_axis is None: if colormap is None: colormap = "gray" if blending is None: blending = "translucent" layer = layers.Image( data, rgb=rgb, is_pyramid=is_pyramid, colormap=colormap, contrast_limits=contrast_limits, gamma=gamma, interpolation=interpolation, rendering=rendering, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.add_layer(layer) return layer else: if is_pyramid: n_channels = data[0].shape[channel_axis] else: n_channels = data.shape[channel_axis] name = ensure_iterable(name) if blending is None: blending = "additive" if colormap is None: if n_channels < 3: colormap = colormaps.MAGENTA_GREEN else: colormap = itertools.cycle(colormaps.CYMRGB) else: colormap = ensure_iterable(colormap) # If one pair of clim values is passed then need to iterate them to # all layers. if contrast_limits is not None and not is_iterable(contrast_limits[0]): contrast_limits = itertools.repeat(contrast_limits) else: contrast_limits = ensure_iterable(contrast_limits) gamma = ensure_iterable(gamma) layer_list = [] zipped_args = zip(range(n_channels), colormap, contrast_limits, gamma, name) for i, cmap, clims, _gamma, name in zipped_args: if is_pyramid: image = [ np.take(data[j], i, axis=channel_axis) for j in range(len(data)) ] else: image = np.take(data, i, axis=channel_axis) layer = layers.Image( image, rgb=rgb, colormap=cmap, contrast_limits=clims, gamma=_gamma, interpolation=interpolation, rendering=rendering, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.add_layer(layer) layer_list.append(layer) return layer_list
https://github.com/napari/napari/issues/691
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'
AttributeError
def magic_imread(filenames, *, use_dask=None, stack=True): """Dispatch the appropriate reader given some files. The files are assumed to all have the same shape. Parameters ------- filenames : list List of filenames or directories to be opened use_dask : bool Whether to use dask to create a lazy array, rather than NumPy. Default of None will resolve to True if filenames contains more than one image, False otherwise. stack : bool Whether to stack the images in multiple files into a single array. If False, a list of arrays will be returned. Returns ------- image : array-like Array or list of images """ if len(filenames) == 0: return None if isinstance(filenames, str): filenames = [filenames] # ensure list # replace folders with their contents filenames_expanded = [] for filename in filenames: ext = os.path.splitext(filename)[-1] # zarr files are folders, but should be read as 1 file if os.path.isdir(filename) and not ext == ".zarr": dir_contents = sorted( glob(os.path.join(filename, "*.*")), key=alphanumeric_key ) # remove subdirectories dir_contents_files = filter(lambda f: not os.path.isdir(f), dir_contents) filenames_expanded.extend(dir_contents_files) else: filenames_expanded.append(filename) if use_dask is None: use_dask = len(filenames_expanded) > 1 # then, read in images images = [] shape = None for filename in filenames_expanded: ext = os.path.splitext(filename)[-1] if ext == ".zarr": image, zarr_shape = read_zarr_dataset(filename) if shape is None: shape = zarr_shape else: if shape is None: image = io.imread(filename) shape = image.shape dtype = image.dtype if use_dask: image = da.from_delayed( delayed(io.imread)(filename), shape=shape, dtype=dtype ) elif len(images) > 0: # not read by shape clause image = io.imread(filename) images.append(image) if len(images) == 1: image = images[0] else: if stack: if use_dask: image = da.stack(images) else: image = np.stack(images) else: image = images # return a list return image
def magic_imread(filenames, *, use_dask=None, stack=True): """Dispatch the appropriate reader given some files. The files are assumed to all have the same shape. Parameters ------- filenames : list List of filenames or directories to be opened. A list of `pathlib.Path` objects and a single filename or `Path` object are also accepted. use_dask : bool Whether to use dask to create a lazy array, rather than NumPy. Default of None will resolve to True if filenames contains more than one image, False otherwise. stack : bool Whether to stack the images in multiple files into a single array. If False, a list of arrays will be returned. Returns ------- image : array-like Array or list of images """ # cast Path to string if isinstance(filenames, Path): filenames = filenames.as_posix() if len(filenames) == 0: return None if isinstance(filenames, str): filenames = [filenames] # ensure list # replace folders with their contents filenames_expanded = [] for filename in filenames: ext = os.path.splitext(filename)[-1] # zarr files are folders, but should be read as 1 file if os.path.isdir(filename) and not ext == ".zarr": dir_contents = sorted( glob(os.path.join(filename, "*.*")), key=alphanumeric_key ) # remove subdirectories dir_contents_files = filter(lambda f: not os.path.isdir(f), dir_contents) filenames_expanded.extend(dir_contents_files) else: filenames_expanded.append(filename) if use_dask is None: use_dask = len(filenames_expanded) > 1 # then, read in images images = [] shape = None for filename in filenames_expanded: ext = os.path.splitext(filename)[-1] if ext == ".zarr": image, zarr_shape = read_zarr_dataset(filename) if shape is None: shape = zarr_shape else: if shape is None: image = io.imread(filename) shape = image.shape dtype = image.dtype if use_dask: image = da.from_delayed( delayed(io.imread)(filename), shape=shape, dtype=dtype ) elif len(images) > 0: # not read by shape clause image = io.imread(filename) images.append(image) if len(images) == 1: image = images[0] else: if stack: if use_dask: image = da.stack(images) else: image = np.stack(images) else: image = images # return a list return image
https://github.com/napari/napari/issues/691
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'
AttributeError
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
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
https://github.com/napari/napari/issues/691
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'
AttributeError
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)]
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)]
https://github.com/napari/napari/issues/691
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'
AttributeError
def view_image( data=None, *, channel_axis=None, rgb=None, is_pyramid=None, colormap=None, contrast_limits=None, gamma=1, interpolation="nearest", rendering="mip", name=None, metadata=None, scale=None, translate=None, opacity=1, blending=None, visible=True, path=None, title="napari", ndisplay=2, order=None, axis_labels=None, ): """Create a viewer and add an image layer. Parameters ---------- data : array or list of array Image data. Can be N dimensional. If the last dimension has length 3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a list and arrays are decreasing in shape then the data is treated as an image pyramid. channel_axis : int, optional Axis to expand image along. rgb : bool Whether the image is rgb RGB or RGBA. If not specified by user and the last dimension of the data has length 3 or 4 it will be set as `True`. If `False` the image is interpreted as a luminance image. is_pyramid : bool Whether the data is an image pyramid or not. Pyramid data is represented by a list of array like image data. If not specified by the user and if the data is a list of arrays that decrease in shape then it will be taken to be a pyramid. The first image in the list should be the largest. colormap : str, vispy.Color.Colormap, tuple, dict, list Colormaps to use for luminance images. If a string must be the name of a supported colormap from vispy or matplotlib. If a tuple the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict the key must be a string to assign as a name to a colormap and the value must be a Colormap. If a list then must be same length as the axis that is being expanded as channels, and each colormap is applied to each new image layer. contrast_limits : list (2,) Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image. If list of lists then must be same length as the axis that is being expanded and then each colormap is applied to each image. gamma : list, float Gamma correction for determining colormap linearity. Defaults to 1. If a list then must be same length as the axis that is being expanded and then each entry in the list is applied to each image. interpolation : str Interpolation mode used by vispy. Must be one of our supported modes. name : str Name of the layer. metadata : dict Layer metadata. scale : tuple of float Scale factors for the layer. translate : tuple of float Translation values for the layer. opacity : float Opacity of the layer visual, between 0.0 and 1.0. blending : str One of a list of preset blending modes that determines how RGB and alpha values of the layer visual get mixed. Allowed values are {'opaque', 'translucent', and 'additive'}. visible : bool Whether the layer visual is currently being displayed. path : str or list of str Path or list of paths to image data. title : string The title of the viewer window. ndisplay : {2, 3} Number of displayed dimensions. order : tuple of int Order in which dimensions are displayed where the last two or last three dimensions correspond to row x column or plane x row x column if ndisplay is 2 or 3. axis_labels : list of str Dimension names. Returns ------- viewer : :class:`napari.Viewer` The newly-created viewer. """ viewer = Viewer( title=title, ndisplay=ndisplay, order=order, axis_labels=axis_labels ) viewer.add_image( data=data, channel_axis=channel_axis, rgb=rgb, is_pyramid=is_pyramid, colormap=colormap, contrast_limits=contrast_limits, gamma=gamma, interpolation=interpolation, rendering=rendering, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, path=path, ) return viewer
def view_image( data=None, *, channel_axis=None, rgb=None, is_pyramid=None, colormap=None, contrast_limits=None, gamma=1, interpolation="nearest", rendering="mip", name=None, metadata=None, scale=None, translate=None, opacity=1, blending=None, visible=True, path=None, title="napari", ndisplay=2, order=None, axis_labels=None, ): """Create a viewer and add an image layer. Parameters ---------- data : array or list of array Image data. Can be N dimensional. If the last dimension has length 3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a list and arrays are decreasing in shape then the data is treated as an image pyramid. channel_axis : int, optional Axis to expand image along. rgb : bool Whether the image is rgb RGB or RGBA. If not specified by user and the last dimension of the data has length 3 or 4 it will be set as `True`. If `False` the image is interpreted as a luminance image. is_pyramid : bool Whether the data is an image pyramid or not. Pyramid data is represented by a list of array like image data. If not specified by the user and if the data is a list of arrays that decrease in shape then it will be taken to be a pyramid. The first image in the list should be the largest. colormap : str, vispy.Color.Colormap, tuple, dict, list Colormaps to use for luminance images. If a string must be the name of a supported colormap from vispy or matplotlib. If a tuple the first value must be a string to assign as a name to a colormap and the second item must be a Colormap. If a dict the key must be a string to assign as a name to a colormap and the value must be a Colormap. If a list then must be same length as the axis that is being expanded as channels, and each colormap is applied to each new image layer. contrast_limits : list (2,) Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image. If list of lists then must be same length as the axis that is being expanded and then each colormap is applied to each image. gamma : list, float Gamma correction for determining colormap linearity. Defaults to 1. If a list then must be same length as the axis that is being expanded and then each entry in the list is applied to each image. interpolation : str Interpolation mode used by vispy. Must be one of our supported modes. name : str Name of the layer. metadata : dict Layer metadata. scale : tuple of float Scale factors for the layer. translate : tuple of float Translation values for the layer. opacity : float Opacity of the layer visual, between 0.0 and 1.0. blending : str One of a list of preset blending modes that determines how RGB and alpha values of the layer visual get mixed. Allowed values are {'opaque', 'translucent', and 'additive'}. visible : bool Whether the layer visual is currently being displayed. path : str or list of str Path or list of paths to image data. Paths can be passed as strings or `pathlib.Path` instances. title : string The title of the viewer window. ndisplay : {2, 3} Number of displayed dimensions. order : tuple of int Order in which dimensions are displayed where the last two or last three dimensions correspond to row x column or plane x row x column if ndisplay is 2 or 3. axis_labels : list of str Dimension names. Returns ------- viewer : :class:`napari.Viewer` The newly-created viewer. """ viewer = Viewer( title=title, ndisplay=ndisplay, order=order, axis_labels=axis_labels ) viewer.add_image( data=data, channel_axis=channel_axis, rgb=rgb, is_pyramid=is_pyramid, colormap=colormap, contrast_limits=contrast_limits, gamma=gamma, interpolation=interpolation, rendering=rendering, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, path=path, ) return viewer
https://github.com/napari/napari/issues/691
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'
AttributeError
def __init__(self, title="napari", ndisplay=2, order=None, axis_labels=None): # instance() returns the singleton instance if it exists, or None app = QApplication.instance() # if None, raise a RuntimeError with the appropriate message if app is None: message = ( "napari requires a Qt event loop to run. To create one, " "try one of the following: \n" " - use the `napari.gui_qt()` context manager. See " "https://github.com/napari/napari/tree/master/examples for" " usage examples.\n" " - In IPython or a local Jupyter instance, use the " "`%gui qt` magic command.\n" " - Launch IPython with the option `--gui=qt`.\n" " - (recommended) in your IPython configuration file, add" " or uncomment the line `c.TerminalIPythonApp.gui = 'qt'`." " Then, restart IPython." ) raise RuntimeError(message) super().__init__( title=title, ndisplay=ndisplay, order=order, axis_labels=axis_labels, ) qt_viewer = QtViewer(self) self.window = Window(qt_viewer) self.screenshot = self.window.qt_viewer.screenshot self.update_console = self.window.qt_viewer.console.push
def __init__(self, title="napari", ndisplay=2, order=None, axis_labels=None): # instance() returns the singleton instance if it exists, or None app = QApplication.instance() # if None, raise a RuntimeError with the appropriate message if app is None: message = ( "napari requires a Qt event loop to run. To create one, " "try one of the following: \n" " - use the `napari.gui_qt()` context manager. See " "https://github.com/napari/napari/tree/master/examples for" " usage examples.\n" " - In IPython or a local Jupyter instance, use the " "`%gui qt` magic command.\n" " - Launch IPython with the option `--gui=qt`.\n" " - (recommended) in your IPython configuration file, add" " or uncomment the line `c.TerminalIPythonApp.gui = 'qt'`." " Then, restart IPython." ) raise RuntimeError(message) super().__init__( title=title, ndisplay=ndisplay, order=order, axis_labels=axis_labels, ) qt_viewer = QtViewer(self) self.window = Window(qt_viewer) self.update_console = self.window.qt_viewer.console.push
https://github.com/napari/napari/issues/691
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'
AttributeError
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)
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)
https://github.com/napari/napari/issues/706
WARNING: Traceback (most recent call last): File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 233, in _open_folder self._add_files([folder]) File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 247, in _add_files self.viewer.add_image(path=filenames) File "/home/jni/projects/napari/napari/components/viewer_model.py", line 485, in add_image data = io.magic_imread(path) File "/home/jni/projects/napari/napari/util/io.py", line 71, in magic_imread image = io.imread(filename) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_io.py", line 48, in imread img = call_plugin('imread', fname, plugin=plugin, **plugin_args) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/manage_plugins.py", line 210, in call_plugin return func(*args, **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_plugins/imageio_plugin.py", line 10, in imread return np.asarray(imageio_imread(*args, **kwargs)) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 264, in imread reader = read(uri, format, "i", **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 182, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i' WARNING:vispy:Traceback (most recent call last): File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 233, in _open_folder self._add_files([folder]) File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 247, in _add_files self.viewer.add_image(path=filenames) File "/home/jni/projects/napari/napari/components/viewer_model.py", line 485, in add_image data = io.magic_imread(path) File "/home/jni/projects/napari/napari/util/io.py", line 71, in magic_imread image = io.imread(filename) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_io.py", line 48, in imread img = call_plugin('imread', fname, plugin=plugin, **plugin_args) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/manage_plugins.py", line 210, in call_plugin return func(*args, **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_plugins/imageio_plugin.py", line 10, in imread return np.asarray(imageio_imread(*args, **kwargs)) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 264, in imread reader = read(uri, format, "i", **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 182, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i' Aborted (core dumped)
ValueError
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])
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])
https://github.com/napari/napari/issues/706
WARNING: Traceback (most recent call last): File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 233, in _open_folder self._add_files([folder]) File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 247, in _add_files self.viewer.add_image(path=filenames) File "/home/jni/projects/napari/napari/components/viewer_model.py", line 485, in add_image data = io.magic_imread(path) File "/home/jni/projects/napari/napari/util/io.py", line 71, in magic_imread image = io.imread(filename) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_io.py", line 48, in imread img = call_plugin('imread', fname, plugin=plugin, **plugin_args) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/manage_plugins.py", line 210, in call_plugin return func(*args, **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_plugins/imageio_plugin.py", line 10, in imread return np.asarray(imageio_imread(*args, **kwargs)) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 264, in imread reader = read(uri, format, "i", **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 182, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i' WARNING:vispy:Traceback (most recent call last): File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 233, in _open_folder self._add_files([folder]) File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 247, in _add_files self.viewer.add_image(path=filenames) File "/home/jni/projects/napari/napari/components/viewer_model.py", line 485, in add_image data = io.magic_imread(path) File "/home/jni/projects/napari/napari/util/io.py", line 71, in magic_imread image = io.imread(filename) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_io.py", line 48, in imread img = call_plugin('imread', fname, plugin=plugin, **plugin_args) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/manage_plugins.py", line 210, in call_plugin return func(*args, **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/skimage/io/_plugins/imageio_plugin.py", line 10, in imread return np.asarray(imageio_imread(*args, **kwargs)) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 264, in imread reader = read(uri, format, "i", **kwargs) File "/home/jni/miniconda3/envs/f7/lib/python3.7/site-packages/imageio/core/functions.py", line 182, in get_reader "Could not find a format to read the specified file " "in mode %r" % mode ValueError: Could not find a format to read the specified file in mode 'i' Aborted (core dumped)
ValueError
def __init__(self, layer, node): super().__init__() self.layer = layer self.node = node self._position = (0,) * self.layer.dims.ndisplay self.camera = None self.layer.events.refresh.connect(lambda e: self.node.update()) self.layer.events.set_data.connect(lambda e: self._on_data_change()) self.layer.events.visible.connect(lambda e: self._on_visible_change()) self.layer.events.opacity.connect(lambda e: self._on_opacity_change()) self.layer.events.blending.connect(lambda e: self._on_blending_change()) self.layer.events.scale.connect(lambda e: self._on_scale_change()) self.layer.events.translate.connect(lambda e: self._on_translate_change())
def __init__(self, layer, node): super().__init__() self.layer = layer self.node = node self._position = (0,) * self.layer.ndim self.camera = None self.layer.events.refresh.connect(lambda e: self.node.update()) self.layer.events.set_data.connect(lambda e: self._on_data_change()) self.layer.events.visible.connect(lambda e: self._on_visible_change()) self.layer.events.opacity.connect(lambda e: self._on_opacity_change()) self.layer.events.blending.connect(lambda e: self._on_blending_change()) self.layer.events.scale.connect(lambda e: self._on_scale_change()) self.layer.events.translate.connect(lambda e: self._on_translate_change())
https://github.com/napari/napari/issues/678
(1, 10, 2, 15, 256, 256, 1) BTCZYX0 (1, 10, 2, 15, 256, 256) Dim PosT : 1 Dim PosZ : 3 Dim PosC : 2 Scale Factors XYZ: [1, 1, 1, 3.516, 1, 1] (1, 10, 15, 256, 256) Adding Channel: AF555 (1, 10, 15, 256, 256) Adding Channel: AF488 WARNING: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_qt\qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_qt\qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\dims.py", line 205, in ndisplay self.events.ndisplay() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 508, in __call__ self._invoke_callback(cb, event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 529, in _invoke_callback cb_event=(cb, event), File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 523, in _invoke_callback cb(event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\viewer_model.py", line 89, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\viewer_model.py", line 1018, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\dims.py", line 205, in ndisplay self.events.ndisplay() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 508, in __call__ self._invoke_callback(cb, event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 529, in _invoke_callback cb_event=(cb, event), File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 523, in _invoke_callback cb(event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\layers\base\base.py", line 174, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\layers\base\base.py", line 372, in _update_dims self._set_view_slice() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\layers\image\image.py", line 502, in _set_view_slice self.events.set_data() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 508, in __call__ self._invoke_callback(cb, event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 529, in _invoke_callback cb_event=(cb, event), File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 523, in _invoke_callback cb(event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_base_layer.py", line 46, in <lambda> self.layer.events.set_data.connect(lambda e: self._on_data_change()) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 59, in _on_data_change self._on_display_change() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 48, in _on_display_change self.reset() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 216, in reset self._reset_base() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_base_layer.py", line 165, in _reset_base self._on_scale_change() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 123, in _on_scale_change self.layer.position = self._transform_position(self._position) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_base_layer.py", line 153, in _transform_position transform.map(list(position))[: len(self.layer.dims.displayed)] File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\vispy\visuals\transforms\chain.py", line 148, in map coords = tr.map(coords) File "<decorator-gen-4>", line 2, in imap File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\vispy\visuals\transforms\_util.py", line 111, in arg_to_vec4 arg = as_vec4(arg) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\vispy\visuals\transforms\_util.py", line 81, in as_vec4 % obj.shape) TypeError: not all arguments converted during string formatting WARNING:vispy:Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_qt\qt_viewer_buttons.py", line 173, in <lambda> lambda state=self: self.change_ndisplay(state) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_qt\qt_viewer_buttons.py", line 178, in change_ndisplay self.viewer.dims.ndisplay = 3 File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\dims.py", line 205, in ndisplay self.events.ndisplay() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 508, in __call__ self._invoke_callback(cb, event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 529, in _invoke_callback cb_event=(cb, event), File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 523, in _invoke_callback cb(event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\viewer_model.py", line 89, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_layers()) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\viewer_model.py", line 1018, in _update_layers layer.dims.ndisplay = self.dims.ndisplay File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\components\dims.py", line 205, in ndisplay self.events.ndisplay() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 508, in __call__ self._invoke_callback(cb, event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 529, in _invoke_callback cb_event=(cb, event), File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 523, in _invoke_callback cb(event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\layers\base\base.py", line 174, in <lambda> self.dims.events.ndisplay.connect(lambda e: self._update_dims()) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\layers\base\base.py", line 372, in _update_dims self._set_view_slice() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\layers\image\image.py", line 502, in _set_view_slice self.events.set_data() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 508, in __call__ self._invoke_callback(cb, event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 529, in _invoke_callback cb_event=(cb, event), File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\util\event.py", line 523, in _invoke_callback cb(event) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_base_layer.py", line 46, in <lambda> self.layer.events.set_data.connect(lambda e: self._on_data_change()) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 59, in _on_data_change self._on_display_change() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 48, in _on_display_change self.reset() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 216, in reset self._reset_base() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_base_layer.py", line 165, in _reset_base self._on_scale_change() File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_image_layer.py", line 123, in _on_scale_change self.layer.position = self._transform_position(self._position) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\napari\_vispy\vispy_base_layer.py", line 153, in _transform_position transform.map(list(position))[: len(self.layer.dims.displayed)] File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\vispy\visuals\transforms\chain.py", line 148, in map coords = tr.map(coords) File "<decorator-gen-4>", line 2, in imap File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\vispy\visuals\transforms\_util.py", line 111, in arg_to_vec4 arg = as_vec4(arg) File "C:\ProgramData\Anaconda3\envs\imageanalysis\lib\site-packages\vispy\visuals\transforms\_util.py", line 81, in as_vec4 % obj.shape) TypeError: not all arguments converted during string formatting
TypeError
def _update_thumbnail(self): """Update thumbnail with current image data and colormap.""" if self.dims.ndisplay == 3 and self.dims.ndim > 2: image = np.max(self._data_thumbnail, axis=0) else: image = self._data_thumbnail # float16 not supported by ndi.zoom dtype = np.dtype(image.dtype) if dtype in [np.dtype(np.float16)]: image = image.astype(np.float32) raw_zoom_factor = np.divide(self._thumbnail_shape[:2], image.shape[:2]).min() new_shape = np.clip( raw_zoom_factor * np.array(image.shape[:2]), 1, # smallest side should be 1 pixel wide self._thumbnail_shape[:2], ) zoom_factor = tuple(new_shape / image.shape[:2]) if self.rgb: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom(image, zoom_factor + (1,), prefilter=False, order=0) if image.shape[2] == 4: # image is RGBA colormapped = np.copy(downsampled) colormapped[..., 3] = downsampled[..., 3] * self.opacity if downsampled.dtype == np.uint8: colormapped = colormapped.astype(np.uint8) else: # image is RGB if downsampled.dtype == np.uint8: alpha = np.full( downsampled.shape[:2] + (1,), int(255 * self.opacity), dtype=np.uint8, ) else: alpha = np.full(downsampled.shape[:2] + (1,), self.opacity) colormapped = np.concatenate([downsampled, alpha], axis=2) else: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom(image, zoom_factor, prefilter=False, order=0) low, high = self.contrast_limits downsampled = np.clip(downsampled, low, high) color_range = high - low if color_range != 0: downsampled = (downsampled - low) / color_range downsampled = downsampled**self.gamma color_array = self.colormap[1][downsampled.ravel()] colormapped = color_array.rgba.reshape(downsampled.shape + (4,)) colormapped[..., 3] *= self.opacity self.thumbnail = colormapped
def _update_thumbnail(self): """Update thumbnail with current image data and colormap.""" if self.dims.ndisplay == 3 and self.dims.ndim > 2: image = np.max(self._data_thumbnail, axis=0) else: image = self._data_thumbnail # float16 not supported by ndi.zoom dtype = np.dtype(image.dtype) if dtype in [np.dtype(np.float16)]: image = image.astype(np.float32) zoom_factor = np.divide(self._thumbnail_shape[:2], image.shape[:2]).min() if self.rgb: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom( image, (zoom_factor, zoom_factor, 1), prefilter=False, order=0, ) if image.shape[2] == 4: # image is RGBA colormapped = np.copy(downsampled) colormapped[..., 3] = downsampled[..., 3] * self.opacity if downsampled.dtype == np.uint8: colormapped = colormapped.astype(np.uint8) else: # image is RGB if downsampled.dtype == np.uint8: alpha = np.full( downsampled.shape[:2] + (1,), int(255 * self.opacity), dtype=np.uint8, ) else: alpha = np.full(downsampled.shape[:2] + (1,), self.opacity) colormapped = np.concatenate([downsampled, alpha], axis=2) else: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom(image, zoom_factor, prefilter=False, order=0) low, high = self.contrast_limits downsampled = np.clip(downsampled, low, high) color_range = high - low if color_range != 0: downsampled = (downsampled - low) / color_range downsampled = downsampled**self.gamma color_array = self.colormap[1][downsampled.ravel()] colormapped = color_array.rgba.reshape(downsampled.shape + (4,)) colormapped[..., 3] *= self.opacity self.thumbnail = colormapped
https://github.com/napari/napari/issues/641
WARNING: Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 121, in <lambda> self.clicked.connect(lambda: self.viewer.dims._roll()) File "/usr/lib/python3.7/site-packages/napari/components/dims.py", line 340, in _roll self.order = np.roll(self.order, 1) File "/usr/lib/python3.7/site-packages/napari/components/dims.py", line 130, in order self.events.order() File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 523, in _invoke_callback cb(event) File "/usr/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.order.connect(lambda e: self._update_layers()) File "/usr/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1045, in _update_layers layer.dims.order = order File "/usr/lib/python3.7/site-packages/napari/components/dims.py", line 130, in order self.events.order() File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 523, in _invoke_callback cb(event) File "/usr/lib/python3.7/site-packages/napari/layers/base/base.py", line 176, in <lambda> self.dims.events.order.connect(lambda e: self._update_dims()) File "/usr/lib/python3.7/site-packages/napari/layers/base/base.py", line 373, in _update_dims self._set_view_slice() File "/usr/lib/python3.7/site-packages/napari/layers/image/image.py", line 477, in _set_view_slice self._update_thumbnail() File "/usr/lib/python3.7/site-packages/napari/layers/image/image.py", line 536, in _update_thumbnail color_array = self.colormap[1][downsampled.ravel()] File "/usr/lib/python3.7/site-packages/vispy/color/colormap.py", line 293, in __getitem__ return ColorArray(colors) File "/usr/lib/python3.7/site-packages/vispy/color/color_array.py", line 148, in __init__ rgba = _user_to_rgba(color, clip=clip) File "/usr/lib/python3.7/site-packages/vispy/color/color_array.py", line 61, in _user_to_rgba if color.min() < 0 or color.max() > 1: File "/usr/lib/python3.7/site-packages/numpy/core/_methods.py", line 32, in _amin return umr_minimum(a, axis, None, out, keepdims, initial) ValueError: zero-size array to reduction operation minimum which has no identity WARNING:vispy:Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/napari/_qt/qt_viewer_buttons.py", line 121, in <lambda> self.clicked.connect(lambda: self.viewer.dims._roll()) File "/usr/lib/python3.7/site-packages/napari/components/dims.py", line 340, in _roll self.order = np.roll(self.order, 1) File "/usr/lib/python3.7/site-packages/napari/components/dims.py", line 130, in order self.events.order() File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 523, in _invoke_callback cb(event) File "/usr/lib/python3.7/site-packages/napari/components/viewer_model.py", line 88, in <lambda> self.dims.events.order.connect(lambda e: self._update_layers()) File "/usr/lib/python3.7/site-packages/napari/components/viewer_model.py", line 1045, in _update_layers layer.dims.order = order File "/usr/lib/python3.7/site-packages/napari/components/dims.py", line 130, in order self.events.order() File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 508, in __call__ self._invoke_callback(cb, event) File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 529, in _invoke_callback cb_event=(cb, event), File "/usr/lib/python3.7/site-packages/napari/util/event.py", line 523, in _invoke_callback cb(event) File "/usr/lib/python3.7/site-packages/napari/layers/base/base.py", line 176, in <lambda> self.dims.events.order.connect(lambda e: self._update_dims()) File "/usr/lib/python3.7/site-packages/napari/layers/base/base.py", line 373, in _update_dims self._set_view_slice() File "/usr/lib/python3.7/site-packages/napari/layers/image/image.py", line 477, in _set_view_slice self._update_thumbnail() File "/usr/lib/python3.7/site-packages/napari/layers/image/image.py", line 536, in _update_thumbnail color_array = self.colormap[1][downsampled.ravel()] File "/usr/lib/python3.7/site-packages/vispy/color/colormap.py", line 293, in __getitem__ return ColorArray(colors) File "/usr/lib/python3.7/site-packages/vispy/color/color_array.py", line 148, in __init__ rgba = _user_to_rgba(color, clip=clip) File "/usr/lib/python3.7/site-packages/vispy/color/color_array.py", line 61, in _user_to_rgba if color.min() < 0 or color.max() > 1: File "/usr/lib/python3.7/site-packages/numpy/core/_methods.py", line 32, in _amin return umr_minimum(a, axis, None, out, keepdims, initial) ValueError: zero-size array to reduction operation minimum which has no identity [1] 16296 abort (core dumped) napari FITC.tif
ValueError
def __init__( self, data, *, rgb=None, is_pyramid=None, colormap="gray", contrast_limits=None, interpolation="nearest", rendering="mip", name=None, metadata=None, scale=None, translate=None, opacity=1, blending="translucent", visible=True, ): if isinstance(data, types.GeneratorType): data = list(data) ndim, rgb, is_pyramid, data_pyramid = get_pyramid_and_rgb( data, pyramid=is_pyramid, rgb=rgb ) super().__init__( ndim, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.events.add( contrast_limits=Event, colormap=Event, interpolation=Event, rendering=Event, ) # Set data self.is_pyramid = is_pyramid self.rgb = rgb self._data = data self._data_pyramid = data_pyramid self._top_left = np.zeros(ndim, dtype=int) if self.is_pyramid: self._data_level = len(data_pyramid) - 1 else: self._data_level = 0 # Intitialize image views and thumbnails with zeros if self.rgb: self._data_view = np.zeros((1,) * self.dims.ndisplay + (self.shape[-1],)) else: self._data_view = np.zeros((1,) * self.dims.ndisplay) self._data_thumbnail = self._data_view # Set contrast_limits and colormaps self._colormap_name = "" self._contrast_limits_msg = "" if contrast_limits is None: if self.is_pyramid: input_data = self._data_pyramid[-1] else: input_data = self.data self._contrast_limits_range = calc_data_range(input_data) else: self._contrast_limits_range = contrast_limits self._contrast_limits = copy(self._contrast_limits_range) self.colormap = colormap self.contrast_limits = self._contrast_limits self.interpolation = interpolation self.rendering = rendering # Trigger generation of view slice and thumbnail self._update_dims()
def __init__( self, data, *, rgb=None, is_pyramid=None, colormap="gray", contrast_limits=None, interpolation="nearest", rendering="mip", name=None, metadata=None, scale=None, translate=None, opacity=1, blending="translucent", visible=True, ): ndim, rgb, is_pyramid, data_pyramid = get_pyramid_and_rgb( data, pyramid=is_pyramid, rgb=rgb ) super().__init__( ndim, name=name, metadata=metadata, scale=scale, translate=translate, opacity=opacity, blending=blending, visible=visible, ) self.events.add( contrast_limits=Event, colormap=Event, interpolation=Event, rendering=Event, ) # Set data self.is_pyramid = is_pyramid self.rgb = rgb self._data = data self._data_pyramid = data_pyramid self._top_left = np.zeros(ndim, dtype=int) if self.is_pyramid: self._data_level = len(data_pyramid) - 1 else: self._data_level = 0 # Intitialize image views and thumbnails with zeros if self.rgb: self._data_view = np.zeros((1,) * self.dims.ndisplay + (self.shape[-1],)) else: self._data_view = np.zeros((1,) * self.dims.ndisplay) self._data_thumbnail = self._data_view # Set contrast_limits and colormaps self._colormap_name = "" self._contrast_limits_msg = "" if contrast_limits is None: if self.is_pyramid: input_data = self._data_pyramid[-1] else: input_data = self.data self._contrast_limits_range = calc_data_range(input_data) else: self._contrast_limits_range = contrast_limits self._contrast_limits = copy(self._contrast_limits_range) self.colormap = colormap self.contrast_limits = self._contrast_limits self.interpolation = interpolation self.rendering = rendering # Trigger generation of view slice and thumbnail self._update_dims()
https://github.com/napari/napari/issues/563
regions <xarray.Regions 'array-baa123768d7ef2a6d2cdfa885e8f3eaa' (x_region: 31725, y_region: 51669)> array([[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], dtype=int16) Dimensions without coordinates: x_region, y_region Attributes: assay: osmFISH authors: ['Simone Codeluppi', 'Lars E. Borm', 'Amit Zeisel', 'G... organism: mouse publication_name: Spatial organization of the somatosensory cortex revea... publication_url: https://www.nature.com/articles/s41592-018-0175-z sample_type: somatosensory cortex year: 2018 pyramid = tuple(pyramid_gaussian(regions), multichannel=False) [i.shape for i in pyramid] [(31725, 51669), (15863, 25835), (7932, 12918), (3966, 6459), (1983, 3230), (992, 1615), (496, 808), (248, 404), (124, 202), (62, 101), (31, 51), (16, 26), (8, 13), (4, 7), (2, 4), (1, 2), (1, 1)] viewer = napari.Viewer() viewer.add_image(np.asarray(pyramid), is_pyramid=True) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-35-665dfea0cb05> in <module> ----> 1 viewer.add_image(np.asarray(pyramid), is_pyramid=True) /usr/local/lib/python3.7/site-packages/napari/components/viewer_model.py in add_image(self, data, rgb, is_pyramid, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 426 opacity=opacity, 427 blending=blending, --> 428 visible=visible, 429 ) 430 self.add_layer(layer) /usr/local/lib/python3.7/site-packages/napari/layers/image/image.py in __init__(self, data, rgb, is_pyramid, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 185 else: 186 input_data = self.data --> 187 self._contrast_limits_range = calc_data_range(input_data) 188 else: 189 self._contrast_limits_range = contrast_limits /usr/local/lib/python3.7/site-packages/napari/util/misc.py in calc_data_range(data) 268 reduced_data = data 269 --> 270 min_val = reduced_data.min() 271 max_val = reduced_data.max() 272 /usr/local/lib/python3.7/site-packages/numpy/core/_methods.py in _amin(a, axis, out, keepdims, initial) 30 def _amin(a, axis=None, out=None, keepdims=False, 31 initial=_NoValue): ---> 32 return umr_minimum(a, axis, None, out, keepdims, initial) 33 34 def _sum(a, axis=None, dtype=None, out=None, keepdims=False, ValueError: operands could not be broadcast together with shapes (31725,51669) (15863,25835)
ValueError
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
def is_pyramid(data): """If data is a list of arrays of decreasing size.""" if isinstance(data, list): size = [np.prod(d.shape) for d in data] return np.all(size[:-1] > size[1:]) else: return False
https://github.com/napari/napari/issues/563
regions <xarray.Regions 'array-baa123768d7ef2a6d2cdfa885e8f3eaa' (x_region: 31725, y_region: 51669)> array([[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], dtype=int16) Dimensions without coordinates: x_region, y_region Attributes: assay: osmFISH authors: ['Simone Codeluppi', 'Lars E. Borm', 'Amit Zeisel', 'G... organism: mouse publication_name: Spatial organization of the somatosensory cortex revea... publication_url: https://www.nature.com/articles/s41592-018-0175-z sample_type: somatosensory cortex year: 2018 pyramid = tuple(pyramid_gaussian(regions), multichannel=False) [i.shape for i in pyramid] [(31725, 51669), (15863, 25835), (7932, 12918), (3966, 6459), (1983, 3230), (992, 1615), (496, 808), (248, 404), (124, 202), (62, 101), (31, 51), (16, 26), (8, 13), (4, 7), (2, 4), (1, 2), (1, 1)] viewer = napari.Viewer() viewer.add_image(np.asarray(pyramid), is_pyramid=True) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-35-665dfea0cb05> in <module> ----> 1 viewer.add_image(np.asarray(pyramid), is_pyramid=True) /usr/local/lib/python3.7/site-packages/napari/components/viewer_model.py in add_image(self, data, rgb, is_pyramid, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 426 opacity=opacity, 427 blending=blending, --> 428 visible=visible, 429 ) 430 self.add_layer(layer) /usr/local/lib/python3.7/site-packages/napari/layers/image/image.py in __init__(self, data, rgb, is_pyramid, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 185 else: 186 input_data = self.data --> 187 self._contrast_limits_range = calc_data_range(input_data) 188 else: 189 self._contrast_limits_range = contrast_limits /usr/local/lib/python3.7/site-packages/napari/util/misc.py in calc_data_range(data) 268 reduced_data = data 269 --> 270 min_val = reduced_data.min() 271 max_val = reduced_data.max() 272 /usr/local/lib/python3.7/site-packages/numpy/core/_methods.py in _amin(a, axis, out, keepdims, initial) 30 def _amin(a, axis=None, out=None, keepdims=False, 31 initial=_NoValue): ---> 32 return umr_minimum(a, axis, None, out, keepdims, initial) 33 34 def _sum(a, axis=None, dtype=None, out=None, keepdims=False, ValueError: operands could not be broadcast together with shapes (31725,51669) (15863,25835)
ValueError
def get_pyramid_and_rgb(data, pyramid=None, rgb=None): """Check if data is or needs to be a pyramid and make one if needed. Parameters ---------- data : array, list, or tuple Data to be checked if pyramid or if needs to be turned into a pyramid. pyramid : bool, optional Value that can force data to be considered as a pyramid or not, otherwise computed. rgb : bool, optional Value that can force data to be considered as a rgb, otherwise computed. Returns ------- ndim : int Dimensionality of the data. rgb : bool If data is rgb. pyramid : bool If data is a pyramid or a pyramid has been generated. data_pyramid : list or None If None then data is not and does not need to be a pyramid. Otherwise is a list of arrays where each array is a level of the pyramid. """ # Determine if data currently is a pyramid currently_pyramid = is_pyramid(data) if currently_pyramid: shapes = [d.shape for d in data] init_shape = shapes[0] else: init_shape = data.shape # Determine if rgb, and determine dimensionality if rgb is False: pass else: # If rgb is True or None then guess if rgb # allowed or not, and if allowed set it to be True rgb_guess = is_rgb(init_shape) if rgb and rgb_guess is False: raise ValueError( "Non rgb or rgba data was passed, but rgb data was requested." ) else: rgb = rgb_guess if rgb: ndim = len(init_shape) - 1 else: ndim = len(init_shape) if pyramid is False: if currently_pyramid: raise ValueError( "Non pyramided data was requested, but pyramid data was passed" ) else: data_pyramid = None else: if currently_pyramid: data_pyramid = trim_pyramid(data) pyramid = True else: # Guess if data should be pyramid or if a pyramid was requested if pyramid: pyr_axes = [True] * ndim else: pyr_axes = should_be_pyramid(data.shape) if np.any(pyr_axes): pyramid = True # Set axes to be downsampled to have a factor of 2 downscale = np.ones(len(data.shape)) downscale[pyr_axes] = 2 largest = np.min(np.array(data.shape)[pyr_axes]) # Determine number of downsample steps needed max_layer = np.floor(np.log2(largest) - 9).astype(int) data_pyramid = fast_pyramid( data, downscale=downscale, max_layer=max_layer ) data_pyramid = trim_pyramid(data_pyramid) else: data_pyramid = None pyramid = False return ndim, rgb, pyramid, data_pyramid
def get_pyramid_and_rgb(data, pyramid=None, rgb=None): """Check if data is or needs to be a pyramid and make one if needed. Parameters ---------- data : array or list Data to be checked if pyramid or if needs to be turned into a pyramid. pyramid : bool, optional Value that can force data to be considered as a pyramid or not, otherwise computed. rgb : bool, optional Value that can force data to be considered as a rgb, otherwise computed. Returns ------- ndim : int Dimensionality of the data. rgb : bool If data is rgb. pyramid : bool If data is a pyramid or a pyramid has been generated. data_pyramid : list or None If None then data is not and does not need to be a pyramid. Otherwise is a list of arrays where each array is a level of the pyramid. """ # Determine if data currently is a pyramid currently_pyramid = is_pyramid(data) if currently_pyramid: init_shape = data[0].shape else: init_shape = data.shape # Determine if rgb, and determine dimensionality if rgb is False: pass else: # If rgb is True or None then guess if rgb # allowed or not, and if allowed set it to be True rgb = is_rgb(init_shape) if rgb: ndim = len(init_shape) - 1 else: ndim = len(init_shape) if pyramid is False: if currently_pyramid: raise ValueError( """Non pyramided data was requested, but pyramid data was passed""" ) else: data_pyramid = None else: if currently_pyramid: data_pyramid = trim_pyramid(data) pyramid = True else: # Guess if data should be pyramid pyr_axes = should_be_pyramid(data.shape) if np.any(pyr_axes): pyramid = True # Set axes to be downsampled to have a factor of 2 downscale = np.ones(len(data.shape)) downscale[pyr_axes] = 2 largest = np.min(np.array(data.shape)[pyr_axes]) # Determine number of downsample steps needed max_layer = np.floor(np.log2(largest) - 9).astype(int) data_pyramid = fast_pyramid( data, downscale=downscale, max_layer=max_layer ) data_pyramid = trim_pyramid(data_pyramid) else: data_pyramid = None pyramid = False return ndim, rgb, pyramid, data_pyramid
https://github.com/napari/napari/issues/563
regions <xarray.Regions 'array-baa123768d7ef2a6d2cdfa885e8f3eaa' (x_region: 31725, y_region: 51669)> array([[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], dtype=int16) Dimensions without coordinates: x_region, y_region Attributes: assay: osmFISH authors: ['Simone Codeluppi', 'Lars E. Borm', 'Amit Zeisel', 'G... organism: mouse publication_name: Spatial organization of the somatosensory cortex revea... publication_url: https://www.nature.com/articles/s41592-018-0175-z sample_type: somatosensory cortex year: 2018 pyramid = tuple(pyramid_gaussian(regions), multichannel=False) [i.shape for i in pyramid] [(31725, 51669), (15863, 25835), (7932, 12918), (3966, 6459), (1983, 3230), (992, 1615), (496, 808), (248, 404), (124, 202), (62, 101), (31, 51), (16, 26), (8, 13), (4, 7), (2, 4), (1, 2), (1, 1)] viewer = napari.Viewer() viewer.add_image(np.asarray(pyramid), is_pyramid=True) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-35-665dfea0cb05> in <module> ----> 1 viewer.add_image(np.asarray(pyramid), is_pyramid=True) /usr/local/lib/python3.7/site-packages/napari/components/viewer_model.py in add_image(self, data, rgb, is_pyramid, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 426 opacity=opacity, 427 blending=blending, --> 428 visible=visible, 429 ) 430 self.add_layer(layer) /usr/local/lib/python3.7/site-packages/napari/layers/image/image.py in __init__(self, data, rgb, is_pyramid, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 185 else: 186 input_data = self.data --> 187 self._contrast_limits_range = calc_data_range(input_data) 188 else: 189 self._contrast_limits_range = contrast_limits /usr/local/lib/python3.7/site-packages/napari/util/misc.py in calc_data_range(data) 268 reduced_data = data 269 --> 270 min_val = reduced_data.min() 271 max_val = reduced_data.max() 272 /usr/local/lib/python3.7/site-packages/numpy/core/_methods.py in _amin(a, axis, out, keepdims, initial) 30 def _amin(a, axis=None, out=None, keepdims=False, 31 initial=_NoValue): ---> 32 return umr_minimum(a, axis, None, out, keepdims, initial) 33 34 def _sum(a, axis=None, dtype=None, out=None, keepdims=False, ValueError: operands could not be broadcast together with shapes (31725,51669) (15863,25835)
ValueError
def _set_view_slice(self): """Set the view given the indices to slice with.""" if self.multichannel: # if multichannel need to keep the final axis fixed during the # transpose. The index of the final axis depends on how many # axes are displayed. order = self.dims.displayed_order + (self.dims.ndisplay,) else: order = self.dims.displayed_order image = np.asarray(self.data[self.dims.indices]).transpose(order) if self.multichannel and image.dtype.kind == "f": self._data_view = np.clip(image, 0, 1) else: self._data_view = image self._data_thumbnail = self._data_view self._update_thumbnail() self._update_coordinates() self.events.set_data()
def _set_view_slice(self): """Set the view given the indices to slice with.""" if self.multichannel: # if multichannel need to keep the final axis fixed during the # transpose. The index of the final axis depends on how many # axes are displayed. order = self.dims.displayed_order + (self.dims.ndisplay,) else: order = self.dims.displayed_order self._data_view = np.asarray(self.data[self.dims.indices]).transpose(order) self._data_thumbnail = self._data_view self._update_thumbnail() self._update_coordinates() self.events.set_data()
https://github.com/napari/napari/issues/523
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-42-5ae500208e78> in <module> ----> 1 napari.view(array) /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/view_function.py in view(title, metadata, multichannel, contrast_limits, *images, **named_images) 51 metadata=metadata, 52 multichannel=multichannel, ---> 53 contrast_limits=contrast_limits, 54 ) 55 for name, image in named_images.items(): /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/components/viewer_model.py in add_image(self, data, multichannel, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 411 opacity=opacity, 412 blending=blending, --> 413 visible=visible, 414 ) 415 self.add_layer(layer) /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/image/image.py in __init__(self, data, multichannel, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 174 175 # Trigger generation of view slice and thumbnail --> 176 self._update_dims() 177 178 @property /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/base/base.py in _update_dims(self) 313 self.dims.set_range(i, r) 314 --> 315 self._set_view_slice() 316 self._update_coordinates() 317 /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/image/image.py in _set_view_slice(self) 333 334 self._data_thumbnail = self._data_view --> 335 self._update_thumbnail() 336 self._update_coordinates() 337 self.events.set_data() /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/image/image.py in _update_thumbnail(self) 392 colormapped = colormapped.reshape(downsampled.shape + (4,)) 393 colormapped[..., 3] *= self.opacity --> 394 self.thumbnail = colormapped 395 396 def get_value(self): /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/base/base.py in thumbnail(self, thumbnail) 353 with warnings.catch_warnings(): 354 warnings.simplefilter("ignore") --> 355 thumbnail = img_as_ubyte(thumbnail) 356 self._thumbnail = thumbnail 357 self.events.thumbnail() /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/skimage/util/dtype.py in img_as_ubyte(image, force_copy) 484 485 """ --> 486 return convert(image, np.uint8, force_copy) 487 488 /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/skimage/util/dtype.py in convert(image, dtype, force_copy, uniform) 253 254 if np.min(image) < -1.0 or np.max(image) > 1.0: --> 255 raise ValueError("Images of type float must be between -1 and 1.") 256 # floating point -> integer 257 prec_loss() ValueError: Images of type float must be between -1 and 1.
ValueError
def _set_view_slice(self): """Set the view given the indices to slice with.""" nd = self.dims.not_displayed if self.multichannel: # if multichannel need to keep the final axis fixed during the # transpose. The index of the final axis depends on how many # axes are displayed. order = self.dims.displayed_order + (self.dims.ndisplay,) else: order = self.dims.displayed_order # Slice thumbnail indices = np.array(self.dims.indices) downsampled = indices[nd] / self.level_downsamples[-1, nd] downsampled = np.round(downsampled.astype(float)).astype(int) downsampled = np.clip(downsampled, 0, self.level_shapes[-1, nd] - 1) indices[nd] = downsampled image = np.asarray(self.data[-1][tuple(indices)]).transpose(order) if self.multichannel and image.dtype.kind == "f": self._data_thumbnail = np.clip(image, 0, 1) else: self._data_thumbnail = image # Slice currently viewed level indices = np.array(self.dims.indices) level = self.data_level downsampled = indices[nd] / self.level_downsamples[level, nd] downsampled = np.round(downsampled.astype(float)).astype(int) downsampled = np.clip(downsampled, 0, self.level_shapes[level, nd] - 1) indices[nd] = downsampled disp_shape = self.level_shapes[level, self.dims.displayed] scale = np.ones(self.ndim) for d in self.dims.displayed: scale[d] = self.level_downsamples[self.data_level][d] self._scale = scale self.events.scale() if np.any(disp_shape > self._max_tile_shape): for d in self.dims.displayed: indices[d] = slice( self._top_left[d], self._top_left[d] + self._max_tile_shape, 1, ) self.translate = self._top_left * self.scale else: self.translate = [0] * self.ndim image = np.asarray(self.data[level][tuple(indices)]).transpose(order) if self.multichannel and image.dtype.kind == "f": self._data_view = np.clip(image, 0, 1) else: self._data_view = image self._update_thumbnail() self._update_coordinates() self.events.set_data()
def _set_view_slice(self): """Set the view given the indices to slice with.""" nd = self.dims.not_displayed if self.multichannel: # if multichannel need to keep the final axis fixed during the # transpose. The index of the final axis depends on how many # axes are displayed. order = self.dims.displayed_order + (self.dims.ndisplay,) else: order = self.dims.displayed_order # Slice thumbnail indices = np.array(self.dims.indices) downsampled = indices[nd] / self.level_downsamples[-1, nd] downsampled = np.round(downsampled.astype(float)).astype(int) downsampled = np.clip(downsampled, 0, self.level_shapes[-1, nd] - 1) indices[nd] = downsampled self._data_thumbnail = np.asarray(self.data[-1][tuple(indices)]).transpose(order) # Slice currently viewed level indices = np.array(self.dims.indices) level = self.data_level downsampled = indices[nd] / self.level_downsamples[level, nd] downsampled = np.round(downsampled.astype(float)).astype(int) downsampled = np.clip(downsampled, 0, self.level_shapes[level, nd] - 1) indices[nd] = downsampled disp_shape = self.level_shapes[level, self.dims.displayed] scale = np.ones(self.ndim) for d in self.dims.displayed: scale[d] = self.level_downsamples[self.data_level][d] self._scale = scale self.events.scale() if np.any(disp_shape > self._max_tile_shape): for d in self.dims.displayed: indices[d] = slice( self._top_left[d], self._top_left[d] + self._max_tile_shape, 1, ) self.translate = self._top_left * self.scale else: self.translate = [0] * self.ndim self._data_view = np.asarray(self.data[level][tuple(indices)]).transpose(order) self._update_thumbnail() self._update_coordinates() self.events.set_data()
https://github.com/napari/napari/issues/523
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-42-5ae500208e78> in <module> ----> 1 napari.view(array) /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/view_function.py in view(title, metadata, multichannel, contrast_limits, *images, **named_images) 51 metadata=metadata, 52 multichannel=multichannel, ---> 53 contrast_limits=contrast_limits, 54 ) 55 for name, image in named_images.items(): /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/components/viewer_model.py in add_image(self, data, multichannel, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 411 opacity=opacity, 412 blending=blending, --> 413 visible=visible, 414 ) 415 self.add_layer(layer) /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/image/image.py in __init__(self, data, multichannel, colormap, contrast_limits, interpolation, rendering, name, metadata, scale, translate, opacity, blending, visible) 174 175 # Trigger generation of view slice and thumbnail --> 176 self._update_dims() 177 178 @property /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/base/base.py in _update_dims(self) 313 self.dims.set_range(i, r) 314 --> 315 self._set_view_slice() 316 self._update_coordinates() 317 /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/image/image.py in _set_view_slice(self) 333 334 self._data_thumbnail = self._data_view --> 335 self._update_thumbnail() 336 self._update_coordinates() 337 self.events.set_data() /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/image/image.py in _update_thumbnail(self) 392 colormapped = colormapped.reshape(downsampled.shape + (4,)) 393 colormapped[..., 3] *= self.opacity --> 394 self.thumbnail = colormapped 395 396 def get_value(self): /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/napari/layers/base/base.py in thumbnail(self, thumbnail) 353 with warnings.catch_warnings(): 354 warnings.simplefilter("ignore") --> 355 thumbnail = img_as_ubyte(thumbnail) 356 self._thumbnail = thumbnail 357 self.events.thumbnail() /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/skimage/util/dtype.py in img_as_ubyte(image, force_copy) 484 485 """ --> 486 return convert(image, np.uint8, force_copy) 487 488 /Applications/anaconda3/envs/chloe/lib/python3.7/site-packages/skimage/util/dtype.py in convert(image, dtype, force_copy, uniform) 253 254 if np.min(image) < -1.0 or np.max(image) > 1.0: --> 255 raise ValueError("Images of type float must be between -1 and 1.") 256 # floating point -> integer 257 prec_loss() ValueError: Images of type float must be between -1 and 1.
ValueError
def _on_data_change(self): data = self.layer._data_view dtype = np.dtype(data.dtype) if dtype not in texture_dtypes: try: dtype = dict(i=np.int16, f=np.float32)[dtype.kind] except KeyError: # not an int or float raise TypeError( f"type {dtype} not allowed for texture; must be one of {set(texture_dtypes)}" ) data = data.astype(dtype) if self.layer.dims.ndisplay == 3: self.node.set_data(data, clim=self.layer.contrast_limits) else: self.node._need_colortransform_update = True self.node.set_data(data) self.node.update()
def _on_data_change(self): if self.layer.dims.ndisplay == 3: self.node.set_data( self.layer._data_view, contrast_limits=self.layer.contrast_limits, ) else: self.node._need_colortransform_update = True self.node.set_data(self.layer._data_view) self.node.update()
https://github.com/napari/napari/issues/447
WARNING: Traceback (most recent call last): File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 76, in <module> demo(astronaut()) File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 31, in demo rescale_intensity(noisy, in_range='image', out_range=(0, 1)), name='noisy' File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/contextlib.py", line 119, in __exit__ next(self.gen) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/napari/_qt/event_loop.py", line 31, in gui_qt app.exec_() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 217, in on_draw self._draw_scene() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 266, in _draw_scene self.draw_visual(self.scene) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 304, in draw_visual node.draw() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/visuals.py", line 99, in draw self._visual_superclass.draw(self) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 787, in _parse ob.set_data(*args) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 1537, in set_data raise ValueError("Type %r not allowed for texture" % data.dtype) ValueError: Type dtype('int64') not allowed for texture ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> for DrawEvent WARNING: Error drawing visual <Image at 0x133fde5f8> ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> repeat 2
ValueError
def _on_contrast_limits_change(self): if self.layer.dims.ndisplay == 3: self._on_data_change() else: self.node.clim = self.layer.contrast_limits
def _on_contrast_limits_change(self): if self.layer.dims.ndisplay == 3: self.node.set_data( self.layer._data_view, contrast_limits=self.layer.contrast_limits, ) else: self.node.clim = self.layer.contrast_limits
https://github.com/napari/napari/issues/447
WARNING: Traceback (most recent call last): File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 76, in <module> demo(astronaut()) File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 31, in demo rescale_intensity(noisy, in_range='image', out_range=(0, 1)), name='noisy' File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/contextlib.py", line 119, in __exit__ next(self.gen) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/napari/_qt/event_loop.py", line 31, in gui_qt app.exec_() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 217, in on_draw self._draw_scene() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 266, in _draw_scene self.draw_visual(self.scene) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 304, in draw_visual node.draw() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/visuals.py", line 99, in draw self._visual_superclass.draw(self) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 787, in _parse ob.set_data(*args) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 1537, in set_data raise ValueError("Type %r not allowed for texture" % data.dtype) ValueError: Type dtype('int64') not allowed for texture ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> for DrawEvent WARNING: Error drawing visual <Image at 0x133fde5f8> ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> repeat 2
ValueError
def _on_data_change(self): data = self.layer._data_view dtype = np.dtype(data.dtype) if dtype not in texture_dtypes: try: dtype = dict(i=np.int16, f=np.float64)[dtype.kind] except KeyError: # not an int or float raise TypeError( f"type {dtype} not allowed for texture; must be one of {set(texture_dtypes)}" ) data = data.astype(dtype) self.node._need_colortransform_update = True self.node.set_data(data) self.node.update()
def _on_data_change(self): self.node._need_colortransform_update = True self.node.set_data(self.layer._data_view) self.node.update()
https://github.com/napari/napari/issues/447
WARNING: Traceback (most recent call last): File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 76, in <module> demo(astronaut()) File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 31, in demo rescale_intensity(noisy, in_range='image', out_range=(0, 1)), name='noisy' File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/contextlib.py", line 119, in __exit__ next(self.gen) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/napari/_qt/event_loop.py", line 31, in gui_qt app.exec_() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 217, in on_draw self._draw_scene() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 266, in _draw_scene self.draw_visual(self.scene) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 304, in draw_visual node.draw() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/visuals.py", line 99, in draw self._visual_superclass.draw(self) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 787, in _parse ob.set_data(*args) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 1537, in set_data raise ValueError("Type %r not allowed for texture" % data.dtype) ValueError: Type dtype('int64') not allowed for texture ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> for DrawEvent WARNING: Error drawing visual <Image at 0x133fde5f8> ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> repeat 2
ValueError
def _update_thumbnail(self): """Update thumbnail with current image data and colormap.""" if self.dims.ndisplay == 3: image = np.max(self._data_thumbnail, axis=0) else: image = self._data_thumbnail # float16 not supported by ndi.zoom dtype = np.dtype(image.dtype) if dtype in [np.dtype(np.float16)]: image = image.astype(np.float32) zoom_factor = np.divide(self._thumbnail_shape[:2], image.shape[:2]).min() if self.multichannel: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom( image, (zoom_factor, zoom_factor, 1), prefilter=False, order=0, ) if image.shape[2] == 4: # image is RGBA colormapped = np.copy(downsampled) colormapped[..., 3] = downsampled[..., 3] * self.opacity if downsampled.dtype == np.uint8: colormapped = colormapped.astype(np.uint8) else: # image is RGB if downsampled.dtype == np.uint8: alpha = np.full( downsampled.shape[:2] + (1,), int(255 * self.opacity), dtype=np.uint8, ) else: alpha = np.full(downsampled.shape[:2] + (1,), self.opacity) colormapped = np.concatenate([downsampled, alpha], axis=2) else: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom(image, zoom_factor, prefilter=False, order=0) low, high = self.contrast_limits downsampled = np.clip(downsampled, low, high) color_range = high - low if color_range != 0: downsampled = (downsampled - low) / color_range colormapped = self.colormap[1].map(downsampled) colormapped = colormapped.reshape(downsampled.shape + (4,)) colormapped[..., 3] *= self.opacity self.thumbnail = colormapped
def _update_thumbnail(self): """Update thumbnail with current image data and colormap.""" if self.dims.ndisplay == 3: image = np.max(self._data_thumbnail, axis=0) else: image = self._data_thumbnail zoom_factor = np.divide(self._thumbnail_shape[:2], image.shape[:2]).min() if self.multichannel: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom( image, (zoom_factor, zoom_factor, 1), prefilter=False, order=0, ) if image.shape[2] == 4: # image is RGBA colormapped = np.copy(downsampled) colormapped[..., 3] = downsampled[..., 3] * self.opacity if downsampled.dtype == np.uint8: colormapped = colormapped.astype(np.uint8) else: # image is RGB if downsampled.dtype == np.uint8: alpha = np.full( downsampled.shape[:2] + (1,), int(255 * self.opacity), dtype=np.uint8, ) else: alpha = np.full(downsampled.shape[:2] + (1,), self.opacity) colormapped = np.concatenate([downsampled, alpha], axis=2) else: # warning filter can be removed with scipy 1.4 with warnings.catch_warnings(): warnings.simplefilter("ignore") downsampled = ndi.zoom(image, zoom_factor, prefilter=False, order=0) low, high = self.contrast_limits downsampled = np.clip(downsampled, low, high) color_range = high - low if color_range != 0: downsampled = (downsampled - low) / color_range colormapped = self.colormap[1].map(downsampled) colormapped = colormapped.reshape(downsampled.shape + (4,)) colormapped[..., 3] *= self.opacity self.thumbnail = colormapped
https://github.com/napari/napari/issues/447
WARNING: Traceback (most recent call last): File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 76, in <module> demo(astronaut()) File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 31, in demo rescale_intensity(noisy, in_range='image', out_range=(0, 1)), name='noisy' File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/contextlib.py", line 119, in __exit__ next(self.gen) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/napari/_qt/event_loop.py", line 31, in gui_qt app.exec_() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 217, in on_draw self._draw_scene() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 266, in _draw_scene self.draw_visual(self.scene) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 304, in draw_visual node.draw() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/visuals.py", line 99, in draw self._visual_superclass.draw(self) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 787, in _parse ob.set_data(*args) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 1537, in set_data raise ValueError("Type %r not allowed for texture" % data.dtype) ValueError: Type dtype('int64') not allowed for texture ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> for DrawEvent WARNING: Error drawing visual <Image at 0x133fde5f8> ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> repeat 2
ValueError
def view( *images, title="napari", metadata=None, multichannel=None, contrast_limits=None, **named_images, ): """View one or more input images. Parameters ---------- *images : ndarray Arrays to render as image layers. title : string, optional The title of the viewer window. meta : dictionary, optional A dictionary of metadata attributes. If multiple images are provided, the metadata applies to all of them. multichannel : bool, optional Whether to consider the last dimension of the image(s) as channels rather than spatial attributes. If not provided, napari will attempt to make an educated guess. If provided, and multiple images are given, the same value applies to all images. contrast_limits : list (2,) Color limits to be used for determining the colormap bounds for luminance images. If not passed is calculated as the min and max of the image. Passing a value prevents this calculation which can be useful when working with very large datasets that are dynamically loaded. If provided, and multiple images are given, the same value applies to all images. **named_images : dict of str -> ndarray, optional Arrays to render as image layers, keyed by layer name. Returns ------- viewer : napari.Viewer A Viewer widget displaying the images. Notes ----- This convenience function is used to view one or few images with identical parameters (colormap etc). To customize each image layer, either use the :class:`napari.Viewer` class (preferred), or update the layers directly on the returned :class:`napari.Viewer` object. """ viewer = Viewer(title=title) for image in images: viewer.add_image( image, metadata=metadata, multichannel=multichannel, contrast_limits=contrast_limits, ) for name, image in named_images.items(): viewer.add_image( image, metadata=metadata, multichannel=multichannel, contrast_limits=contrast_limits, name=name, ) return viewer
def view( *images, title="napari", metadata=None, multichannel=None, contrast_limits_range=None, **named_images, ): """View one or more input images. Parameters ---------- *images : ndarray Arrays to render as image layers. title : string, optional The title of the viewer window. meta : dictionary, optional A dictionary of metadata attributes. If multiple images are provided, the metadata applies to all of them. multichannel : bool, optional Whether to consider the last dimension of the image(s) as channels rather than spatial attributes. If not provided, napari will attempt to make an educated guess. If provided, and multiple images are given, the same value applies to all images. contrast_limits_range : list | array | None Length two list or array with the default color limit range for the image. If not passed will be calculated as the min and max of the image. Passing a value prevents this calculation which can be useful when working with very large datasets that are dynamically loaded. If provided, and multiple images are given, the same value applies to all images. **named_images : dict of str -> ndarray, optional Arrays to render as image layers, keyed by layer name. Returns ------- viewer : napari.Viewer A Viewer widget displaying the images. Notes ----- This convenience function is used to view one or few images with identical parameters (colormap etc). To customize each image layer, either use the :class:`napari.Viewer` class (preferred), or update the layers directly on the returned :class:`napari.Viewer` object. """ viewer = Viewer(title=title) for image in images: viewer.add_image( image, metadata=metadata, multichannel=multichannel, contrast_limits_range=contrast_limits_range, ) for name, image in named_images.items(): viewer.add_image( image, metadata=metadata, multichannel=multichannel, contrast_limits_range=contrast_limits_range, name=name, ) return viewer
https://github.com/napari/napari/issues/447
WARNING: Traceback (most recent call last): File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 76, in <module> demo(astronaut()) File "/Users/royer/workspace/python/pitl/pitl/it/demo/demo_it_n2s_gbm_2D_rgb.py", line 31, in demo rescale_intensity(noisy, in_range='image', out_range=(0, 1)), name='noisy' File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/contextlib.py", line 119, in __exit__ next(self.gen) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/napari/_qt/event_loop.py", line 31, in gui_qt app.exec_() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 217, in on_draw self._draw_scene() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 266, in _draw_scene self.draw_visual(self.scene) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/canvas.py", line 304, in draw_visual node.draw() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/scene/visuals.py", line 99, in draw self._visual_superclass.draw(self) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 787, in _parse ob.set_data(*args) File "/Users/royer/anaconda3/envs/pitl/lib/python3.7/site-packages/vispy/gloo/glir.py", line 1537, in set_data raise ValueError("Type %r not allowed for texture" % data.dtype) ValueError: Type dtype('int64') not allowed for texture ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> for DrawEvent WARNING: Error drawing visual <Image at 0x133fde5f8> ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PySide2) at 0x128724438>> repeat 2
ValueError
def on_key_press(self, event): """Called whenever key pressed in canvas.""" if event.native.isAutoRepeat(): return else: if event.key == " ": if self._mode != Mode.PAN_ZOOM: self._mode_history = self.mode self._selected_data_history = copy(self.selected_data) self.mode = Mode.PAN_ZOOM else: self._mode_history = Mode.PAN_ZOOM elif event.key == "Shift": if self._mode == Mode.ADD: self.cursor = "forbidden" elif event.key == "p": self.mode = Mode.ADD elif event.key == "s": self.mode = Mode.SELECT elif event.key == "z": self.mode = Mode.PAN_ZOOM elif event.key == "c" and "Control" in event.modifiers: if self._mode == Mode.SELECT: self._copy_data() elif event.key == "v" and "Control" in event.modifiers: if self._mode == Mode.SELECT: self._paste_data() elif event.key == "a": if self._mode == Mode.SELECT: self.selected_data = self._indices_view[: len(self._data_view)] self._set_highlight() elif event.key == "Backspace": if self._mode == Mode.SELECT: self.remove_selected()
def on_key_press(self, event): """Called whenever key pressed in canvas.""" if event.native.isAutoRepeat(): return else: if event.key == " ": if self._mode != Mode.PAN_ZOOM: self._mode_history = self.mode self._selected_data_history = copy(self.selected_data) self.mode = Mode.PAN_ZOOM else: self._mode_history = Mode.PAN_ZOOM elif event.key == "Shift": if self._mode == Mode.ADD: self.cursor = "forbidden" elif event.key == "p": self.mode = Mode.ADD elif event.key == "s": self.mode = Mode.SELECT elif event.key == "z": self.mode = Mode.PAN_ZOOM elif event.key == "c" and "Control" in event.modifiers: if self._mode == Mode.SELECT: self._copy_data() elif event.key == "v" and "Control" in event.modifiers: if self._mode == Mode.SELECT: self._paste_data() elif event.key == "a": if self._mode == Mode.SELECT: self.selected_data = self._indices_view[ list(range(len(self._data_view))) ] self._set_highlight() elif event.key == "Backspace": if self._mode == Mode.SELECT: self.remove_selected()
https://github.com/napari/napari/issues/417
$ python examples/add_image.py /home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/visuals/markers.py:564: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. ('a_edgewidth', np.float32, 1)]) /home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/visuals/markers.py:564: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. ('a_edgewidth', np.float32, 1)]) WARNING: Traceback (most recent call last): File "examples/add_image.py", line 44, in <module> layer.interpolation = 'nearest' File "/home/jni/miniconda3/envs/cf/lib/python3.6/contextlib.py", line 88, in __exit__ next(self.gen) File "/home/jni/projects/napari/napari/_qt/event_loop.py", line 31, in gui_qt app.exec_() File "/home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/app/backends/_qt.py", line 495, in keyPressEvent self._keyEvent(self._vispy_canvas.events.key_press, ev) File "/home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/app/backends/_qt.py", line 544, in _keyEvent func(native=ev, key=key, text=text_type(ev.text()), modifiers=mod) File "/home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/home/jni/miniconda3/envs/cf/lib/python3.6/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/home/jni/projects/napari/napari/_qt/qt_viewer.py", line 236, in on_key_press layer.on_key_press(event) File "/home/jni/projects/napari/napari/layers/points/points.py", line 968, in on_key_press list(range(len(self._data_view))) TypeError: list indices must be integers or slices, not list ERROR: Invoking <bound method QtViewer.on_key_press of <napari._qt.qt_viewer.QtViewer object at 0x7fc1c12c1798>> for KeyEvent
TypeError
def _remove(event): """When a layer is removed, remove its viewer.""" layers = event.source layer = event.item layer._order = 0 layer._node.transforms = ChainTransform() layer._node.parent = None
def _remove(event): """When a layer is removed, remove its viewer.""" layers = event.source layer = event.item layer._order = 0 layer._node.parent = None
https://github.com/napari/napari/issues/170
In [15]: WARNING: Traceback (most recent call last): File "/Users/jni/conda/envs/36/bin/ipython", line 11, in <module> sys.exit(start_ipython()) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/__init__.py", line 125, in start_ipython return launch_new_instance(argv=argv, **kwargs) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance app.start() File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/terminal/ipapp.py", line 356, in start self.shell.mainloop() File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", line 480, in mainloop self.interact() File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", line 463, in interact code = self.prompt_for_code() File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", line 376, in prompt_for_code pre_run=self.pre_prompt, reset_current_buffer=True) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/prompt_toolkit/interface.py", line 415, in run self.eventloop.run(self.input, self.create_eventloop_callbacks()) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/prompt_toolkit/eventloop/posix.py", line 102, in run self._inputhook_context.call_inputhook(ready) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/prompt_toolkit/eventloop/inputhook.py", line 74, in call_inputhook self.inputhook(self) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py", line 495, in inputhook self._inputhook(context) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/IPython/terminal/pt_inputhooks/qt.py", line 35, in inputhook event_loop.exec_() File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/components/_layers_list/model.py", line 182, in remove_selected self.pop(i) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/util/list/_model.py", line 55, in pop self.changed.removed(item=obj) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/util/event.py", line 489, in __call__ self._invoke_callback(cb, event) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/util/event.py", line 504, in _invoke_callback cb(event) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/components/_layers_list/model.py", line 29, in _remove layer.viewer = None File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/layers/_base_layer/model.py", line 162, in viewer self._parent = parent File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/layers/_base_layer/_visual_wrapper.py", line 82, in _parent self._node.parent = parent File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/util/frozen.py", line 17, in __setattr__ object.__setattr__(self, key, value) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/scene/node.py", line 209, in parent self._update_trsys(None) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/napari/_vispy/scene/visuals.py", line 82, in _update_trsys self.transforms.scene_transform = scene.node_transform(doc) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/visuals/transforms/transform_system.py", line 276, in scene_transform self._scene_transform.transforms = tr File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/visuals/transforms/chain.py", line 96, in transforms self.update() File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/visuals/transforms/base_transform.py", line 153, in update self.changed(*args) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/visuals/transforms/chain.py", line 212, in _subtr_changed self.update(ev) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/visuals/transforms/base_transform.py", line 153, in update self.changed(*args) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/Users/jni/conda/envs/36/lib/python3.6/site-packages/vispy/visuals/transforms/chain.py", line 281, in source_changed new_tr = [tr[0]] IndexError: list index out of range ERROR: Invoking <bound method SimplifiedChainTransform.source_changed of <ChainTransform [<STTransform scale=[1. 1. 1. 1.] translate=[0. 0. 0. 0.] at 0x5071730616>, <STTransform scale=[2.6181054e+00 2.6181054e+00 1.0000000e-06 1.0000000e+00] translate=[-558.83954 -403.84387 0. 0. ] at 0x5319047544>] at 0x12e27aba8>> for Event
IndexError
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
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
https://github.com/napari/napari/issues/304
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'
TypeError
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
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
https://github.com/napari/napari/issues/304
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'
TypeError
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_()
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_()
https://github.com/napari/napari/issues/304
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'
TypeError
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()
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()
https://github.com/napari/napari/issues/304
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'
TypeError
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()
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()
https://github.com/napari/napari/issues/154
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
ValueError
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)
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)
https://github.com/napari/napari/issues/159
--------------------------------------------------------------------------- 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'
TypeError
def use_info_auxv(): lines = pwndbg.info.auxv().splitlines() if not lines: return None auxv = AUXV() for line in lines: match = re.match("([0-9]+) .*? (0x[0-9a-f]+|[0-9]+)", line) if not match: print("Warning: Skipping auxv entry '{}'".format(line)) continue const, value = int(match.group(1)), int(match.group(2), 0) auxv.set(const, value) return auxv
def use_info_auxv(): lines = pwndbg.info.auxv().splitlines() if not lines: return None auxv = AUXV() for line in lines: match = re.match("([0-9]+) .* (0x[0-9a-f]+|[0-9]+)", line) if not match: print("Warning: Skipping auxv entry '{}'".format(line)) continue const, value = int(match.group(1)), int(match.group(2), 0) auxv.set(const, value) return auxv
https://github.com/pwndbg/pwndbg/issues/858
$ pwd /home/user/test/x 01 $ cat test.c #include <stdio.h> #include <stdlib.h> void main() { printf("Hello world\n"); getchar(); } $ gcc -o test test.c $ gdb test GNU gdb (Ubuntu 9.2-0ubuntu1~20.04) 9.2 Copyright (C) 2020 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... pwndbg: loaded 191 commands. Type pwndbg [filter] for a list. pwndbg: created $rebase, $ida gdb functions (can be used with print/break) Reading symbols from test... (No debugging symbols found in test) pwndbg> r Starting program: /home/user/test/x 01/test Hello world ^C Program received signal SIGINT, Interrupt. 0x00007ffff7ebe142 in __GI___libc_read (fd=0, buf=0x5555555596b0, nbytes=1024) at ../sysdeps/unix/sysv/linux/read.c:26 26 ../sysdeps/unix/sysv/linux/read.c: No such file or directory. Exception occurred: Error: invalid literal for int() with base 0: '01' (<class 'ValueError'>) For more info invoke `set exception-verbose on` and rerun the command or debug it by yourself with `set exception-debugger on` Python Exception <class 'ValueError'> invalid literal for int() with base 0: '01': Exception occurred: Error: invalid literal for int() with base 0: '01' (<class 'ValueError'>) For more info invoke `set exception-verbose on` and rerun the command or debug it by yourself with `set exception-debugger on` Python Exception <class 'ValueError'> invalid literal for int() with base 0: '01': Exception occurred: Error: invalid literal for int() with base 0: '01' (<class 'ValueError'>) For more info invoke `set exception-verbose on` and rerun the command or debug it by yourself with `set exception-debugger on` Python Exception <class 'ValueError'> invalid literal for int() with base 0: '01': pwndbg> set exception-debugger on Set whether to debug exceptions raised in Pwndbg commands to True Traceback (most recent call last): File "/home/user/pwndbg/pwndbg/pwndbg/events.py", line 165, in caller func() File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/stack.py", line 79, in update page = pwndbg.memory.Page(start, stop-start, 6 if not is_executable() else 7, 0, '[stack]') File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/stack.py", line 127, in is_executable ehdr = pwndbg.elf.exe() File "/home/user/pwndbg/pwndbg/pwndbg/proc.py", line 71, in wrapper return func(*a, **kw) File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/elf.py", line 180, in exe e = entry() File "/home/user/pwndbg/pwndbg/pwndbg/proc.py", line 71, in wrapper return func(*a, **kw) File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/elf.py", line 191, in entry entry = pwndbg.auxv.get().AT_ENTRY File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/auxv.py", line 106, in get return use_info_auxv() or walk_stack() or AUXV() File "/home/user/pwndbg/pwndbg/pwndbg/auxv.py", line 121, in use_info_auxv const, value = int(match.group(1)), int(match.group(2), 0) ValueError: invalid literal for int() with base 0: '01' 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) To generate the report and open a browser, you may run `bugreport --run-browser` PS: Pull requests are welcome /home/user/pwndbg/pwndbg/pwndbg/auxv.py(121)use_info_auxv() -> const, value = int(match.group(1)), int(match.group(2), 0) (Pdb) q Traceback (most recent call last): File "/home/user/pwndbg/pwndbg/pwndbg/prompt.py", line 33, in prompt_hook pwndbg.events.after_reload(start=False) File "/home/user/pwndbg/pwndbg/pwndbg/events.py", line 216, in after_reload f() File "/home/user/pwndbg/pwndbg/pwndbg/events.py", line 169, in caller raise e File "/home/user/pwndbg/pwndbg/pwndbg/events.py", line 165, in caller func() File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/stack.py", line 79, in update page = pwndbg.memory.Page(start, stop-start, 6 if not is_executable() else 7, 0, '[stack]') File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/stack.py", line 127, in is_executable ehdr = pwndbg.elf.exe() File "/home/user/pwndbg/pwndbg/pwndbg/proc.py", line 71, in wrapper return func(*a, **kw) File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/elf.py", line 180, in exe e = entry() File "/home/user/pwndbg/pwndbg/pwndbg/proc.py", line 71, in wrapper return func(*a, **kw) File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/elf.py", line 191, in entry entry = pwndbg.auxv.get().AT_ENTRY File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/auxv.py", line 106, in get return use_info_auxv() or walk_stack() or AUXV() File "/home/user/pwndbg/pwndbg/pwndbg/auxv.py", line 121, in use_info_auxv const, value = int(match.group(1)), int(match.group(2), 0) ValueError: invalid literal for int() with base 0: '01' pwndbg> info auxv 33 AT_SYSINFO_EHDR System-supplied DSO's ELF header 0x7ffff7fce000 16 AT_HWCAP Machine-dependent CPU capability hints 0xbfebfbff 6 AT_PAGESZ System page size 4096 17 AT_CLKTCK Frequency of times() 100 3 AT_PHDR Program headers for program 0x555555554040 4 AT_PHENT Size of program header entry 56 5 AT_PHNUM Number of program headers 13 7 AT_BASE Base address of interpreter 0x7ffff7fcf000 8 AT_FLAGS Flags 0x0 9 AT_ENTRY Entry point of program 0x555555555080 11 AT_UID Real user ID 1000 12 AT_EUID Effective user ID 1000 13 AT_GID Real group ID 1001 14 AT_EGID Effective group ID 1001 23 AT_SECURE Boolean, was exec setuid-like? 0 25 AT_RANDOM Address of 16 random bytes 0x7fffffffdff9 26 AT_HWCAP2 Extension of AT_HWCAP 0x0 31 AT_EXECFN File name of executable 0x7fffffffefde "/home/user/test/x 01/test" 15 AT_PLATFORM String identifying platform 0x7fffffffe009 "x86_64" 0 AT_NULL End of vector 0x0 Traceback (most recent call last): File "/home/user/pwndbg/pwndbg/pwndbg/events.py", line 165, in caller func() File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/stack.py", line 79, in update page = pwndbg.memory.Page(start, stop-start, 6 if not is_executable() else 7, 0, '[stack]') File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/stack.py", line 127, in is_executable ehdr = pwndbg.elf.exe() File "/home/user/pwndbg/pwndbg/pwndbg/proc.py", line 71, in wrapper return func(*a, **kw) File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/elf.py", line 180, in exe e = entry() File "/home/user/pwndbg/pwndbg/pwndbg/proc.py", line 71, in wrapper return func(*a, **kw) File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/elf.py", line 191, in entry entry = pwndbg.auxv.get().AT_ENTRY File "/home/user/pwndbg/pwndbg/pwndbg/memoize.py", line 44, in __call__ value = self.func(*args, **kwargs) File "/home/user/pwndbg/pwndbg/pwndbg/auxv.py", line 106, in get return use_info_auxv() or walk_stack() or AUXV() File "/home/user/pwndbg/pwndbg/pwndbg/auxv.py", line 121, in use_info_auxv const, value = int(match.group(1)), int(match.group(2), 0) ValueError: invalid literal for int() with base 0: '01' /home/user/pwndbg/pwndbg/pwndbg/auxv.py(121)use_info_auxv() -> const, value = int(match.group(1)), int(match.group(2), 0) (Pdb)
ValueError
def malloc_chunk(addr, fake=False, verbose=False, simple=False): """Print a malloc_chunk struct's contents.""" # points to the real start of the chunk cursor = int(addr) allocator = pwndbg.heap.current ptr_size = allocator.size_sz size_field = pwndbg.memory.u(cursor + allocator.chunk_key_offset("size")) real_size = size_field & ~allocator.malloc_align_mask headers_to_print = [] # both state (free/allocated) and flags fields_to_print = set() # in addition to addr and size out_fields = "Addr: {}\n".format(M.get(cursor)) if fake: headers_to_print.append(message.on("Fake chunk")) verbose = True # print all fields for fake chunks if simple: chunk = read_chunk(cursor) if not headers_to_print: headers_to_print.append(message.hint(M.get(cursor))) prev_inuse, is_mmapped, non_main_arena = allocator.chunk_flags( int(chunk["size"]) ) if prev_inuse: headers_to_print.append(message.hint("PREV_INUSE")) if is_mmapped: headers_to_print.append(message.hint("IS_MMAPED")) if non_main_arena: headers_to_print.append(message.hint("NON_MAIN_ARENA")) print(" | ".join(headers_to_print)) for key, val in chunk.items(): print(message.system(key) + ": 0x{:02x}".format(int(val))) print("") return arena = allocator.get_arena_for_chunk(cursor) arena_address = None is_top = False if not fake and arena: arena_address = arena.address top_chunk = arena["top"] if cursor == top_chunk: headers_to_print.append(message.off("Top chunk")) is_top = True if not is_top: fastbins = allocator.fastbins(arena_address) or {} smallbins = allocator.smallbins(arena_address) or {} largebins = allocator.largebins(arena_address) or {} unsortedbin = allocator.unsortedbin(arena_address) or {} if allocator.has_tcache(): tcachebins = allocator.tcachebins(None) if real_size in fastbins.keys() and cursor in fastbins[real_size]: headers_to_print.append(message.on("Free chunk (fastbins)")) if not verbose: fields_to_print.add("fd") elif real_size in smallbins.keys() and cursor in bin_addrs( smallbins[real_size], "smallbins" ): headers_to_print.append(message.on("Free chunk (smallbins)")) if not verbose: fields_to_print.update(["fd", "bk"]) elif real_size >= list(largebins.items())[0][0] and cursor in bin_addrs( largebins[ (list(largebins.items())[allocator.largebin_index(real_size) - 64][0]) ], "largebins", ): headers_to_print.append(message.on("Free chunk (largebins)")) if not verbose: fields_to_print.update(["fd", "bk", "fd_nextsize", "bk_nextsize"]) elif cursor in bin_addrs(unsortedbin["all"], "unsortedbin"): headers_to_print.append(message.on("Free chunk (unsortedbin)")) if not verbose: fields_to_print.update(["fd", "bk"]) elif ( allocator.has_tcache() and real_size in tcachebins.keys() and cursor + ptr_size * 2 in bin_addrs(tcachebins[real_size], "tcachebins") ): headers_to_print.append(message.on("Free chunk (tcache)")) if not verbose: fields_to_print.add("fd") else: headers_to_print.append(message.hint("Allocated chunk")) if verbose: fields_to_print.update( ["prev_size", "size", "fd", "bk", "fd_nextsize", "bk_nextsize"] ) else: out_fields += "Size: 0x{:02x}\n".format(size_field) prev_inuse, is_mmapped, non_main_arena = allocator.chunk_flags(size_field) if prev_inuse: headers_to_print.append(message.hint("PREV_INUSE")) if is_mmapped: headers_to_print.append(message.hint("IS_MMAPED")) if non_main_arena: headers_to_print.append(message.hint("NON_MAIN_ARENA")) fields_ordered = ["prev_size", "size", "fd", "bk", "fd_nextsize", "bk_nextsize"] for field_to_print in fields_ordered: if field_to_print in fields_to_print: out_fields += message.system(field_to_print) + ": 0x{:02x}\n".format( pwndbg.memory.u(cursor + allocator.chunk_key_offset(field_to_print)) ) print(" | ".join(headers_to_print) + "\n" + out_fields)
def malloc_chunk(addr, fake=False, verbose=False, simple=False): """Print a malloc_chunk struct's contents.""" # points to the real start of the chunk cursor = int(addr) allocator = pwndbg.heap.current ptr_size = allocator.size_sz size_field = pwndbg.memory.u(cursor + allocator.chunk_key_offset("size")) real_size = size_field & ~allocator.malloc_align_mask headers_to_print = [] # both state (free/allocated) and flags fields_to_print = set() # in addition to addr and size out_fields = "Addr: {}\n".format(M.get(cursor)) arena = allocator.get_arena_for_chunk(cursor) arena_address = None if fake: headers_to_print.append(message.on("Fake chunk")) verbose = True # print all fields for fake chunks if simple: chunk = read_chunk(cursor) if not headers_to_print: headers_to_print.append(message.hint(M.get(cursor))) prev_inuse, is_mmapped, non_main_arena = allocator.chunk_flags( int(chunk["size"]) ) if prev_inuse: headers_to_print.append(message.hint("PREV_INUSE")) if is_mmapped: headers_to_print.append(message.hint("IS_MMAPED")) if non_main_arena: headers_to_print.append(message.hint("NON_MAIN_ARENA")) print(" | ".join(headers_to_print)) for key, val in chunk.items(): print(message.system(key) + ": 0x{:02x}".format(int(val))) print("") return is_top = False if arena: arena_address = arena.address top_chunk = arena["top"] if cursor == top_chunk: headers_to_print.append(message.off("Top chunk")) is_top = True if not is_top: fastbins = allocator.fastbins(arena_address) or {} smallbins = allocator.smallbins(arena_address) or {} largebins = allocator.largebins(arena_address) or {} unsortedbin = allocator.unsortedbin(arena_address) or {} if allocator.has_tcache(): tcachebins = allocator.tcachebins(None) if real_size in fastbins.keys() and cursor in fastbins[real_size]: headers_to_print.append(message.on("Free chunk (fastbins)")) if not verbose: fields_to_print.add("fd") elif real_size in smallbins.keys() and cursor in bin_addrs( smallbins[real_size], "smallbins" ): headers_to_print.append(message.on("Free chunk (smallbins)")) if not verbose: fields_to_print.update(["fd", "bk"]) elif real_size >= list(largebins.items())[0][0] and cursor in bin_addrs( largebins[ (list(largebins.items())[allocator.largebin_index(real_size) - 64][0]) ], "largebins", ): headers_to_print.append(message.on("Free chunk (largebins)")) if not verbose: fields_to_print.update(["fd", "bk", "fd_nextsize", "bk_nextsize"]) elif cursor in bin_addrs(unsortedbin["all"], "unsortedbin"): headers_to_print.append(message.on("Free chunk (unsortedbin)")) if not verbose: fields_to_print.update(["fd", "bk"]) elif ( allocator.has_tcache() and real_size in tcachebins.keys() and cursor + ptr_size * 2 in bin_addrs(tcachebins[real_size], "tcachebins") ): headers_to_print.append(message.on("Free chunk (tcache)")) if not verbose: fields_to_print.add("fd") else: headers_to_print.append(message.hint("Allocated chunk")) if verbose: fields_to_print.update( ["prev_size", "size", "fd", "bk", "fd_nextsize", "bk_nextsize"] ) else: out_fields += "Size: 0x{:02x}\n".format(size_field) prev_inuse, is_mmapped, non_main_arena = allocator.chunk_flags(size_field) if prev_inuse: headers_to_print.append(message.hint("PREV_INUSE")) if is_mmapped: headers_to_print.append(message.hint("IS_MMAPED")) if non_main_arena: headers_to_print.append(message.hint("NON_MAIN_ARENA")) fields_ordered = ["prev_size", "size", "fd", "bk", "fd_nextsize", "bk_nextsize"] for field_to_print in fields_ordered: if field_to_print in fields_to_print: out_fields += message.system(field_to_print) + ": 0x{:02x}\n".format( pwndbg.memory.u(cursor + allocator.chunk_key_offset(field_to_print)) ) print(" | ".join(headers_to_print) + "\n" + out_fields)
https://github.com/pwndbg/pwndbg/issues/781
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
gdb.MemoryError
def find_fake_fast(addr, size=None): """Find candidate fake fast chunks overlapping the specified address.""" psize = pwndbg.arch.ptrsize allocator = pwndbg.heap.current align = allocator.malloc_alignment min_fast = allocator.min_chunk_size max_fast = allocator.global_max_fast max_fastbin = allocator.fastbin_index(max_fast) start = int(addr) - max_fast + psize if start < 0: print( message.warn( "addr - global_max_fast is negative, if the max_fast is not corrupted, you gave wrong address" ) ) start = 0 # TODO, maybe some better way to handle case when global_max_fast is overwritten with something large mem = pwndbg.memory.read(start, max_fast - psize, partial=True) fmt = {"little": "<", "big": ">"}[pwndbg.arch.endian] + {4: "I", 8: "Q"}[psize] if size is None: sizes = range(min_fast, max_fast + 1, align) else: sizes = [int(size)] print(C.banner("FAKE CHUNKS")) for size in sizes: fastbin = allocator.fastbin_index(size) for offset in range((max_fastbin - fastbin) * align, max_fast - align + 1): candidate = mem[offset : offset + psize] if len(candidate) == psize: value = struct.unpack(fmt, candidate)[0] if allocator.fastbin_index(value) == fastbin: malloc_chunk(start + offset - psize, fake=True)
def find_fake_fast(addr, size=None): """Find candidate fake fast chunks overlapping the specified address.""" psize = pwndbg.arch.ptrsize allocator = pwndbg.heap.current align = allocator.malloc_alignment min_fast = allocator.min_chunk_size max_fast = allocator.global_max_fast max_fastbin = allocator.fastbin_index(max_fast) start = int(addr) - max_fast + psize mem = pwndbg.memory.read(start, max_fast - psize, partial=True) fmt = {"little": "<", "big": ">"}[pwndbg.arch.endian] + {4: "I", 8: "Q"}[psize] if size is None: sizes = range(min_fast, max_fast + 1, align) else: sizes = [int(size)] print(C.banner("FAKE CHUNKS")) for size in sizes: fastbin = allocator.fastbin_index(size) for offset in range((max_fastbin - fastbin) * align, max_fast - align + 1): candidate = mem[offset : offset + psize] if len(candidate) == psize: value = struct.unpack(fmt, candidate)[0] if allocator.fastbin_index(value) == fastbin: malloc_chunk(start + offset - psize, fake=True)
https://github.com/pwndbg/pwndbg/issues/781
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
gdb.MemoryError
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
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
https://github.com/pwndbg/pwndbg/issues/781
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
gdb.MemoryError
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
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
https://github.com/pwndbg/pwndbg/issues/777
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
TypeError
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
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
https://github.com/pwndbg/pwndbg/issues/660
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'
TypeError
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])
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)
https://github.com/pwndbg/pwndbg/issues/662
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.
subprocess.CalledProcessError
def exe(self): return gdb.current_progspace().filename
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"]
https://github.com/pwndbg/pwndbg/issues/623
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
OSError
def iter_phdrs(ehdr): if not ehdr: return phnum, phentsize, phdr = get_phdrs(ehdr.address) if not phdr: return first_phdr = phdr.address PhdrType = phdr.type for i in range(0, phnum): p_phdr = int(first_phdr + (i * phentsize)) p_phdr = read(PhdrType, p_phdr) yield p_phdr
def iter_phdrs(ehdr): if not ehdr: raise StopIteration phnum, phentsize, phdr = get_phdrs(ehdr.address) if not phdr: raise StopIteration first_phdr = phdr.address PhdrType = phdr.type for i in range(0, phnum): p_phdr = int(first_phdr + (i * phentsize)) p_phdr = read(PhdrType, p_phdr) yield p_phdr
https://github.com/pwndbg/pwndbg/issues/570
pwndbg> target remote localhost:1234 Remote debugging using localhost:1234 warning: No executable has been specified and target does not support determining executable automatically. Try using the "file" command. 0x0000000000000000 in ?? () Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/elf.py", line 318, in iter_phdrs raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/events.py", line 169, in caller func() File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/stack.py", line 81, in update page = pwndbg.memory.Page(start, stop-start, 6 if not is_executable() else 7, 0, '[stack]') File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/stack.py", line 131, in is_executable for phdr in pwndbg.elf.iter_phdrs(ehdr): RuntimeError: generator raised StopIteration 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) To generate the report and open a browser, you may run `bugreport --run-browser` PS: Pull requests are welcome /usr/share/pwndbg/pwndbg/stack.py(131)is_executable() -> for phdr in pwndbg.elf.iter_phdrs(ehdr): (Pdb) (Pdb) c Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/elf.py", line 318, in iter_phdrs raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/events.py", line 173, in caller raise e File "/usr/share/pwndbg/pwndbg/events.py", line 169, in caller func() File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/stack.py", line 81, in update page = pwndbg.memory.Page(start, stop-start, 6 if not is_executable() else 7, 0, '[stack]') File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/stack.py", line 131, in is_executable for phdr in pwndbg.elf.iter_phdrs(ehdr): RuntimeError: generator raised StopIteration Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/elf.py", line 318, in iter_phdrs raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/events.py", line 169, in caller func() File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/stack.py", line 131, in is_executable for phdr in pwndbg.elf.iter_phdrs(ehdr): RuntimeError: generator raised StopIteration 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) To generate the report and open a browser, you may run `bugreport --run-browser` PS: Pull requests are welcome /usr/share/pwndbg/pwndbg/stack.py(131)is_executable() -> for phdr in pwndbg.elf.iter_phdrs(ehdr): (Pdb) c Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/elf.py", line 318, in iter_phdrs raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/events.py", line 173, in caller raise e File "/usr/share/pwndbg/pwndbg/events.py", line 169, in caller func() File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/stack.py", line 131, in is_executable for phdr in pwndbg.elf.iter_phdrs(ehdr): RuntimeError: generator raised StopIteration Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/events.py", line 169, in caller func() File "/usr/share/pwndbg/pwndbg/vmmap.py", line 116, in explore_registers find(pwndbg.regs[regname]) File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/vmmap.py", line 75, in find return explore(address) File "/usr/share/pwndbg/pwndbg/abi.py", line 165, in caller return func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/vmmap.py", line 105, in explore page = find_boundaries(address_maybe) File "/usr/share/pwndbg/pwndbg/vmmap.py", line 366, in find_boundaries start = pwndbg.memory.find_lower_boundary(addr) File "/usr/share/pwndbg/pwndbg/memory.py", line 357, in find_lower_boundary pwndbg.memory.read(addr, 1) File "/usr/share/pwndbg/pwndbg/memory.py", line 44, in read result = gdb.selected_inferior().read_memory(addr, count) gdb.error: Remote connection closed 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) To generate the report and open a browser, you may run `bugreport --run-browser` PS: Pull requests are welcome /usr/share/pwndbg/pwndbg/memory.py(44)read() -> result = gdb.selected_inferior().read_memory(addr, count) (Pdb) c Traceback (most recent call last): File "/usr/share/pwndbg/pwndbg/events.py", line 173, in caller raise e File "/usr/share/pwndbg/pwndbg/events.py", line 169, in caller func() File "/usr/share/pwndbg/pwndbg/vmmap.py", line 116, in explore_registers find(pwndbg.regs[regname]) File "/usr/share/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/vmmap.py", line 75, in find return explore(address) File "/usr/share/pwndbg/pwndbg/abi.py", line 165, in caller return func(*args, **kwargs) File "/usr/share/pwndbg/pwndbg/vmmap.py", line 105, in explore page = find_boundaries(address_maybe) File "/usr/share/pwndbg/pwndbg/vmmap.py", line 366, in find_boundaries start = pwndbg.memory.find_lower_boundary(addr) File "/usr/share/pwndbg/pwndbg/memory.py", line 357, in find_lower_boundary pwndbg.memory.read(addr, 1) File "/usr/share/pwndbg/pwndbg/memory.py", line 44, in read result = gdb.selected_inferior().read_memory(addr, count) gdb.error: Remote connection closed [1] 7286 segmentation fault (core dumped) aarch64-linux-gnu-gdb
RuntimeError
def next(self, instruction, call=False): """ Architecture-specific hook point for enhance_next. """ if CS_GRP_CALL in instruction.groups: if not call: return None elif CS_GRP_JUMP not in instruction.groups: return None # At this point, all operands have been resolved. # Assume only single-operand jumps. if len(instruction.operands) != 1: return None # Memory operands must be dereferenced op = instruction.operands[0] addr = op.int if addr: addr &= pwndbg.arch.ptrmask if op.type == CS_OP_MEM: if addr is None: addr = self.memory(instruction, op) # self.memory may return none, so we need to check it here again if addr is not None: try: # fails with gdb.MemoryError if the dereferenced address # doesn't belong to any of process memory maps addr = int(pwndbg.memory.poi(pwndbg.typeinfo.ppvoid, addr)) except gdb.MemoryError: return None if op.type == CS_OP_REG: addr = self.register(instruction, op) # Evidently this can happen? if addr is None: return None return int(addr)
def next(self, instruction, call=False): """ Architecture-specific hook point for enhance_next. """ if CS_GRP_CALL in instruction.groups: if not call: return None elif CS_GRP_JUMP not in instruction.groups: return None # At this point, all operands have been resolved. # Assume only single-operand jumps. if len(instruction.operands) != 1: return None # Memory operands must be dereferenced op = instruction.operands[0] addr = op.int if addr: addr &= pwndbg.arch.ptrmask if op.type == CS_OP_MEM: if addr is None: addr = self.memory(instruction, op) # self.memory may return none, so we need to check it here again if addr is not None: addr = int(pwndbg.memory.poi(pwndbg.typeinfo.ppvoid, addr)) if op.type == CS_OP_REG: addr = self.register(instruction, op) # Evidently this can happen? if addr is None: return None return int(addr)
https://github.com/pwndbg/pwndbg/issues/587
Traceback (most recent call last): File "/home/dc/pwndbg/pwndbg/commands/__init__.py", line 135, in __call__ return self.function(*args, **kwargs) File "/home/dc/pwndbg/pwndbg/commands/__init__.py", line 226, in _OnlyWhenRunning return function(*a, **kw) File "/home/dc/pwndbg/pwndbg/commands/context.py", line 88, in context result.extend(func()) File "/home/dc/pwndbg/pwndbg/commands/context.py", line 100, in context_regs return [pwndbg.ui.banner("registers")] + get_regs() File "/home/dc/pwndbg/pwndbg/commands/context.py", line 144, in get_regs desc = pwndbg.chain.format(value) File "/home/dc/pwndbg/pwndbg/chain.py", line 122, in format enhanced = pwndbg.enhance.enhance(chain[-2] + offset, code=code) File "/home/dc/pwndbg/pwndbg/enhance.py", line 102, in enhance instr = pwndbg.disasm.one(value) File "/home/dc/pwndbg/pwndbg/disasm/__init__.py", line 115, in one for insn in get(address, 1): File "/home/dc/pwndbg/pwndbg/disasm/__init__.py", line 135, in get i = get_one_instruction(address) File "/home/dc/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/home/dc/pwndbg/pwndbg/disasm/__init__.py", line 107, in get_one_instruction pwndbg.disasm.arch.DisassemblyAssistant.enhance(ins) File "/home/dc/pwndbg/pwndbg/disasm/arch.py", line 55, in enhance enhancer.enhance_next(instruction) File "/home/dc/pwndbg/pwndbg/disasm/arch.py", line 111, in enhance_next instruction.target = self.next(instruction, call=True) File "/home/dc/pwndbg/pwndbg/disasm/x86.py", line 112, in next return super(DisassemblyAssistant, self).next(instruction, call) File "/home/dc/pwndbg/pwndbg/disasm/arch.py", line 150, in next addr = int(pwndbg.memory.poi(pwndbg.typeinfo.ppvoid, addr)) File "/home/dc/pwndbg/pwndbg/inthook.py", line 40, in __new__ value = value.cast(pwndbg.typeinfo.ulong) gdb.MemoryError: Cannot access memory at address 0x30
gdb.MemoryError
def dump(self, instruction): """ Debug-only method. """ ins = instruction rv = [] rv.append("%s %s" % (ins.mnemonic, ins.op_str)) for i, group in enumerate(ins.groups): rv.append(" groups[%i] = %s" % (i, groups.get(group, group))) rv.append(" next = %#x" % (ins.next)) rv.append(" condition = %r" % (ins.condition)) for i, op in enumerate(ins.operands): rv.append(" operands[%i] = %s" % (i, ops.get(op.type, op.type))) rv.append(" access = %s" % (access.get(op.access, op.access))) if op.int is not None: rv.append(" int = %#x" % (op.int)) if op.symbol is not None: rv.append(" sym = %s" % (op.symbol)) if op.str is not None: rv.append(" str = %s" % (op.str)) return "\n".join(rv)
def dump(self, instruction): ins = instruction rv = [] rv.append("%s %s" % (ins.mnemonic, ins.op_str)) for i, group in enumerate(ins.groups): rv.append(" groups[%i] = %s" % (i, groups.get(group, group))) rv.append(" next = %#x" % (ins.next)) rv.append(" condition = %r" % (ins.condition)) for i, op in enumerate(ins.operands): rv.append(" operands[%i] = %s" % (i, ops.get(op.type, op.type))) rv.append(" access = %s" % (access.get(op.access, op.access))) if op.int is not None: rv.append(" int = %#x" % (op.int)) if op.symbol is not None: rv.append(" sym = %s" % (op.symbol)) if op.str is not None: rv.append(" str = %s" % (op.str)) return "\n".join(rv)
https://github.com/pwndbg/pwndbg/issues/587
Traceback (most recent call last): File "/home/dc/pwndbg/pwndbg/commands/__init__.py", line 135, in __call__ return self.function(*args, **kwargs) File "/home/dc/pwndbg/pwndbg/commands/__init__.py", line 226, in _OnlyWhenRunning return function(*a, **kw) File "/home/dc/pwndbg/pwndbg/commands/context.py", line 88, in context result.extend(func()) File "/home/dc/pwndbg/pwndbg/commands/context.py", line 100, in context_regs return [pwndbg.ui.banner("registers")] + get_regs() File "/home/dc/pwndbg/pwndbg/commands/context.py", line 144, in get_regs desc = pwndbg.chain.format(value) File "/home/dc/pwndbg/pwndbg/chain.py", line 122, in format enhanced = pwndbg.enhance.enhance(chain[-2] + offset, code=code) File "/home/dc/pwndbg/pwndbg/enhance.py", line 102, in enhance instr = pwndbg.disasm.one(value) File "/home/dc/pwndbg/pwndbg/disasm/__init__.py", line 115, in one for insn in get(address, 1): File "/home/dc/pwndbg/pwndbg/disasm/__init__.py", line 135, in get i = get_one_instruction(address) File "/home/dc/pwndbg/pwndbg/memoize.py", line 48, in __call__ value = self.func(*args, **kwargs) File "/home/dc/pwndbg/pwndbg/disasm/__init__.py", line 107, in get_one_instruction pwndbg.disasm.arch.DisassemblyAssistant.enhance(ins) File "/home/dc/pwndbg/pwndbg/disasm/arch.py", line 55, in enhance enhancer.enhance_next(instruction) File "/home/dc/pwndbg/pwndbg/disasm/arch.py", line 111, in enhance_next instruction.target = self.next(instruction, call=True) File "/home/dc/pwndbg/pwndbg/disasm/x86.py", line 112, in next return super(DisassemblyAssistant, self).next(instruction, call) File "/home/dc/pwndbg/pwndbg/disasm/arch.py", line 150, in next addr = int(pwndbg.memory.poi(pwndbg.typeinfo.ppvoid, addr)) File "/home/dc/pwndbg/pwndbg/inthook.py", line 40, in __new__ value = value.cast(pwndbg.typeinfo.ulong) gdb.MemoryError: Cannot access memory at address 0x30
gdb.MemoryError
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)
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)
https://github.com/pwndbg/pwndbg/issues/440
[!] 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
InterruptedError
def init_ida_rpc_client(): global _ida, _ida_last_exception, _ida_last_connection_check if not ida_enabled: return now = time.time() if _ida is None and (now - _ida_last_connection_check) < int(ida_timeout) + 5: return addr = "http://{host}:{port}".format(host=ida_rpc_host, port=ida_rpc_port) _ida = xmlrpclib.ServerProxy(addr) socket.setdefaulttimeout(int(ida_timeout)) exception = None # (type, value, traceback) try: _ida.here() print( message.success( "Pwndbg successfully connected to Ida Pro xmlrpc: %s" % addr ) ) except socket.error as e: if e.errno != errno.ECONNREFUSED: exception = sys.exc_info() _ida = None except socket.timeout: exception = sys.exc_info() _ida = None except xmlrpclib.ProtocolError: exception = sys.exc_info() _ida = None if exception: if ( not isinstance(_ida_last_exception, exception[0]) or _ida_last_exception.args != exception[1].args ): if ( hasattr(pwndbg.config, "exception_verbose") and pwndbg.config.exception_verbose ): print(message.error("[!] Ida Pro xmlrpc error")) traceback.print_exception(*exception) else: exc_type, exc_value, _ = exception print( message.error( "Failed to connect to IDA Pro ({}: {})".format( exc_type.__qualname__, exc_value ) ) ) if exc_type is socket.timeout: print( message.notice("To increase the time to wait for IDA Pro use `") + message.hint("set ida-timeout <new-timeout-in-seconds>") + message.notice("`") ) else: print( message.notice("For more info invoke `") + message.hint("set exception-verbose on") + message.notice("`") ) print( message.notice("To disable IDA Pro integration invoke `") + message.hint("set ida-enabled off") + message.notice("`") ) _ida_last_exception = exception and exception[1] _ida_last_connection_check = now
def init_ida_rpc_client(): global _ida, _ida_last_exception addr = "http://{host}:{port}".format(host=ida_rpc_host, port=ida_rpc_port) _ida = xmlrpclib.ServerProxy(addr) socket.setdefaulttimeout(3) exception = None # (type, value, traceback) try: _ida.here() print( message.success( "Pwndbg successfully connected to Ida Pro xmlrpc: %s" % addr ) ) except socket.error as e: if e.errno != errno.ECONNREFUSED: exception = sys.exc_info() _ida = None except socket.timeout: exception = sys.exc_info() _ida = None except xmlrpclib.ProtocolError: exception = sys.exc_info() _ida = None if exception: if ( not isinstance(_ida_last_exception, exception[0]) or _ida_last_exception.args != exception[1].args ): print(message.error("[!] Ida Pro xmlrpc error")) traceback.print_exception(*exception) _ida_last_exception = exception and exception[1]
https://github.com/pwndbg/pwndbg/issues/440
[!] 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
InterruptedError
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
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
https://github.com/pwndbg/pwndbg/issues/440
[!] 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
InterruptedError
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)
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)
https://github.com/pwndbg/pwndbg/issues/440
[!] 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
InterruptedError
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)
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)
https://github.com/pwndbg/pwndbg/issues/362
[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
gdb.error
def dt(name="", addr=None, obj=None): """ Dump out a structure type Windbg style. """ # Return value is a list of strings.of # We concatenate at the end. rv = [] if obj and not name: t = obj.type while t.code == (gdb.TYPE_CODE_PTR): t = t.target() obj = obj.dereference() name = str(t) # Lookup the type name specified by the user else: t = pwndbg.typeinfo.load(name) # If it's not a struct (e.g. int or char*), bail if t.code not in (gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_TYPEDEF, gdb.TYPE_CODE_UNION): raise Exception("Not a structure: %s" % t) # If an address was specified, create a Value of the # specified type at that address. if addr is not None: obj = pwndbg.memory.poi(t, addr) # Header, optionally include the name header = name if obj: header = "%s @ %s" % (header, hex(int(obj.address))) rv.append(header) if t.strip_typedefs().code == gdb.TYPE_CODE_ARRAY: return "Arrays not supported yet" if t.strip_typedefs().code not in (gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION): t = {name: obj or gdb.Value(0).cast(t)} for name, field in t.items(): # Offset into the parent structure o = getattr(field, "bitpos", 0) // 8 b = getattr(field, "bitpos", 0) % 8 extra = str(field.type) ftype = field.type.strip_typedefs() if obj and obj.type.strip_typedefs().code in ( gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, ): v = obj[name] if ftype.code == gdb.TYPE_CODE_INT: v = hex(int(v)) if ( ftype.code in (gdb.TYPE_CODE_PTR, gdb.TYPE_CODE_ARRAY) and ftype.target() == pwndbg.typeinfo.uchar ): data = pwndbg.memory.read(v.address, ftype.sizeof) v = " ".join("%02x" % b for b in data) extra = v # Adjust trailing lines in 'extra' to line up # This is necessary when there are nested structures. # Ideally we'd expand recursively if the type is complex. extra_lines = [] for i, line in enumerate(str(extra).splitlines()): if i == 0: extra_lines.append(line) else: extra_lines.append(35 * " " + line) extra = "\n".join(extra_lines) bitpos = "" if not b else (".%i" % b) line = " +0x%04x%s %-20s : %s" % (o, bitpos, name, extra) rv.append(line) return "\n".join(rv)
def dt(name="", addr=None, obj=None): """ Dump out a structure type Windbg style. """ # Return value is a list of strings.of # We concatenate at the end. rv = [] if obj and not name: t = obj.type while t.code == (gdb.TYPE_CODE_PTR): t = t.target() obj = obj.dereference() name = str(t) # Lookup the type name specified by the user else: t = pwndbg.typeinfo.load(name) # If it's not a struct (e.g. int or char*), bail if t.code not in (gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_TYPEDEF, gdb.TYPE_CODE_UNION): raise Exception("Not a structure: %s" % t) # If an address was specified, create a Value of the # specified type at that address. if addr is not None: obj = pwndbg.memory.poi(t, addr) # Header, optionally include the name header = name if obj: header = "%s @ %s" % (header, hex(int(obj.address))) rv.append(header) if t.strip_typedefs().code == gdb.TYPE_CODE_ARRAY: return "Arrays not supported yet" if t.strip_typedefs().code not in (gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION): t = {name: obj or gdb.Value(0).cast(t)} for name, field in t.items(): # Offset into the parent structure o = getattr(field, "bitpos", 0) / 8 extra = str(field.type) ftype = field.type.strip_typedefs() if obj and obj.type.strip_typedefs().code in ( gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, ): v = obj[name] if ftype.code == gdb.TYPE_CODE_INT: v = hex(int(v)) if ( ftype.code in (gdb.TYPE_CODE_PTR, gdb.TYPE_CODE_ARRAY) and ftype.target() == pwndbg.typeinfo.uchar ): data = pwndbg.memory.read(v.address, ftype.sizeof) v = " ".join("%02x" % b for b in data) extra = v # Adjust trailing lines in 'extra' to line up # This is necessary when there are nested structures. # Ideally we'd expand recursively if the type is complex. extra_lines = [] for i, line in enumerate(str(extra).splitlines()): if i == 0: extra_lines.append(line) else: extra_lines.append(35 * " " + line) extra = "\n".join(extra_lines) line = " +0x%04x %-20s : %s" % (o, name, extra) rv.append(line) return "\n".join(rv)
https://github.com/pwndbg/pwndbg/issues/362
[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
gdb.error
def search(type, hex, string, executable, writable, value, mapping, save, next): # Adjust pointer sizes to the local architecture if type == "pointer": type = {4: "dword", 8: "qword"}[pwndbg.arch.ptrsize] if save is None: save = bool(pwndbg.config.auto_save_search) if hex: value = codecs.decode(value, "hex") # Convert to an integer if needed, and pack to bytes if type not in ("string", "bytes"): value = pwndbg.commands.fix_int(value) value &= pwndbg.arch.ptrmask fmt = {"little": "<", "big": ">"}[pwndbg.arch.endian] + { "byte": "B", "short": "H", "dword": "L", "qword": "Q", }[type] value = struct.pack(fmt, value) # Null-terminate strings elif type == "string": value += b"\x00" # Prep the saved set if necessary global saved if save: saved = set() # Perform the search for address in pwndbg.search.search( value, mapping=mapping, executable=executable, writable=writable ): if next and address not in saved: continue if save: saved.add(address) print_search_hit(address)
def search(type, hex, string, executable, writable, value, mapping, save, next): # Adjust pointer sizes to the local architecture if type == "pointer": type = {4: "dword", 8: "qword"}[pwndbg.arch.ptrsize] if save is None: save = bool(pwndbg.config.auto_save_search) if hex: value = codecs.decode(value, "hex") # Convert to an integer if needed, and pack to bytes if type not in ("string", "bytes"): value = pwndbg.commands.fix_int(value) fmt = {"little": "<", "big": ">"}[pwndbg.arch.endian] + { "byte": "B", "short": "H", "dword": "L", "qword": "Q", }[type] value = struct.pack(fmt, value) # Null-terminate strings elif type == "string": value += b"\x00" # Prep the saved set if necessary global saved if save: saved = set() # Perform the search for address in pwndbg.search.search( value, mapping=mapping, executable=executable, writable=writable ): if next and address not in saved: continue if save: saved.add(address) print_search_hit(address)
https://github.com/pwndbg/pwndbg/issues/123
pwndbg> search -4 0xf7eebf83 Traceback (most recent call last): File "/home/bruce30262/pwndbg/pwndbg/commands/__init__.py", line 57, in __call__ return self.function(*args, **kwargs) File "/home/bruce30262/pwndbg/pwndbg/commands/__init__.py", line 162, in _ArgparsedCommand return function(**vars(args)) File "/home/bruce30262/pwndbg/pwndbg/commands/__init__.py", line 115, in _OnlyWhenRunning return function(*a, **kw) File "/home/bruce30262/pwndbg/pwndbg/commands/search.py", line 112, in search value = struct.pack(fmt, value) struct.error: argument out of range
struct.error
def _same_modules(source_module, target_module): """Compare the filenames associated with the given modules names. This tries to not actually load the modules. """ if not (source_module or target_module): return False if target_module == source_module: return True def _get_filename(module): filename = None try: if not inspect.ismodule(module): loader = pkgutil.get_loader(module) if isinstance(loader, importlib.machinery.SourceFileLoader): filename = loader.get_filename() else: filename = inspect.getfile(module) except (TypeError, ImportError): pass return filename source_filename = _get_filename(source_module) target_filename = _get_filename(target_module) return source_filename and target_filename and source_filename == target_filename
def _same_modules(source_module, target_module): """Compare the filenames associated with the given modules names. This tries to not actually load the modules. """ if not (source_module or target_module): return False if target_module == source_module: return True def _get_filename(module): filename = None try: if not inspect.ismodule(module): loader = pkgutil.get_loader(module) if loader: filename = loader.get_filename() else: filename = inspect.getfile(module) except (TypeError, ImportError): pass return filename source_filename = _get_filename(source_module) target_filename = _get_filename(target_module) return source_filename and target_filename and source_filename == target_filename
https://github.com/hylang/hy/issues/1911
$ python Python 3.7.5 (default, Jun 8 2020, 17:36:22) [Clang 11.0.3 (clang-1103.0.32.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. import hy hy.eval(hy.read_str("(require [hy.contrib.walk [let]])")) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/compiler.py", line 2099, in hy_eval module.__dict__, locals) File "<string>", line 1, in <module> File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 170, in require if _same_modules(source_module, target_module): File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 118, in _same_modules target_filename = _get_filename(target_module) File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 109, in _get_filename filename = loader.get_filename() AttributeError: type object 'BuiltinImporter' has no attribute 'get_filename'
AttributeError
def _get_filename(module): filename = None try: if not inspect.ismodule(module): loader = pkgutil.get_loader(module) if isinstance(loader, importlib.machinery.SourceFileLoader): filename = loader.get_filename() else: filename = inspect.getfile(module) except (TypeError, ImportError): pass return filename
def _get_filename(module): filename = None try: if not inspect.ismodule(module): loader = pkgutil.get_loader(module) if loader: filename = loader.get_filename() else: filename = inspect.getfile(module) except (TypeError, ImportError): pass return filename
https://github.com/hylang/hy/issues/1911
$ python Python 3.7.5 (default, Jun 8 2020, 17:36:22) [Clang 11.0.3 (clang-1103.0.32.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. import hy hy.eval(hy.read_str("(require [hy.contrib.walk [let]])")) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/compiler.py", line 2099, in hy_eval module.__dict__, locals) File "<string>", line 1, in <module> File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 170, in require if _same_modules(source_module, target_module): File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 118, in _same_modules target_filename = _get_filename(target_module) File "/Users/chris/.pyenv/versions/3.7.5/lib/python3.7/site-packages/hy/macros.py", line 109, in _get_filename filename = loader.get_filename() AttributeError: type object 'BuiltinImporter' has no attribute 'get_filename'
AttributeError
def run_command(source, filename=None): __main__ = importlib.import_module("__main__") require("hy.cmdline", __main__, assignments="ALL") try: tree = hy_parse(source, filename=filename) except HyLanguageError: hy_exc_handler(*sys.exc_info()) return 1 with filtered_hy_exceptions(): hy_eval(tree, __main__.__dict__, __main__, filename=filename, source=source) return 0
def run_command(source, filename=None): __main__ = importlib.import_module("__main__") require("hy.cmdline", __main__, assignments="ALL") try: tree = hy_parse(source, filename=filename) except HyLanguageError: hy_exc_handler(*sys.exc_info()) return 1 with filtered_hy_exceptions(): hy_eval(tree, None, __main__, filename=filename, source=source) return 0
https://github.com/hylang/hy/issues/1879
$ CODE='(import math) (print (lfor j [1] (math.sqrt 5)))' $ hy -c "$CODE" Traceback (most recent call last): File "/usr/local/bin/hy", line 8, in <module> sys.exit(hy_main()) File "<string>", line 1, in <module> File "<string>", line 1, in <listcomp> NameError: name 'math' is not defined $ echo "$CODE" | hy hy 0.18.0 using CPython(default) 3.7.5 on Linux => [2.23606797749979] => now exiting HyREPL... $ echo "$CODE" > /tmp/foo.hy &amp;&amp; hy /tmp/foo.hy [2.23606797749979]
NameError
def macroexpand(tree, module, compiler=None, once=False): """Expand the toplevel macros for the given Hy AST tree. Load the macros from the given `module`, then expand the (top-level) macros in `tree` until we no longer can. `HyExpression` resulting from macro expansions are assigned the module in which the macro function is defined (determined using `inspect.getmodule`). If the resulting `HyExpression` is itself macro expanded, then the namespace of the assigned module is checked first for a macro corresponding to the expression's head/car symbol. If the head/car symbol of such a `HyExpression` is not found among the macros of its assigned module's namespace, the outer-most namespace--e.g. the one given by the `module` parameter--is used as a fallback. Parameters ---------- tree: HyObject or list Hy AST tree. module: str or types.ModuleType Module used to determine the local namespace for macros. compiler: HyASTCompiler, optional The compiler object passed to expanded macros. once: boolean, optional Only expand the first macro in `tree`. Returns ------ out: HyObject Returns a mutated tree with macros expanded. """ if not inspect.ismodule(module): module = importlib.import_module(module) assert not compiler or compiler.module == module while isinstance(tree, HyExpression) and tree: fn = tree[0] if fn in ("quote", "quasiquote") or not isinstance(fn, HySymbol): break fn = mangle(fn) expr_modules = ([] if not hasattr(tree, "module") else [tree.module]) + [module] # Choose the first namespace with the macro. m = next( (mod.__macros__[fn] for mod in expr_modules if fn in mod.__macros__), None ) if not m: break opts = {} if m._hy_macro_pass_compiler: if compiler is None: from hy.compiler import HyASTCompiler compiler = HyASTCompiler(module) opts["compiler"] = compiler with macro_exceptions(module, tree, compiler): obj = m(module.__name__, *tree[1:], **opts) if isinstance(obj, HyExpression): obj.module = inspect.getmodule(m) tree = replace_hy_obj(obj, tree) if once: break tree = wrap_value(tree) return tree
def macroexpand(tree, module, compiler=None, once=False): """Expand the toplevel macros for the given Hy AST tree. Load the macros from the given `module`, then expand the (top-level) macros in `tree` until we no longer can. `HyExpression` resulting from macro expansions are assigned the module in which the macro function is defined (determined using `inspect.getmodule`). If the resulting `HyExpression` is itself macro expanded, then the namespace of the assigned module is checked first for a macro corresponding to the expression's head/car symbol. If the head/car symbol of such a `HyExpression` is not found among the macros of its assigned module's namespace, the outer-most namespace--e.g. the one given by the `module` parameter--is used as a fallback. Parameters ---------- tree: HyObject or list Hy AST tree. module: str or types.ModuleType Module used to determine the local namespace for macros. compiler: HyASTCompiler, optional The compiler object passed to expanded macros. once: boolean, optional Only expand the first macro in `tree`. Returns ------ out: HyObject Returns a mutated tree with macros expanded. """ if not inspect.ismodule(module): module = importlib.import_module(module) assert not compiler or compiler.module == module while True: if not isinstance(tree, HyExpression) or tree == []: break fn = tree[0] if fn in ("quote", "quasiquote") or not isinstance(fn, HySymbol): break fn = mangle(fn) expr_modules = ([] if not hasattr(tree, "module") else [tree.module]) + [module] # Choose the first namespace with the macro. m = next( (mod.__macros__[fn] for mod in expr_modules if fn in mod.__macros__), None ) if not m: break opts = {} if m._hy_macro_pass_compiler: if compiler is None: from hy.compiler import HyASTCompiler compiler = HyASTCompiler(module) opts["compiler"] = compiler with macro_exceptions(module, tree, compiler): obj = m(module.__name__, *tree[1:], **opts) if isinstance(obj, HyExpression): obj.module = inspect.getmodule(m) tree = replace_hy_obj(obj, tree) if once: break tree = wrap_value(tree) return tree
https://github.com/hylang/hy/issues/1885
felix@alienware:~$ hy --version hy 0.18.0 felix@alienware:~$ echo "()" > foo.hy &amp;&amp; hy foo.hy Traceback (most recent call last): File "/home/felix/.pyenv/versions/3.8.0/bin/hy", line 8, in <module> sys.exit(hy_main()) File "/home/felix/.pyenv/versions/3.8.0/lib/python3.8/runpy.py", line 261, in run_path code, fname = _get_code_from_file(run_name, path_name) File "<frozen importlib._bootstrap_external>", line 916, in get_code hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ Traceback (most recent call last): File "/home/felix/.pyenv/versions/3.8.0/lib/python3.8/site-packages/hy/compiler.py", line 433, in compile ret = self.compile_atom(tree) File "/home/felix/.pyenv/versions/3.8.0/lib/python3.8/site-packages/hy/compiler.py", line 427, in compile_atom return Result() + _model_compilers[type(atom)](self, atom) File "/home/felix/.pyenv/versions/3.8.0/lib/python3.8/site-packages/hy/compiler.py", line 1730, in compile_expression expr = macroexpand(expr, self.module, self) File "/home/felix/.pyenv/versions/3.8.0/lib/python3.8/site-packages/hy/macros.py", line 316, in macroexpand fn = tree[0] File "/home/felix/.pyenv/versions/3.8.0/lib/python3.8/site-packages/hy/models.py", line 278, in __getitem__ ret = super(HySequence, self).__getitem__(item) IndexError: tuple index out of range
hy.errors.HyCompileError
def _format_string(self, string, rest, allow_recursion=True): values = [] ret = Result() while True: # Look for the next replacement field, and get the # plain text before it. match = re.search(r"\{\{?|\}\}?", rest) if match: literal_chars = rest[: match.start()] if match.group() == "}": raise self._syntax_error(string, "f-string: single '}' is not allowed") if match.group() in ("{{", "}}"): # Doubled braces just add a single brace to the text. literal_chars += match.group()[0] rest = rest[match.end() :] else: literal_chars = rest rest = "" if literal_chars: values.append(asty.Str(string, s=literal_chars)) if not rest: break if match.group() != "{": continue # Look for the end of the replacement field, allowing # one more level of matched braces, but no deeper, and only # if we can recurse. match = re.match( r"(?: \{ [^{}]* \} | [^{}]+ )* \}" if allow_recursion else r"[^{}]* \}", rest, re.VERBOSE, ) if not match: raise self._syntax_error(string, "f-string: mismatched braces") item = rest[: match.end() - 1] rest = rest[match.end() :] # Parse the first form. try: model, item = parse_one_thing(item) except (ValueError, LexException) as e: raise self._syntax_error(string, "f-string: " + str(e)) # Look for a conversion character. item = item.lstrip() conversion = None if item.startswith("!"): conversion = item[1] item = item[2:].lstrip() # Look for a format specifier. format_spec = None if item.startswith(":"): if allow_recursion: ret += self._format_string(string, item[1:], allow_recursion=False) format_spec = ret.force_expr else: format_spec = asty.Str(string, s=item[1:]) if PY36: format_spec = asty.JoinedStr(string, values=[format_spec]) elif item: raise self._syntax_error(string, "f-string: trailing junk in field") # Now, having finished compiling any recursively included # forms, we can compile the first form that we parsed. ret += self.compile(model) if PY36: values.append( asty.FormattedValue( string, conversion=-1 if conversion is None else ord(conversion), format_spec=format_spec, value=ret.force_expr, ) ) else: # Make an expression like: # "{!r:{}}".format(value, format_spec) values.append( asty.Call( string, func=asty.Attribute( string, value=asty.Str( string, s="{" + ("!" + conversion if conversion else "") + ":{}}", ), attr="format", ctx=ast.Load(), ), args=[ret.force_expr, format_spec or asty.Str(string, s="")], keywords=[], starargs=None, kwargs=None, ) ) return ret + ( asty.JoinedStr(string, values=values) if PY36 else reduce( lambda x, y: asty.BinOp(string, left=x, op=ast.Add(), right=y), values ) )
def _format_string(self, string, rest, allow_recursion=True): values = [] ret = Result() while True: # Look for the next replacement field, and get the # plain text before it. match = re.search(r"\{\{?|\}\}?", rest) if match: literal_chars = rest[: match.start()] if match.group() == "}": raise self._syntax_error(string, "f-string: single '}' is not allowed") if match.group() in ("{{", "}}"): # Doubled braces just add a single brace to the text. literal_chars += match.group()[0] rest = rest[match.end() :] else: literal_chars = rest rest = "" if literal_chars: values.append(asty.Str(string, s=literal_chars)) if not rest: break if match.group() != "{": continue # Look for the end of the replacement field, allowing # one more level of matched braces, but no deeper, and only # if we can recurse. match = re.match( r"(?: \{ [^{}]* \} | [^{}]+ )* \}" if allow_recursion else r"[^{}]* \}", rest, re.VERBOSE, ) if not match: raise self._syntax_error(string, "f-string: mismatched braces") item = rest[: match.end() - 1] rest = rest[match.end() :] # Parse the first form. try: model, item = parse_one_thing(item) except (ValueError, LexException) as e: raise self._syntax_error(string, "f-string: " + str(e)) # Look for a conversion character. item = item.lstrip() conversion = None if item.startswith("!"): conversion = item[1] item = item[2:].lstrip() # Look for a format specifier. format_spec = asty.Str(string, s="") if item.startswith(":"): if allow_recursion: ret += self._format_string(string, item[1:], allow_recursion=False) format_spec = ret.force_expr else: format_spec = asty.Str(string, s=item[1:]) elif item: raise self._syntax_error(string, "f-string: trailing junk in field") # Now, having finished compiling any recursively included # forms, we can compile the first form that we parsed. ret += self.compile(model) if PY36: values.append( asty.FormattedValue( string, conversion=-1 if conversion is None else ord(conversion), format_spec=format_spec, value=ret.force_expr, ) ) else: # Make an expression like: # "{!r:{}}".format(value, format_spec) values.append( asty.Call( string, func=asty.Attribute( string, value=asty.Str( string, s="{" + ("!" + conversion if conversion else "") + ":{}}", ), attr="format", ctx=ast.Load(), ), args=[ret.force_expr, format_spec], keywords=[], starargs=None, kwargs=None, ) ) return ret + ( asty.JoinedStr(string, values=values) if PY36 else reduce( lambda x, y: asty.BinOp(string, left=x, op=ast.Add(), right=y), values ) )
https://github.com/hylang/hy/issues/1802
(hylearn) # hy2py minor.hy Traceback (most recent call last): File "/home/diego/hylearn/bin/hy2py", line 12, in <module> sys.exit(hy2py_main()) File "/home/diego/hylearn/lib/python3.7/site-packages/hy/cmdline.py", line 690, in hy2py_main print(astor.code_gen.to_source(_ast)) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 62, in to_source generator.visit(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/node_util.py", line 143, in visit return visitor(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 876, in visit_Module self.write(*node.body) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 177, in write visit(item) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/node_util.py", line 143, in visit return visitor(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 370, in visit_If self.body(node.body) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 225, in body self.write(*statements) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 177, in write visit(item) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/node_util.py", line 143, in visit return visitor(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 334, in visit_FunctionDef self.body(node.body) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 225, in body self.write(*statements) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 177, in write visit(item) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/node_util.py", line 143, in visit return visitor(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 487, in visit_Return self.conditional_write(' ', node.value) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 213, in conditional_write self.write(*stuff) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 177, in write visit(item) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/node_util.py", line 143, in visit return visitor(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 532, in visit_Call write(write_comma, arg) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 177, in write visit(item) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/node_util.py", line 143, in visit return visitor(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 564, in visit_JoinedStr self._handle_string_constant(node, None, is_joined=True) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 620, in _handle_string_constant recurse(node) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 612, in recurse recurse(value.format_spec) File "/home/diego/hylearn/lib/python3.7/site-packages/astor/code_gen.py", line 597, in recurse for value in node.values: AttributeError: 'Str' object has no attribute 'values'
AttributeError
def __init__(self, spy=False, output_fn=None, locals=None, filename="<stdin>"): # Create a proper module for this REPL so that we can obtain it easily # (e.g. using `importlib.import_module`). # We let `InteractiveConsole` initialize `self.locals` when it's # `None`. super(HyREPL, self).__init__(locals=locals, filename=filename) module_name = self.locals.get("__name__", "__console__") # Make sure our newly created module is properly introduced to # `sys.modules`, and consistently use its namespace as `self.locals` # from here on. self.module = sys.modules.setdefault(module_name, types.ModuleType(module_name)) self.module.__dict__.update(self.locals) self.locals = self.module.__dict__ # Load cmdline-specific macros. require("hy.cmdline", self.module, assignments="ALL") self.hy_compiler = HyASTCompiler(self.module) self.compile = HyCommandCompiler(self.module, self.ast_callback, self.hy_compiler) self.spy = spy self.last_value = None if output_fn is None: self.output_fn = repr elif callable(output_fn): self.output_fn = output_fn else: if "." in output_fn: parts = [mangle(x) for x in output_fn.split(".")] module, f = ".".join(parts[:-1]), parts[-1] self.output_fn = getattr(importlib.import_module(module), f) else: self.output_fn = __builtins__[mangle(output_fn)] # Pre-mangle symbols for repl recent results: *1, *2, *3 self._repl_results_symbols = [mangle("*{}".format(i + 1)) for i in range(3)] self.locals.update({sym: None for sym in self._repl_results_symbols})
def __init__(self, spy=False, output_fn=None, locals=None, filename="<input>"): super(HyREPL, self).__init__(locals=locals, filename=filename) # Create a proper module for this REPL so that we can obtain it easily # (e.g. using `importlib.import_module`). # Also, make sure it's properly introduced to `sys.modules` and # consistently use its namespace as `locals` from here on. module_name = self.locals.get("__name__", "__console__") self.module = sys.modules.setdefault(module_name, types.ModuleType(module_name)) self.module.__dict__.update(self.locals) self.locals = self.module.__dict__ # Load cmdline-specific macros. require("hy.cmdline", module_name, assignments="ALL") self.hy_compiler = HyASTCompiler(self.module) self.spy = spy if output_fn is None: self.output_fn = repr elif callable(output_fn): self.output_fn = output_fn else: if "." in output_fn: parts = [mangle(x) for x in output_fn.split(".")] module, f = ".".join(parts[:-1]), parts[-1] self.output_fn = getattr(importlib.import_module(module), f) else: self.output_fn = __builtins__[mangle(output_fn)] # Pre-mangle symbols for repl recent results: *1, *2, *3 self._repl_results_symbols = [mangle("*{}".format(i + 1)) for i in range(3)] self.locals.update({sym: None for sym in self._repl_results_symbols})
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def ast_callback(self, exec_ast, eval_ast): if self.spy: try: # Mush the two AST chunks into a single module for # conversion into Python. new_ast = ast.Module(exec_ast.body + [ast.Expr(eval_ast.body)]) print(astor.to_source(new_ast)) except Exception: msg = "Exception in AST callback:\n{}\n".format(traceback.format_exc()) self.write(msg)
def ast_callback(self, main_ast, expr_ast): if self.spy: # Mush the two AST chunks into a single module for # conversion into Python. new_ast = ast.Module(main_ast.body + [ast.Expr(expr_ast.body)]) print(astor.to_source(new_ast))
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def runsource(self, source, filename="<stdin>", symbol="exec"): try: res = super(HyREPL, self).runsource(source, filename, symbol) except (HyMacroExpansionError, HyRequireError): # We need to handle these exceptions ourselves, because the base # method only handles `OverflowError`, `SyntaxError` and # `ValueError`. self.showsyntaxerror(filename) return False except HyLanguageError: # Our compiler will also raise `TypeError`s self.showtraceback() return False # Shift exisitng REPL results if not res: next_result = self.last_value for sym in self._repl_results_symbols: self.locals[sym], next_result = next_result, self.locals[sym] # Print the value. if self.print_last_value: try: output = self.output_fn(self.last_value) except Exception: self.showtraceback() return False print(output) return res
def runsource(self, source, filename="<input>", symbol="single"): try: do = hy_parse(source, filename=filename) except PrematureEndOfInput: return True except HySyntaxError as e: self.showsyntaxerror(filename=filename) return False try: # Our compiler doesn't correspond to a real, fixed source file, so # we need to [re]set these. self.hy_compiler.filename = filename self.hy_compiler.source = source value = hy_eval( do, self.locals, self.module, self.ast_callback, compiler=self.hy_compiler, filename=filename, source=source, ) except SystemExit: raise except Exception as e: self.showtraceback() return False if value is not None: # Shift exisitng REPL results next_result = value for sym in self._repl_results_symbols: self.locals[sym], next_result = next_result, self.locals[sym] # Print the value. try: output = self.output_fn(value) except Exception: self.showtraceback() return False print(output) return False
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def run_command(source, filename=None): __main__ = importlib.import_module("__main__") require("hy.cmdline", __main__, assignments="ALL") try: tree = hy_parse(source, filename=filename) except HyLanguageError: hy_exc_handler(*sys.exc_info()) return 1 with filtered_hy_exceptions(): hy_eval(tree, None, __main__, filename=filename, source=source) return 0
def run_command(source, filename=None): tree = hy_parse(source, filename=filename) __main__ = importlib.import_module("__main__") require("hy.cmdline", __main__, assignments="ALL") with filtered_hy_exceptions(): hy_eval(tree, None, __main__, filename=filename, source=source) return 0
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def run_icommand(source, **kwargs): if os.path.exists(source): # Emulate Python cmdline behavior by setting `sys.path` relative # to the executed file's location. if sys.path[0] == "": sys.path[0] = os.path.realpath(os.path.split(source)[0]) else: sys.path.insert(0, os.path.split(source)[0]) with io.open(source, "r", encoding="utf-8") as f: source = f.read() filename = source else: filename = "<string>" hr = HyREPL(**kwargs) with filtered_hy_exceptions(): res = hr.runsource(source, filename=filename) # If the command was prematurely ended, show an error (just like Python # does). if res: hy_exc_handler(sys.last_type, sys.last_value, sys.last_traceback) return run_repl(hr)
def run_icommand(source, **kwargs): if os.path.exists(source): # Emulate Python cmdline behavior by setting `sys.path` relative # to the executed file's location. if sys.path[0] == "": sys.path[0] = os.path.realpath(os.path.split(source)[0]) else: sys.path.insert(0, os.path.split(source)[0]) with io.open(source, "r", encoding="utf-8") as f: source = f.read() filename = source else: filename = "<input>" with filtered_hy_exceptions(): hr = HyREPL(**kwargs) hr.runsource(source, filename=filename, symbol="single") return run_repl(hr)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def cmdline_handler(scriptname, argv): parser = argparse.ArgumentParser( prog="hy", usage=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=EPILOG, ) parser.add_argument("-c", dest="command", help="program passed in as a string") parser.add_argument("-m", dest="mod", help="module to run, passed in as a string") parser.add_argument( "-E", action="store_true", help="ignore PYTHON* environment variables" ) parser.add_argument( "-B", action="store_true", help="don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x", ) parser.add_argument( "-i", dest="icommand", help="program passed in as a string, then stay in REPL" ) parser.add_argument( "--spy", action="store_true", help="print equivalent Python code before executing", ) parser.add_argument( "--repl-output-fn", help="function for printing REPL output (e.g., hy.contrib.hy-repr.hy-repr)", ) parser.add_argument("-v", "--version", action="version", version=VERSION) # this will contain the script/program name and any arguments for it. parser.add_argument("args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS) # Get the path of the Hy cmdline executable and swap it with # `sys.executable` (saving the original, just in case). # XXX: The `__main__` module will also have `__file__` set to the # entry-point script. Currently, I don't see an immediate problem, but # that's not how the Python cmdline works. hy.executable = argv[0] hy.sys_executable = sys.executable sys.executable = hy.executable # Need to split the args. If using "-m" all args after the MOD are sent to # the module in sys.argv. module_args = [] if "-m" in argv: mloc = argv.index("-m") if len(argv) > mloc + 2: module_args = argv[mloc + 2 :] argv = argv[: mloc + 2] options = parser.parse_args(argv[1:]) if options.E: # User did "hy -E ..." _remove_python_envs() if options.B: sys.dont_write_bytecode = True if options.command: # User did "hy -c ..." return run_command(options.command, filename="<string>") if options.mod: # User did "hy -m ..." sys.argv = [sys.argv[0]] + options.args + module_args runpy.run_module(options.mod, run_name="__main__", alter_sys=True) return 0 if options.icommand: # User did "hy -i ..." return run_icommand( options.icommand, spy=options.spy, output_fn=options.repl_output_fn ) if options.args: if options.args[0] == "-": # Read the program from stdin return run_command(sys.stdin.read(), filename="<stdin>") else: # User did "hy <filename>" filename = options.args[0] # Emulate Python cmdline behavior by setting `sys.path` relative # to the executed file's location. if sys.path[0] == "": sys.path[0] = os.path.realpath(os.path.split(filename)[0]) else: sys.path.insert(0, os.path.split(filename)[0]) try: sys.argv = options.args with filtered_hy_exceptions(): runhy.run_path(filename, run_name="__main__") return 0 except FileNotFoundError as e: print( "hy: Can't open file '{0}': [Errno {1}] {2}".format( e.filename, e.errno, e.strerror ), file=sys.stderr, ) sys.exit(e.errno) except HyLanguageError: hy_exc_handler(*sys.exc_info()) sys.exit(1) # User did NOTHING! return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
def cmdline_handler(scriptname, argv): parser = argparse.ArgumentParser( prog="hy", usage=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=EPILOG, ) parser.add_argument("-c", dest="command", help="program passed in as a string") parser.add_argument("-m", dest="mod", help="module to run, passed in as a string") parser.add_argument( "-E", action="store_true", help="ignore PYTHON* environment variables" ) parser.add_argument( "-B", action="store_true", help="don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x", ) parser.add_argument( "-i", dest="icommand", help="program passed in as a string, then stay in REPL" ) parser.add_argument( "--spy", action="store_true", help="print equivalent Python code before executing", ) parser.add_argument( "--repl-output-fn", help="function for printing REPL output (e.g., hy.contrib.hy-repr.hy-repr)", ) parser.add_argument("-v", "--version", action="version", version=VERSION) # this will contain the script/program name and any arguments for it. parser.add_argument("args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS) # Get the path of the Hy cmdline executable and swap it with # `sys.executable` (saving the original, just in case). # XXX: The `__main__` module will also have `__file__` set to the # entry-point script. Currently, I don't see an immediate problem, but # that's not how the Python cmdline works. hy.executable = argv[0] hy.sys_executable = sys.executable sys.executable = hy.executable # Need to split the args. If using "-m" all args after the MOD are sent to # the module in sys.argv. module_args = [] if "-m" in argv: mloc = argv.index("-m") if len(argv) > mloc + 2: module_args = argv[mloc + 2 :] argv = argv[: mloc + 2] options = parser.parse_args(argv[1:]) if options.E: # User did "hy -E ..." _remove_python_envs() if options.B: sys.dont_write_bytecode = True if options.command: # User did "hy -c ..." return run_command(options.command, filename="<string>") if options.mod: # User did "hy -m ..." sys.argv = [sys.argv[0]] + options.args + module_args runpy.run_module(options.mod, run_name="__main__", alter_sys=True) return 0 if options.icommand: # User did "hy -i ..." return run_icommand( options.icommand, spy=options.spy, output_fn=options.repl_output_fn ) if options.args: if options.args[0] == "-": # Read the program from stdin return run_command(sys.stdin.read(), filename="<stdin>") else: # User did "hy <filename>" filename = options.args[0] # Emulate Python cmdline behavior by setting `sys.path` relative # to the executed file's location. if sys.path[0] == "": sys.path[0] = os.path.realpath(os.path.split(filename)[0]) else: sys.path.insert(0, os.path.split(filename)[0]) try: sys.argv = options.args with filtered_hy_exceptions(): runhy.run_path(filename, run_name="__main__") return 0 except FileNotFoundError as e: print( "hy: Can't open file '{0}': [Errno {1}] {2}".format( e.filename, e.errno, e.strerror ), file=sys.stderr, ) sys.exit(e.errno) # User did NOTHING! return run_repl(spy=options.spy, output_fn=options.repl_output_fn)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def hy2py_main(): import platform options = dict( prog="hy2py", usage="%(prog)s [options] [FILE]", formatter_class=argparse.RawDescriptionHelpFormatter, ) parser = argparse.ArgumentParser(**options) parser.add_argument( "FILE", type=str, nargs="?", help='Input Hy code (use STDIN if "-" or not provided)', ) parser.add_argument( "--with-source", "-s", action="store_true", help="Show the parsed source structure", ) parser.add_argument( "--with-ast", "-a", action="store_true", help="Show the generated AST" ) parser.add_argument( "--without-python", "-np", action="store_true", help=("Do not show the Python code generated from the AST"), ) options = parser.parse_args(sys.argv[1:]) if options.FILE is None or options.FILE == "-": filename = "<stdin>" source = sys.stdin.read() else: filename = options.FILE with io.open(options.FILE, "r", encoding="utf-8") as source_file: source = source_file.read() with filtered_hy_exceptions(): hst = hy_parse(source, filename=filename) if options.with_source: # need special printing on Windows in case the # codepage doesn't support utf-8 characters if PY3 and platform.system() == "Windows": for h in hst: try: print(h) except: print(str(h).encode("utf-8")) else: print(hst) print() print() with filtered_hy_exceptions(): _ast = hy_compile(hst, "__main__", filename=filename, source=source) if options.with_ast: if PY3 and platform.system() == "Windows": _print_for_windows(astor.dump_tree(_ast)) else: print(astor.dump_tree(_ast)) print() print() if not options.without_python: if PY3 and platform.system() == "Windows": _print_for_windows(astor.code_gen.to_source(_ast)) else: print(astor.code_gen.to_source(_ast)) parser.exit(0)
def hy2py_main(): import platform options = dict( prog="hy2py", usage="%(prog)s [options] [FILE]", formatter_class=argparse.RawDescriptionHelpFormatter, ) parser = argparse.ArgumentParser(**options) parser.add_argument( "FILE", type=str, nargs="?", help='Input Hy code (use STDIN if "-" or not provided)', ) parser.add_argument( "--with-source", "-s", action="store_true", help="Show the parsed source structure", ) parser.add_argument( "--with-ast", "-a", action="store_true", help="Show the generated AST" ) parser.add_argument( "--without-python", "-np", action="store_true", help=("Do not show the Python code generated from the AST"), ) options = parser.parse_args(sys.argv[1:]) if options.FILE is None or options.FILE == "-": source = sys.stdin.read() with filtered_hy_exceptions(): hst = hy_parse(source, filename="<stdin>") else: with ( filtered_hy_exceptions(), io.open(options.FILE, "r", encoding="utf-8") as source_file, ): source = source_file.read() hst = hy_parse(source, filename=options.FILE) if options.with_source: # need special printing on Windows in case the # codepage doesn't support utf-8 characters if PY3 and platform.system() == "Windows": for h in hst: try: print(h) except: print(str(h).encode("utf-8")) else: print(hst) print() print() with filtered_hy_exceptions(): _ast = hy_compile(hst, "__main__") if options.with_ast: if PY3 and platform.system() == "Windows": _print_for_windows(astor.dump_tree(_ast)) else: print(astor.dump_tree(_ast)) print() print() if not options.without_python: if PY3 and platform.system() == "Windows": _print_for_windows(astor.code_gen.to_source(_ast)) else: print(astor.code_gen.to_source(_ast)) parser.exit(0)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def __call__(self, source, filename="<input>", symbol="single"): try: hy_ast = hy_parse(source, filename=filename) root_ast = ast.Interactive if symbol == "single" else ast.Module # Our compiler doesn't correspond to a real, fixed source file, so # we need to [re]set these. self.hy_compiler.filename = filename self.hy_compiler.source = source exec_ast, eval_ast = hy_compile( hy_ast, self.module, root=root_ast, get_expr=True, compiler=self.hy_compiler, filename=filename, source=source, ) if self.ast_callback: self.ast_callback(exec_ast, eval_ast) exec_code = ast_compile(exec_ast, filename, symbol) eval_code = ast_compile(eval_ast, filename, "eval") return exec_code, eval_code except PrematureEndOfInput: # Save these so that we can reraise/display when an incomplete # interactive command is given at the prompt. sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info() return None
def __call__(self, code=None): try: sys.stdin.close() except: pass raise SystemExit(code)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def compile(self, tree): if tree is None: return Result() try: ret = self.compile_atom(tree) self.update_imports(ret) return ret except HyCompileError: # compile calls compile, so we're going to have multiple raise # nested; so let's re-raise this exception, let's not wrap it in # another HyCompileError! raise except HyLanguageError as e: # These are expected errors that should be passed to the user. reraise(type(e), e, sys.exc_info()[2]) except Exception as e: # These are unexpected errors that will--hopefully--never be seen # by the user. f_exc = traceback.format_exc() exc_msg = "Internal Compiler Bug 😱\n⤷ {}".format(f_exc) reraise(HyCompileError, HyCompileError(exc_msg), sys.exc_info()[2])
def compile(self, tree): if tree is None: return Result() try: ret = self.compile_atom(tree) self.update_imports(ret) return ret except HyCompileError: # compile calls compile, so we're going to have multiple raise # nested; so let's re-raise this exception, let's not wrap it in # another HyCompileError! raise except HyTypeError as e: reraise(type(e), e, None) except Exception as e: f_exc = traceback.format_exc() exc_msg = "Internal Compiler Bug 😱\n⤷ {}".format(f_exc) reraise(HyCompileError, HyCompileError(exc_msg), sys.exc_info()[2])
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def _syntax_error(self, expr, message): return HySyntaxError(message, expr, self.filename, self.source)
def _syntax_error(self, expr, message): return HyTypeError(message, self.filename, expr, self.source)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def __init__( self, message, expression=None, filename=None, source=None, lineno=1, colno=1 ): """ Parameters ---------- message: str The message to display for this error. expression: HyObject, optional The Hy expression generating this error. filename: str, optional The filename for the source code generating this error. Expression-provided information will take precedence of this value. source: str, optional The actual source code generating this error. Expression-provided information will take precedence of this value. lineno: int, optional The line number of the error. Expression-provided information will take precedence of this value. colno: int, optional The column number of the error. Expression-provided information will take precedence of this value. """ self.msg = message self.compute_lineinfo(expression, filename, source, lineno, colno) if isinstance(self, SyntaxError): syntax_error_args = (self.filename, self.lineno, self.offset, self.text) super(HyLanguageError, self).__init__(message, syntax_error_args) else: super(HyLanguageError, self).__init__(message)
def __init__(self, message, *args): super(HyLanguageError, self).__init__(message, *args)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def hy_exc_handler(exc_type, exc_value, exc_traceback): """A `sys.excepthook` handler that uses `hy_exc_filter` to remove internal Hy frames from a traceback print-out. """ if os.environ.get("HY_DEBUG", False): return sys.__excepthook__(exc_type, exc_value, exc_traceback) try: output = hy_exc_filter(exc_type, exc_value, exc_traceback) sys.stderr.write(output) sys.stderr.flush() except Exception: sys.__excepthook__(exc_type, exc_value, exc_traceback)
def hy_exc_handler(exc_type, exc_value, exc_traceback): """Produce exceptions print-outs with all frames originating from the modules in `_tb_hidden_modules` filtered out. The frames are actually filtered by each module's filename and only when a subclass of `HyLanguageError` is emitted. This does not remove the frames from the actual tracebacks, so debugging will show everything. """ try: # frame = (filename, line number, function name*, text) new_tb = [ frame for frame in traceback.extract_tb(exc_traceback) if not ( frame[0].replace(".pyc", ".py") in _tb_hidden_modules or os.path.dirname(frame[0]) in _tb_hidden_modules ) ] lines = traceback.format_list(new_tb) if lines: lines.insert(0, "Traceback (most recent call last):\n") lines.extend(traceback.format_exception_only(exc_type, exc_value)) output = "".join(lines) sys.stderr.write(output) sys.stderr.flush() except Exception: sys.__excepthook__(exc_type, exc_value, exc_traceback)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def __init__( self, message, expression=None, filename=None, source=None, lineno=1, colno=1 ): """ Parameters ---------- message: str The message to display for this error. expression: HyObject, optional The Hy expression generating this error. filename: str, optional The filename for the source code generating this error. Expression-provided information will take precedence of this value. source: str, optional The actual source code generating this error. Expression-provided information will take precedence of this value. lineno: int, optional The line number of the error. Expression-provided information will take precedence of this value. colno: int, optional The column number of the error. Expression-provided information will take precedence of this value. """ self.msg = message self.compute_lineinfo(expression, filename, source, lineno, colno) if isinstance(self, SyntaxError): syntax_error_args = (self.filename, self.lineno, self.offset, self.text) super(HyLanguageError, self).__init__(message, syntax_error_args) else: super(HyLanguageError, self).__init__(message)
def __init__(self, message, filename=None, lineno=-1, colno=-1, source=None): """ Parameters ---------- message: str The exception's message. filename: str, optional The filename for the source code generating this error. lineno: int, optional The line number of the error. colno: int, optional The column number of the error. source: str, optional The actual source code generating this error. """ self.message = message self.filename = filename self.lineno = lineno self.colno = colno self.source = source super(HySyntaxError, self).__init__( message, # The builtin `SyntaxError` needs a # tuple. (filename, lineno, colno, source), )
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def __str__(self): """Provide an exception message that includes SyntaxError-like source line information when available. """ global _hy_colored_errors # Syntax errors are special and annotate the traceback (instead of what # we would do in the message that follows the traceback). if isinstance(self, SyntaxError): return super(HyLanguageError, self).__str__() # When there isn't extra source information, use the normal message. if not isinstance(self, SyntaxError) and not self.text: return super(HyLanguageError, self).__str__() # Re-purpose Python's builtin syntax error formatting. output = traceback.format_exception_only( SyntaxError, SyntaxError(self.msg, (self.filename, self.lineno, self.offset, self.text)), ) arrow_idx, _ = next( ((i, x) for i, x in enumerate(output) if x.strip() == "^"), (None, None) ) if arrow_idx: msg_idx = arrow_idx + 1 else: msg_idx, _ = next( (i, x) for i, x in enumerate(output) if x.startswith("SyntaxError: ") ) # Get rid of erroneous error-type label. output[msg_idx] = re.sub("^SyntaxError: ", "", output[msg_idx]) # Extend the text arrow, when given enough source info. if arrow_idx and self.arrow_offset: output[arrow_idx] = "{}{}^\n".format( output[arrow_idx].rstrip("\n"), "-" * (self.arrow_offset - 1) ) if _hy_colored_errors: from clint.textui import colored output[msg_idx:] = [colored.yellow(o) for o in output[msg_idx:]] if arrow_idx: output[arrow_idx] = colored.green(output[arrow_idx]) for idx, line in enumerate(output[::msg_idx]): if line.strip().startswith('File "{}", line'.format(self.filename)): output[idx] = colored.red(line) # This resulting string will come after a "<class-name>:" prompt, so # put it down a line. output.insert(0, "\n") # Avoid "...expected str instance, ColoredString found" return reduce(lambda x, y: x + y, output)
def __str__(self): global _hy_colored_errors output = traceback.format_exception_only(SyntaxError, SyntaxError(*self.args)) if _hy_colored_errors: from hy.errors import colored output[-1] = colored.yellow(output[-1]) if len(self.source) > 0: output[-2] = colored.green(output[-2]) for line in output[::-2]: if line.strip().startswith('File "{}", line'.format(self.filename)): break output[-3] = colored.red(output[-3]) # Avoid "...expected str instance, ColoredString found" return reduce(lambda x, y: x + y, output)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def hy_parse(source, filename="<string>"): """Parse a Hy source string. Parameters ---------- source: string Source code to parse. filename: string, optional File name corresponding to source. Defaults to "<string>". Returns ------- out : HyExpression """ _source = re.sub(r"\A#!.*", "", source) res = HyExpression([HySymbol("do")] + tokenize(_source + "\n", filename=filename)) res.source = source res.filename = filename return res
def hy_parse(source, filename="<string>"): """Parse a Hy source string. Parameters ---------- source: string Source code to parse. filename: string, optional File name corresponding to source. Defaults to "<string>". Returns ------- out : HyExpression """ _source = re.sub(r"\A#!.*", "", source) try: res = HyExpression( [HySymbol("do")] + tokenize(_source + "\n", filename=filename) ) res.source = source res.filename = filename return res except HySyntaxError as e: reraise(type(e), e, None)
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError
def tokenize(source, filename=None): """Tokenize a Lisp file or string buffer into internal Hy objects. Parameters ---------- source: str The source to tokenize. filename: str, optional The filename corresponding to `source`. """ from hy.lex.lexer import lexer from hy.lex.parser import parser from rply.errors import LexingError try: return parser.parse(lexer.lex(source), state=ParserState(source, filename)) except LexingError as e: pos = e.getsourcepos() raise LexException( "Could not identify the next token.", None, filename, source, max(pos.lineno, 1), max(pos.colno, 1), ) except LexException as e: raise e
def tokenize(source, filename=None): """Tokenize a Lisp file or string buffer into internal Hy objects. Parameters ---------- source: str The source to tokenize. filename: str, optional The filename corresponding to `source`. """ from hy.lex.lexer import lexer from hy.lex.parser import parser from rply.errors import LexingError try: return parser.parse(lexer.lex(source), state=ParserState(source, filename)) except LexingError as e: pos = e.getsourcepos() raise LexException( "Could not identify the next token.", filename, pos.lineno, pos.colno, source, )
https://github.com/hylang/hy/issues/1486
Traceback (most recent call last): File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/importer.py", line 180, in hy_eval _ast, expr = hy_compile(hytree, module_name, get_expr=True) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 2213, in hy_compile result = compiler.compile(tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 819, in compile_do return self._compile_branch(expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 873, in compile_try_expression name) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1002, in _compile_catch_expression body = self._compile_branch(expr) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in _compile_branch return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 318, in _branch results = list(results) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 545, in <genexpr> return _branch(self.compile(expr) for expr in exprs) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 372, in checker return fn(self, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 858, in compile_try_expression body += self.compile(expr.pop(0)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 472, in compile raise_empty(HyCompileError, e, sys.exc_info()[2]) File "<string>", line 1, in raise_empty hy.errors.HyCompileError: Internal Compiler Bug 😱 ⤷ ImportError: cannot require names: [HySymbol('let')] Compilation traceback: File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 460, in compile ret = self.compile_atom(_type, tree) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1731, in compile_expression ret = self.compile_atom(fn, expression) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 447, in compile_atom else _compile_table[atom_type](self, atom)) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/compiler.py", line 1486, in compile_require require(module, self.module_name, assignments=assignments) File "/home/johnzhuang/.virtualenvs/hy/lib/python3.6/site-packages/hy/macros.py", line 106, in require raise ImportError("cannot require names: " + repr(list(unseen)))
hy.errors.HyCompileError