code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def validate(cls, value: ColorArrayParam) -> 'ColorArray': """Validates and coerces the given value into an array storing many colors. Parameters ---------- value : Union[np.ndarray, list, tuple, None] A supported sequence of single color values. See ``ColorValue...
Validates and coerces the given value into an array storing many colors. Parameters ---------- value : Union[np.ndarray, list, tuple, None] A supported sequence of single color values. See ``ColorValue.validate`` for valid single color values. In general each...
validate
python
napari/napari
src/napari/utils/color.py
https://github.com/napari/napari/blob/master/src/napari/utils/color.py
BSD-3-Clause
def project_points_onto_plane( points: np.ndarray, plane_point: np.ndarray, plane_normal: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: """Project points on to a plane. Plane is defined by a point and a normal vector. This function is designed to work with points and planes in 3D. Parameters ...
Project points on to a plane. Plane is defined by a point and a normal vector. This function is designed to work with points and planes in 3D. Parameters ---------- points : np.ndarray The coordinate of the point to be projected. The points should be 3D and have shape shape (N,3) f...
project_points_onto_plane
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def rotation_matrix_from_vectors_2d( vec_1: np.ndarray, vec_2: np.ndarray ) -> np.ndarray: """Calculate the 2D rotation matrix to rotate vec_1 onto vec_2 Parameters ---------- vec_1 : np.ndarray The (2,) array containing the starting vector. vec_2 : np.ndarray The (2,) array con...
Calculate the 2D rotation matrix to rotate vec_1 onto vec_2 Parameters ---------- vec_1 : np.ndarray The (2,) array containing the starting vector. vec_2 : np.ndarray The (2,) array containing the destination vector. Returns ------- rotation_matrix : np.ndarray The ...
rotation_matrix_from_vectors_2d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def rotation_matrix_from_vectors_3d( vec_1: np.ndarray, vec_2: np.ndarray ) -> np.ndarray: """Calculate the rotation matrix that aligns vec1 to vec2. Parameters ---------- vec_1 : np.ndarray The vector you want to rotate vec_2 : np.ndarray The vector you would like to align to. ...
Calculate the rotation matrix that aligns vec1 to vec2. Parameters ---------- vec_1 : np.ndarray The vector you want to rotate vec_2 : np.ndarray The vector you would like to align to. Returns ------- rotation_matrix : np.ndarray The rotation matrix that aligns vec_...
rotation_matrix_from_vectors_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def rotate_points( points: np.ndarray, current_plane_normal: np.ndarray, new_plane_normal: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """Rotate points using a rotation matrix defined by the rotation from current_plane to new_plane. Parameters ---------- points : np.ndarray ...
Rotate points using a rotation matrix defined by the rotation from current_plane to new_plane. Parameters ---------- points : np.ndarray The points to rotate. They should all lie on the same plane with the normal vector current_plane_normal. Should be (NxD) array. current_plane_norm...
rotate_points
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def point_in_bounding_box(point: np.ndarray, bounding_box: np.ndarray) -> bool: """Determine whether an nD point is inside an nD bounding box. Parameters ---------- point : np.ndarray (n,) array containing nD point coordinates to check. bounding_box : np.ndarray (2, n) array contain...
Determine whether an nD point is inside an nD bounding box. Parameters ---------- point : np.ndarray (n,) array containing nD point coordinates to check. bounding_box : np.ndarray (2, n) array containing the min and max of the nD bounding box. As returned by `Layer._extent_data`...
point_in_bounding_box
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def face_coordinate_from_bounding_box( bounding_box: np.ndarray, face_normal: np.ndarray ) -> float: """Get the coordinate for a given face in an axis-aligned bounding box. For example, if the bounding box has extents [[0, 10], [0, 20], [0, 30]] (ordered zyx), then the face with normal [0, 1, 0] is desc...
Get the coordinate for a given face in an axis-aligned bounding box. For example, if the bounding box has extents [[0, 10], [0, 20], [0, 30]] (ordered zyx), then the face with normal [0, 1, 0] is described by y=20. Thus, the face_coordinate in this case is 20. Parameters ---------- bounding_box...
face_coordinate_from_bounding_box
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def intersect_line_with_axis_aligned_plane( plane_intercept: float, plane_normal: np.ndarray, line_start: np.ndarray, line_direction: np.ndarray, ) -> np.ndarray: """Find the intersection of a line with an axis aligned plane. Parameters ---------- plane_intercept : float The coo...
Find the intersection of a line with an axis aligned plane. Parameters ---------- plane_intercept : float The coordinate that the plane intersects on the axis to which plane is normal. For example, if the plane is described by y=42, plane_intercept is 42. plane_normal : np.ndarr...
intersect_line_with_axis_aligned_plane
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def bounding_box_to_face_vertices( bounding_box: np.ndarray, ) -> dict[str, np.ndarray]: """From a layer bounding box (N, 2), N=ndim, return a dictionary containing the vertices of each face of the bounding_box. Parameters ---------- bounding_box : np.ndarray (N, 2), N=ndim array with t...
From a layer bounding box (N, 2), N=ndim, return a dictionary containing the vertices of each face of the bounding_box. Parameters ---------- bounding_box : np.ndarray (N, 2), N=ndim array with the min and max value for each dimension of the bounding box. The bounding box is take form t...
bounding_box_to_face_vertices
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def inside_triangles(triangles): """Checks which triangles contain the origin Parameters ---------- triangles : (N, 3, 2) array Array of N triangles that should be checked Returns ------- inside : (N,) array of bool Array with `True` values for triangles containing the orig...
Checks which triangles contain the origin Parameters ---------- triangles : (N, 3, 2) array Array of N triangles that should be checked Returns ------- inside : (N,) array of bool Array with `True` values for triangles containing the origin
inside_triangles
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def intersect_line_with_plane_3d( line_position: npt.ArrayLike, line_direction: npt.ArrayLike, plane_position: npt.ArrayLike, plane_normal: npt.ArrayLike, ) -> np.ndarray: """Find the intersection of a line with an arbitrarily oriented plane in 3D. The line is defined by a position and a directi...
Find the intersection of a line with an arbitrarily oriented plane in 3D. The line is defined by a position and a direction vector. The plane is defined by a position and a normal vector. https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection Parameters ---------- line_position : np.ndarr...
intersect_line_with_plane_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def intersect_line_with_multiple_planes_3d( line_position: np.ndarray, line_direction: np.ndarray, plane_position: np.ndarray, plane_normal: np.ndarray, ) -> np.ndarray: """Find the intersection of a line with multiple arbitrarily oriented planes in 3D. The line is defined by a position and a di...
Find the intersection of a line with multiple arbitrarily oriented planes in 3D. The line is defined by a position and a direction vector. The plane is defined by a position and a normal vector. https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection Parameters ---------- line_position : ...
intersect_line_with_multiple_planes_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def intersect_line_with_triangles( line_point: np.ndarray, line_direction: np.ndarray, triangles: np.ndarray ) -> np.ndarray: """Find the intersection of a ray with a set of triangles. This function does not test whether the ray intersects the triangles, so you should have tested for intersection first...
Find the intersection of a ray with a set of triangles. This function does not test whether the ray intersects the triangles, so you should have tested for intersection first. See line_in_triangles_3d() for testing for intersection. Parameters ---------- line_point : np.ndarray The (3,...
intersect_line_with_triangles
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def point_in_quadrilateral_2d( point: np.ndarray, quadrilateral: np.ndarray ) -> bool: """Determines whether a point is inside a 2D quadrilateral. Parameters ---------- point : np.ndarray (2,) array containing coordinates of a point. quadrilateral : np.ndarray (4, 2) array conta...
Determines whether a point is inside a 2D quadrilateral. Parameters ---------- point : np.ndarray (2,) array containing coordinates of a point. quadrilateral : np.ndarray (4, 2) array containing the coordinates for the 4 corners of a quadrilateral. The vertices should be in cloc...
point_in_quadrilateral_2d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def line_in_quadrilateral_3d( line_point: np.ndarray, line_direction: np.ndarray, quadrilateral: np.ndarray, ) -> bool: """Determine if a line goes tbrough any of a set of quadrilaterals. For example, this could be used to determine if a click was in a specific face of a bounding box. Par...
Determine if a line goes tbrough any of a set of quadrilaterals. For example, this could be used to determine if a click was in a specific face of a bounding box. Parameters ---------- line_point : np.ndarray (3,) array containing the location that was clicked. This should be in t...
line_in_quadrilateral_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def line_in_triangles_3d( line_point: np.ndarray, line_direction: np.ndarray, triangles: np.ndarray ): """Determine if a line goes through any of a set of triangles. For example, this could be used to determine if a click was in a triangle of a mesh. Parameters ---------- line_point : np.n...
Determine if a line goes through any of a set of triangles. For example, this could be used to determine if a click was in a triangle of a mesh. Parameters ---------- line_point : np.ndarray (3,) array containing the location that was clicked. This should be in the same coordinate ...
line_in_triangles_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def find_front_back_face( click_pos: np.ndarray, bounding_box: np.ndarray, view_dir: np.ndarray ): """Find the faces of an axis aligned bounding box a click intersects with. Parameters ---------- click_pos : np.ndarray (3,) array containing the location that was clicked. bounding_bo...
Find the faces of an axis aligned bounding box a click intersects with. Parameters ---------- click_pos : np.ndarray (3,) array containing the location that was clicked. bounding_box : np.ndarray (N, 2), N=ndim array with the min and max value for each dimension of the bound...
find_front_back_face
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def intersect_line_with_axis_aligned_bounding_box_3d( line_point: np.ndarray, line_direction: np.ndarray, bounding_box: np.ndarray, face_normal: np.ndarray, ): """Find the intersection of a ray with the specified face of an axis-aligned bounding box. Parameters ---------- face_norma...
Find the intersection of a ray with the specified face of an axis-aligned bounding box. Parameters ---------- face_normal : np.ndarray The (3,) normal vector of the face the click intersects with. line_point : np.ndarray (3,) array containing the location that was clicked. bound...
intersect_line_with_axis_aligned_bounding_box_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def distance_between_point_and_line_3d( point: np.ndarray, line_position: np.ndarray, line_direction: np.ndarray ): """Determine the minimum distance between a point and a line in 3D. Parameters ---------- point : np.ndarray (3,) array containing coordinates of a point in 3D space. line...
Determine the minimum distance between a point and a line in 3D. Parameters ---------- point : np.ndarray (3,) array containing coordinates of a point in 3D space. line_position : np.ndarray (3,) array containing coordinates of a point on a line in 3D space. line_direction : np.ndar...
distance_between_point_and_line_3d
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def find_nearest_triangle_intersection( ray_position: np.ndarray, ray_direction: np.ndarray, triangles: np.ndarray ) -> tuple[int | None, np.ndarray | None]: """Given an array of triangles, find the index and intersection location of a ray and the nearest triangle. This returns only the triangle closes...
Given an array of triangles, find the index and intersection location of a ray and the nearest triangle. This returns only the triangle closest to the the ray_position. Parameters ---------- ray_position : np.ndarray The coordinate of the starting point of the ray. ray_direction : np.n...
find_nearest_triangle_intersection
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def get_center_bbox(roi: np.ndarray) -> tuple[list[float], int, int]: """Get the center coordinate, height, width of the roi. Parameters ---------- roi : np.ndarray An array of shape (4, 2) representing a rectangular roi. Returns ------- center_coords: list[float, float] ce...
Get the center coordinate, height, width of the roi. Parameters ---------- roi : np.ndarray An array of shape (4, 2) representing a rectangular roi. Returns ------- center_coords: list[float, float] center y and x coordinates of the roi height: int height of the roi...
get_center_bbox
python
napari/napari
src/napari/utils/geometry.py
https://github.com/napari/napari/blob/master/src/napari/utils/geometry.py
BSD-3-Clause
def update_open_history(filename: str) -> None: """Updates open history of files in settings. Parameters ---------- filename : str New file being added to open history. """ settings = get_settings() folders = settings.application.open_history new_loc = os.path.dirname(filename) ...
Updates open history of files in settings. Parameters ---------- filename : str New file being added to open history.
update_open_history
python
napari/napari
src/napari/utils/history.py
https://github.com/napari/napari/blob/master/src/napari/utils/history.py
BSD-3-Clause
def update_save_history(filename: str) -> None: """Updates save history of files in settings. Parameters ---------- filename : str New file being added to save history. """ settings = get_settings() folders = settings.application.save_history new_loc = os.path.dirname(filename) ...
Updates save history of files in settings. Parameters ---------- filename : str New file being added to save history.
update_save_history
python
napari/napari
src/napari/utils/history.py
https://github.com/napari/napari/blob/master/src/napari/utils/history.py
BSD-3-Clause
def _linux_sys_name() -> str: """ Try to discover linux system name base on /etc/os-release file or lsb_release command output https://www.freedesktop.org/software/systemd/man/os-release.html """ if os.path.exists(OS_RELEASE_PATH): with open(OS_RELEASE_PATH) as f_p: data = {} ...
Try to discover linux system name base on /etc/os-release file or lsb_release command output https://www.freedesktop.org/software/systemd/man/os-release.html
_linux_sys_name
python
napari/napari
src/napari/utils/info.py
https://github.com/napari/napari/blob/master/src/napari/utils/info.py
BSD-3-Clause
def _linux_sys_name_lsb_release() -> str: """ Try to discover linux system name base on lsb_release command output """ with contextlib.suppress(subprocess.CalledProcessError): res = subprocess.run( ['lsb_release', '-d', '-r'], check=True, capture_output=True ) text = ...
Try to discover linux system name base on lsb_release command output
_linux_sys_name_lsb_release
python
napari/napari
src/napari/utils/info.py
https://github.com/napari/napari/blob/master/src/napari/utils/info.py
BSD-3-Clause
def _sys_name() -> str: """ Discover MacOS or Linux Human readable information. For Linux provide information about distribution. """ with contextlib.suppress(Exception): if sys.platform == 'linux': return _linux_sys_name() if sys.platform == 'darwin': with contex...
Discover MacOS or Linux Human readable information. For Linux provide information about distribution.
_sys_name
python
napari/napari
src/napari/utils/info.py
https://github.com/napari/napari/blob/master/src/napari/utils/info.py
BSD-3-Clause
def _napari_from_conda() -> bool: """ Try to check if napari was installed using conda. This is done by checking for the presence of a conda metadata json file in the current environment's conda-meta directory. Returns ------- bool True if the main napari application is installed v...
Try to check if napari was installed using conda. This is done by checking for the presence of a conda metadata json file in the current environment's conda-meta directory. Returns ------- bool True if the main napari application is installed via conda, False otherwise.
_napari_from_conda
python
napari/napari
src/napari/utils/info.py
https://github.com/napari/napari/blob/master/src/napari/utils/info.py
BSD-3-Clause
def get_plugin_list() -> str: """Get a list of installed plugins. Returns ------- str A string containing the names and versions of installed plugins. """ try: from npe2 import PluginManager pm = PluginManager.instance() pm.discover(include_npe1=True) pm...
Get a list of installed plugins. Returns ------- str A string containing the names and versions of installed plugins.
get_plugin_list
python
napari/napari
src/napari/utils/info.py
https://github.com/napari/napari/blob/master/src/napari/utils/info.py
BSD-3-Clause
def sys_info(as_html: bool = False) -> str: """Gathers relevant module versions for troubleshooting purposes. Parameters ---------- as_html : bool if True, info will be returned as HTML, suitable for a QTextEdit widget """ sys_version = sys.version.replace('\n', ' ') text = f'<b>nap...
Gathers relevant module versions for troubleshooting purposes. Parameters ---------- as_html : bool if True, info will be returned as HTML, suitable for a QTextEdit widget
sys_info
python
napari/napari
src/napari/utils/info.py
https://github.com/napari/napari/blob/master/src/napari/utils/info.py
BSD-3-Clause
def mouse_wheel_callbacks(obj, event): """Run mouse wheel callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') ...
Run mouse wheel callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') yield # on move ...
mouse_wheel_callbacks
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def mouse_double_click_callbacks(obj, event) -> None: """Run mouse double_click callbacks on either layer or viewer object. Note that unlike other press and release callback those can't be generators: .. code-block:: python def double_click_callback(layer, event): layer._finish_drawin...
Run mouse double_click callbacks on either layer or viewer object. Note that unlike other press and release callback those can't be generators: .. code-block:: python def double_click_callback(layer, event): layer._finish_drawing() Parameters ---------- obj : ViewerModel or L...
mouse_double_click_callbacks
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def mouse_press_callbacks(obj, event): """Run mouse press callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') ...
Run mouse press callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') yield # on move ...
mouse_press_callbacks
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def mouse_move_callbacks(obj, event: 'NapariMouseEvent'): """Run mouse move callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('h...
Run mouse move callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') yield # on move ...
mouse_move_callbacks
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def mouse_release_callbacks(obj, event): """Run mouse release callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') ...
Run mouse release callbacks on either layer or viewer object. Note that drag callbacks should have the following form: .. code-block:: python def hello_world(layer, event): "dragging" # on press print('hello world!') yield # on move ...
mouse_release_callbacks
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def __init__(self, shortcut: KeyBindingLike) -> None: """Parameters ---------- shortcut : keybinding-like shortcut to format """ error_msg = trans._( '`{shortcut}` does not seem to be a valid shortcut Key.', shortcut=shortcut, ) ...
Parameters ---------- shortcut : keybinding-like shortcut to format
__init__
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def get_key_bindings_summary(keymap, col='rgb(134, 142, 147)'): """Get summary of key bindings in keymap. Parameters ---------- keymap : dict Dictionary of key bindings. col : str Color string in format rgb(int, int, int) used for highlighting keypress combination. Retu...
Get summary of key bindings in keymap. Parameters ---------- keymap : dict Dictionary of key bindings. col : str Color string in format rgb(int, int, int) used for highlighting keypress combination. Returns ------- str String with summary of all key_bindings...
get_key_bindings_summary
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def get_function_summary(func): """Get summary of doc string of function.""" doc = FunctionDoc(func) summary = '' for s in doc['Summary']: summary += s return summary.rstrip('.')
Get summary of doc string of function.
get_function_summary
python
napari/napari
src/napari/utils/interactions.py
https://github.com/napari/napari/blob/master/src/napari/utils/interactions.py
BSD-3-Clause
def imsave(filename: str, data: 'np.ndarray'): """Custom implementation of imsave to avoid skimage dependency. Parameters ---------- filename : string The path to write the file to. data : np.ndarray The image data. """ ext = os.path.splitext(filename)[1].lower() # If no...
Custom implementation of imsave to avoid skimage dependency. Parameters ---------- filename : string The path to write the file to. data : np.ndarray The image data.
imsave
python
napari/napari
src/napari/utils/io.py
https://github.com/napari/napari/blob/master/src/napari/utils/io.py
BSD-3-Clause
def imsave_png(filename, data): """Save .png image to file PNG images created in napari have a digital watermark. The napari version info is embedded into the bytes of the PNG. Parameters ---------- filename : string The path to write the file to. data : np.ndarray The imag...
Save .png image to file PNG images created in napari have a digital watermark. The napari version info is embedded into the bytes of the PNG. Parameters ---------- filename : string The path to write the file to. data : np.ndarray The image data.
imsave_png
python
napari/napari
src/napari/utils/io.py
https://github.com/napari/napari/blob/master/src/napari/utils/io.py
BSD-3-Clause
def imsave_tiff(filename, data): """Save .tiff image to file Parameters ---------- filename : string The path to write the file to. data : np.ndarray The image data. """ import tifffile if data.dtype == bool: tifffile.imwrite(filename, data) else: tr...
Save .tiff image to file Parameters ---------- filename : string The path to write the file to. data : np.ndarray The image data.
imsave_tiff
python
napari/napari
src/napari/utils/io.py
https://github.com/napari/napari/blob/master/src/napari/utils/io.py
BSD-3-Clause
def coerce_keybinding(key_bind: KeyBindingLike) -> KeyBinding: """Convert a keybinding-like object to a KeyBinding. Parameters ---------- key_bind : keybinding-like Object to coerce. Returns ------- key_bind : KeyBinding Object as KeyBinding. """ if isinstance(key_b...
Convert a keybinding-like object to a KeyBinding. Parameters ---------- key_bind : keybinding-like Object to coerce. Returns ------- key_bind : KeyBinding Object as KeyBinding.
coerce_keybinding
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def bind_key( keymap: Keymap, key_bind: KeyBindingLike | EllipsisType, func=_UNDEFINED, *, overwrite=False, ): """Bind a key combination to a keymap. Parameters ---------- keymap : dict of str: callable Keymap to modify. key_bind : keybinding-like or ... Key comb...
Bind a key combination to a keymap. Parameters ---------- keymap : dict of str: callable Keymap to modify. key_bind : keybinding-like or ... Key combination. ``...`` acts as a wildcard if no key combinations can be matched in the keymap (this will overwrite all key combi...
bind_key
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def _bind_user_key( key_bind: KeyBindingLike, func=_UNDEFINED, *, overwrite=False ): """Bind a key combination to the user keymap. See ``bind_key`` docs for details. """ return bind_key(_get_user_keymap(), key_bind, func, overwrite=overwrite)
Bind a key combination to the user keymap. See ``bind_key`` docs for details.
_bind_user_key
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def _bind_keymap(keymap, instance): """Bind all functions in a keymap to an instance. Parameters ---------- keymap : dict Keymap to bind. instance : object Instance to bind to. Returns ------- bound_keymap : dict Keymap with functions bound to the instance. ...
Bind all functions in a keymap to an instance. Parameters ---------- keymap : dict Keymap to bind. instance : object Instance to bind to. Returns ------- bound_keymap : dict Keymap with functions bound to the instance.
_bind_keymap
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def keymap_chain(self): """collections.ChainMap: Chain of keymaps from keymap providers.""" maps = [_get_user_keymap()] for parent in self.keymap_providers: maps.append(_bind_keymap(parent.keymap, parent)) # For parent and superclasses add inherited keybindings ...
collections.ChainMap: Chain of keymaps from keymap providers.
keymap_chain
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def active_keymap(self): """dict: Active keymap, created by resolving the keymap chain.""" active_keymap = self.keymap_chain keymaps = active_keymap.maps for i, keymap in enumerate(keymaps): if Ellipsis in keymap: # catch-all key # trim all keymaps after cat...
dict: Active keymap, created by resolving the keymap chain.
active_keymap
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def press_key(self, key_bind: KeyBindingLike) -> bool: """Simulate a key press to activate a keybinding. Parameters ---------- key_bind : keybinding-like Key combination. """ key_bind = coerce_keybinding(key_bind) keymap = self.active_keymap i...
Simulate a key press to activate a keybinding. Parameters ---------- key_bind : keybinding-like Key combination.
press_key
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def release_key(self, key_bind: KeyBindingLike) -> bool: """Simulate a key release for a keybinding. Parameters ---------- key_bind : keybinding-like Key combination. """ from napari.settings import get_settings key_bind = coerce_keybinding(key_bind)...
Simulate a key release for a keybinding. Parameters ---------- key_bind : keybinding-like Key combination.
release_key
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def on_key_press(self, event): """Called whenever key pressed in canvas. Parameters ---------- event : vispy.util.event.Event The vispy key press event that triggered this method. """ from napari.utils.action_manager import action_manager if event.ke...
Called whenever key pressed in canvas. Parameters ---------- event : vispy.util.event.Event The vispy key press event that triggered this method.
on_key_press
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def on_key_release(self, event): """Called whenever key released in canvas. Parameters ---------- event : vispy.util.event.Event The vispy key release event that triggered this method. """ if event.key is None or ( # on linux press down is treated...
Called whenever key released in canvas. Parameters ---------- event : vispy.util.event.Event The vispy key release event that triggered this method.
on_key_release
python
napari/napari
src/napari/utils/key_bindings.py
https://github.com/napari/napari/blob/master/src/napari/utils/key_bindings.py
BSD-3-Clause
def rename_argument( from_name: str, to_name: str, version: str, since_version: str = '' ) -> Callable: """ This is decorator for simple rename function argument without break backward compatibility. Parameters ---------- from_name : str old name of argument to_name : str ...
This is decorator for simple rename function argument without break backward compatibility. Parameters ---------- from_name : str old name of argument to_name : str new name of argument version : str version when old argument will be removed since_version : str ...
rename_argument
python
napari/napari
src/napari/utils/migrations.py
https://github.com/napari/napari/blob/master/src/napari/utils/migrations.py
BSD-3-Clause
def add_deprecated_property( obj: Any, previous_name: str, new_name: str, version: str, since_version: str, ) -> None: """ Adds deprecated property and links to new property name setter and getter. Parameters ---------- obj: Class instances to add property previous_n...
Adds deprecated property and links to new property name setter and getter. Parameters ---------- obj: Class instances to add property previous_name : str Name of previous property, its methods must be removed. new_name : str Name of new property, must have its getter (a...
add_deprecated_property
python
napari/napari
src/napari/utils/migrations.py
https://github.com/napari/napari/blob/master/src/napari/utils/migrations.py
BSD-3-Clause
def deprecated_constructor_arg_by_attr(name: str) -> Callable: """ Decorator to deprecate a constructor argument and remove it from the signature. It works by popping the argument from kwargs, and setting it later via setattr. The property setter should take care of issuing the deprecation warning. ...
Decorator to deprecate a constructor argument and remove it from the signature. It works by popping the argument from kwargs, and setting it later via setattr. The property setter should take care of issuing the deprecation warning. Parameters ---------- name : str Name of the argumen...
deprecated_constructor_arg_by_attr
python
napari/napari
src/napari/utils/migrations.py
https://github.com/napari/napari/blob/master/src/napari/utils/migrations.py
BSD-3-Clause
def deprecated_class_name( new_class: type, previous_name: str, version: str, since_version: str, ) -> type: """Function to deprecate a class. Usage: class NewName: pass OldName = deprecated_class_name( NewName, 'OldName', version='0.5.0', since_version...
Function to deprecate a class. Usage: class NewName: pass OldName = deprecated_class_name( NewName, 'OldName', version='0.5.0', since_version='0.4.19' )
deprecated_class_name
python
napari/napari
src/napari/utils/migrations.py
https://github.com/napari/napari/blob/master/src/napari/utils/migrations.py
BSD-3-Clause
def set_deprecated_from_rename( self, *, from_name: str, to_name: str, version: str, since_version: str ) -> None: """Sets a deprecated key with a value that comes from another key. A warning message is automatically generated using the given version information. """ self._r...
Sets a deprecated key with a value that comes from another key. A warning message is automatically generated using the given version information.
set_deprecated_from_rename
python
napari/napari
src/napari/utils/migrations.py
https://github.com/napari/napari/blob/master/src/napari/utils/migrations.py
BSD-3-Clause
def parse_version(v: str) -> packaging.version._BaseVersion: """Parse a version string and return a packaging.version.Version obj.""" import packaging.version try: return packaging.version.Version(v) except packaging.version.InvalidVersion: return packaging.version.LegacyVersion(v) # t...
Parse a version string and return a packaging.version.Version obj.
parse_version
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def running_as_constructor_app() -> bool: """Infer whether we are running as a constructor bundle.""" return ( Path(sys.prefix).parent.parent / '.napari_is_bundled_constructor' ).exists()
Infer whether we are running as a constructor bundle.
running_as_constructor_app
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def in_jupyter() -> bool: """Return true if we're running in jupyter notebook/lab or qtconsole.""" with contextlib.suppress(ImportError): from IPython import get_ipython return get_ipython().__class__.__name__ == 'ZMQInteractiveShell' return False
Return true if we're running in jupyter notebook/lab or qtconsole.
in_jupyter
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def in_ipython() -> bool: """Return true if we're running in an IPython interactive shell.""" with contextlib.suppress(ImportError): from IPython import get_ipython return get_ipython().__class__.__name__ == 'TerminalInteractiveShell' return False
Return true if we're running in an IPython interactive shell.
in_ipython
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def in_python_repl() -> bool: """Return true if we're running in a Python REPL.""" with contextlib.suppress(ImportError): from IPython import get_ipython return get_ipython().__class__.__name__ == 'NoneType' and hasattr( sys, 'ps1' ) return False
Return true if we're running in a Python REPL.
in_python_repl
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def str_to_rgb(arg: str) -> list[int]: """Convert an rgb string 'rgb(x,y,z)' to a list of ints [x,y,z].""" match = re.match(r'rgb\((\d+),\s*(\d+),\s*(\d+)\)', arg) if match is None: raise ValueError("arg not in format 'rgb(x,y,z)'") return list(map(int, match.groups()))
Convert an rgb string 'rgb(x,y,z)' to a list of ints [x,y,z].
str_to_rgb
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def ensure_iterable( arg: None | str | Enum | float | list | npt.NDArray, ): """Ensure an argument is an iterable. Useful when an input argument can either be a single value or a list. """ if is_iterable(arg): return arg return itertools.repeat(arg)
Ensure an argument is an iterable. Useful when an input argument can either be a single value or a list.
ensure_iterable
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def is_iterable( arg: None | str | Enum | float | list | npt.NDArray, allow_none: bool = False, ) -> bool: """Determine if a single argument is an iterable.""" if arg is None: return allow_none # Here if arg is None it used to return allow_none if isinstance(arg, str | Enum) or np.issca...
Determine if a single argument is an iterable.
is_iterable
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def is_sequence(arg: Any) -> bool: """Check if ``arg`` is a sequence like a list or tuple. return True: list tuple return False: string numbers dict set """ return bool( isinstance(arg, collections.abc.Sequence) and not isinstance(arg, str) ...
Check if ``arg`` is a sequence like a list or tuple. return True: list tuple return False: string numbers dict set
is_sequence
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def ensure_sequence_of_iterables( obj: Any, length: int | None = None, repeat_empty: bool = False, allow_none: bool = False, ): """Ensure that ``obj`` behaves like a (nested) sequence of iterables. If length is provided and the object is already a sequence of iterables, a ValueError will be...
Ensure that ``obj`` behaves like a (nested) sequence of iterables. If length is provided and the object is already a sequence of iterables, a ValueError will be raised if ``len(obj) != length``. Parameters ---------- obj : Any the object to check length : int, optional If provi...
ensure_sequence_of_iterables
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def formatdoc(obj): """Substitute globals and locals into an object's docstring.""" frame = inspect.currentframe().f_back try: obj.__doc__ = obj.__doc__.format( **{**frame.f_globals, **frame.f_locals} ) finally: del frame return obj
Substitute globals and locals into an object's docstring.
formatdoc
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def __getitem__(self, item): """set the item name case to uppercase for name lookup""" if isinstance(item, str): item = item.upper() return super().__getitem__(item)
set the item name case to uppercase for name lookup
__getitem__
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def __call__( cls, value, names=None, *, module=None, qualname=None, type=None, # noqa: A002 start=1, ): """set the item value case to lowercase for value lookup""" # simple value lookup if names is None: if isinsta...
set the item value case to lowercase for value lookup
__call__
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def abspath_or_url(relpath: T, *, must_exist: bool = False) -> T: """Utility function that normalizes paths or a sequence thereof. Expands user directory and converts relpaths to abspaths... but ignores URLS that begin with "http", "ftp", or "file". Parameters ---------- relpath : str|Path ...
Utility function that normalizes paths or a sequence thereof. Expands user directory and converts relpaths to abspaths... but ignores URLS that begin with "http", "ftp", or "file". Parameters ---------- relpath : str|Path A path, either as string or Path object. must_exist : bool, defa...
abspath_or_url
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def all_subclasses(cls: type) -> set: """Recursively find all subclasses of class ``cls``. Parameters ---------- cls : class A python class (or anything that implements a __subclasses__ method). Returns ------- set the set of all classes that are subclassed from ``cls`` ...
Recursively find all subclasses of class ``cls``. Parameters ---------- cls : class A python class (or anything that implements a __subclasses__ method). Returns ------- set the set of all classes that are subclassed from ``cls``
all_subclasses
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def ensure_n_tuple(val: Iterable, n: int, fill: int = 0) -> tuple: """Ensure input is a length n tuple. Parameters ---------- val : iterable Iterable to be forced into length n-tuple. n : int Length of tuple. Returns ------- tuple Coerced tuple. """ asse...
Ensure input is a length n tuple. Parameters ---------- val : iterable Iterable to be forced into length n-tuple. n : int Length of tuple. Returns ------- tuple Coerced tuple.
ensure_n_tuple
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def _arraylike_short_names(obj) -> Iterator[str]: """Yield all the short names of an array-like or its class.""" type_ = type(obj) if not inspect.isclass(obj) else obj for base in type_.mro(): yield f'{base.__module__.split(".", maxsplit=1)[0]}.{base.__name__}'
Yield all the short names of an array-like or its class.
_arraylike_short_names
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def pick_equality_operator(obj: Any) -> Callable[[Any, Any], bool]: """Return a function that can check equality between ``obj`` and another. Rather than always using ``==`` (i.e. ``operator.eq``), this function returns operators that are aware of object types: mostly "array types with more than one el...
Return a function that can check equality between ``obj`` and another. Rather than always using ``==`` (i.e. ``operator.eq``), this function returns operators that are aware of object types: mostly "array types with more than one element" whose truth value is ambiguous. This function works for both cl...
pick_equality_operator
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def dir_hash( path: str | Path, include_paths: bool = True, ignore_hidden: bool = True, ) -> str: """Compute the hash of a directory, based on structure and contents. Parameters ---------- path : Union[str, Path] Source path which will be used to select all files (and files in subdi...
Compute the hash of a directory, based on structure and contents. Parameters ---------- path : Union[str, Path] Source path which will be used to select all files (and files in subdirectories) to compute the hexadecimal digest. include_paths : bool If ``True``, the hash will als...
dir_hash
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def paths_hash( paths: Iterable[str | Path], include_paths: bool = True, ignore_hidden: bool = True, ) -> str: """Compute the hash of list of paths. Parameters ---------- paths : Iterable[Union[str, Path]] An iterable of paths to files which will be used when computing the hash. ...
Compute the hash of list of paths. Parameters ---------- paths : Iterable[Union[str, Path]] An iterable of paths to files which will be used when computing the hash. include_paths : bool If ``True``, the hash will also include the ``file`` parts. ignore_hidden : bool If ``Tr...
paths_hash
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def _file_hash( _hash, file: Path, path: Path, include_paths: bool = True ) -> None: """Update hash with based on file contents and optionally relative path. Parameters ---------- _hash file : Path Path to the source file which will be used to compute the hash. path : Path P...
Update hash with based on file contents and optionally relative path. Parameters ---------- _hash file : Path Path to the source file which will be used to compute the hash. path : Path Path to the base directory of the `file`. This can be usually obtained by using `file.parent`. ...
_file_hash
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def _combine_signatures( *objects: Callable, return_annotation=inspect.Signature.empty, exclude: Iterable[str] = (), ) -> inspect.Signature: """Create combined Signature from objects, excluding names in `exclude`. Parameters ---------- *objects : Callable callables whose signatures ...
Create combined Signature from objects, excluding names in `exclude`. Parameters ---------- *objects : Callable callables whose signatures should be combined return_annotation : [type], optional The return annotation to use for combined signature, by default inspect.Signature.em...
_combine_signatures
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def install_certifi_opener() -> None: """Install urlopener that uses certifi context. This is useful in the bundle, where otherwise users might get SSL errors when using `urllib.request.urlopen`. """ import ssl from urllib import request import certifi context = ssl.create_default_con...
Install urlopener that uses certifi context. This is useful in the bundle, where otherwise users might get SSL errors when using `urllib.request.urlopen`.
install_certifi_opener
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def reorder_after_dim_reduction(order: Sequence[int]) -> tuple[int, ...]: """Ensure current dimension order is preserved after dims are dropped. This is similar to :func:`scipy.stats.rankdata`, but only deals with unique integers (like dimension indices), so is simpler and faster. Parameters -----...
Ensure current dimension order is preserved after dims are dropped. This is similar to :func:`scipy.stats.rankdata`, but only deals with unique integers (like dimension indices), so is simpler and faster. Parameters ---------- order : Sequence[int] The data to reorder. Returns ---...
reorder_after_dim_reduction
python
napari/napari
src/napari/utils/misc.py
https://github.com/napari/napari/blob/master/src/napari/utils/misc.py
BSD-3-Clause
def magic_name(value: Any, *, path_prefix: str = ROOT_DIR) -> str | None: """Fetch the name of the variable with the given value passed to the calling function. Parameters ---------- value : any The value of the desired variable. path_prefix : absolute path-like, kwonly The path pre...
Fetch the name of the variable with the given value passed to the calling function. Parameters ---------- value : any The value of the desired variable. path_prefix : absolute path-like, kwonly The path prefixes to ignore. Returns ------- name : str or None Name of ...
magic_name
python
napari/napari
src/napari/utils/naming.py
https://github.com/napari/napari/blob/master/src/napari/utils/naming.py
BSD-3-Clause
def __init__( self, viewer, *, canvas_only=False, alt_text=None, ) -> None: """Initialize screenshot object. Parameters ---------- viewer : napari.Viewer The napari viewer canvas_only : bool, optional If False i...
Initialize screenshot object. Parameters ---------- viewer : napari.Viewer The napari viewer canvas_only : bool, optional If False include the napari viewer frame in the screenshot, and if True then take screenshot of just the image display canvas. ...
__init__
python
napari/napari
src/napari/utils/notebook_display.py
https://github.com/napari/napari/blob/master/src/napari/utils/notebook_display.py
BSD-3-Clause
def _clean_alt_text(self, alt_text): """Clean user input to prevent script injection.""" if alt_text is not None: if lxml_unavailable: warn( 'The lxml_html_clean library is not installed, and is ' 'required to sanitize alt text for napa...
Clean user input to prevent script injection.
_clean_alt_text
python
napari/napari
src/napari/utils/notebook_display.py
https://github.com/napari/napari/blob/master/src/napari/utils/notebook_display.py
BSD-3-Clause
def _repr_png_(self): """PNG representation of the viewer object for IPython. Returns ------- In memory binary stream containing PNG screenshot image. """ from napari._qt.qt_event_loop import get_qapp get_qapp().processEvents() self.image = self.viewer.s...
PNG representation of the viewer object for IPython. Returns ------- In memory binary stream containing PNG screenshot image.
_repr_png_
python
napari/napari
src/napari/utils/notebook_display.py
https://github.com/napari/napari/blob/master/src/napari/utils/notebook_display.py
BSD-3-Clause
def install_hooks(self): """ Install a `sys.excepthook`, a `showwarning` hook and a threading.excepthook to display any message in the UI, storing the previous hooks to be restored if necessary. """ # TODO: we might want to display the additional thread information ...
Install a `sys.excepthook`, a `showwarning` hook and a threading.excepthook to display any message in the UI, storing the previous hooks to be restored if necessary.
install_hooks
python
napari/napari
src/napari/utils/notifications.py
https://github.com/napari/napari/blob/master/src/napari/utils/notifications.py
BSD-3-Clause
def restore_hooks(self): """ Remove hooks installed by `install_hooks` and restore previous hooks. """ threading.excepthook = self._originals_thread_except_hooks.pop() sys.excepthook = self._originals_except_hooks.pop() warnings.showwarning = self._original_showwarnings_...
Remove hooks installed by `install_hooks` and restore previous hooks.
restore_hooks
python
napari/napari
src/napari/utils/notifications.py
https://github.com/napari/napari/blob/master/src/napari/utils/notifications.py
BSD-3-Clause
def show_debug(message: str): """ Show a debug message in the notification manager. """ notification_manager.dispatch( Notification(message, severity=NotificationSeverity.DEBUG) )
Show a debug message in the notification manager.
show_debug
python
napari/napari
src/napari/utils/notifications.py
https://github.com/napari/napari/blob/master/src/napari/utils/notifications.py
BSD-3-Clause
def show_info(message: str): """ Show an info message in the notification manager. """ notification_manager.dispatch( Notification(message, severity=NotificationSeverity.INFO) )
Show an info message in the notification manager.
show_info
python
napari/napari
src/napari/utils/notifications.py
https://github.com/napari/napari/blob/master/src/napari/utils/notifications.py
BSD-3-Clause
def show_warning(message: str): """ Show a warning in the notification manager. """ notification_manager.dispatch( Notification(message, severity=NotificationSeverity.WARNING) )
Show a warning in the notification manager.
show_warning
python
napari/napari
src/napari/utils/notifications.py
https://github.com/napari/napari/blob/master/src/napari/utils/notifications.py
BSD-3-Clause
def show_error(message: str): """ Show an error in the notification manager. """ notification_manager.dispatch( Notification(message, severity=NotificationSeverity.ERROR) )
Show an error in the notification manager.
show_error
python
napari/napari
src/napari/utils/notifications.py
https://github.com/napari/napari/blob/master/src/napari/utils/notifications.py
BSD-3-Clause
def increment_with_overflow(self): """Update if not exceeding total, else set indeterminate range.""" if self.n == self.total: self.total = 0 self.events.overflow() else: self.update(1)
Update if not exceeding total, else set indeterminate range.
increment_with_overflow
python
napari/napari
src/napari/utils/progress.py
https://github.com/napari/napari/blob/master/src/napari/utils/progress.py
BSD-3-Clause
def status_format(value): """Return a "nice" string representation of a value. Parameters ---------- value : Any The value to be printed. Returns ------- formatted : str The string resulting from formatting. Examples -------- >>> values = np.array([1, 10, 100, ...
Return a "nice" string representation of a value. Parameters ---------- value : Any The value to be printed. Returns ------- formatted : str The string resulting from formatting. Examples -------- >>> values = np.array([1, 10, 100, 1000, 1e6, 6.283, 123.932021, ...
status_format
python
napari/napari
src/napari/utils/status_messages.py
https://github.com/napari/napari/blob/master/src/napari/utils/status_messages.py
BSD-3-Clause
def generate_layer_status(name, position, value): """Generate a status message based on the coordinates and value Parameters ---------- name : str Name of the layer. position : tuple or list List of coordinates, say of the cursor. value : Any The value to be printed. ...
Generate a status message based on the coordinates and value Parameters ---------- name : str Name of the layer. position : tuple or list List of coordinates, say of the cursor. value : Any The value to be printed. Returns ------- msg : string String con...
generate_layer_status
python
napari/napari
src/napari/utils/status_messages.py
https://github.com/napari/napari/blob/master/src/napari/utils/status_messages.py
BSD-3-Clause
def _guess_exports(module, exclude=()) -> list[str]: """If __all__ wasn't provided, this function guesses what to stub.""" return [ k for k, v in vars(module).items() if callable(v) and not k.startswith('_') and k not in exclude ]
If __all__ wasn't provided, this function guesses what to stub.
_guess_exports
python
napari/napari
src/napari/utils/stubgen.py
https://github.com/napari/napari/blob/master/src/napari/utils/stubgen.py
BSD-3-Clause
def _iter_imports(hint) -> Iterator[str]: """Get all imports necessary for `hint`""" # inspect.formatannotation strips "typing." from type annotations # so our signatures won't have it in there if not repr(hint).startswith('typing.') and (orig := get_origin(hint)): yield orig.__module__ for...
Get all imports necessary for `hint`
_iter_imports
python
napari/napari
src/napari/utils/stubgen.py
https://github.com/napari/napari/blob/master/src/napari/utils/stubgen.py
BSD-3-Clause
def generate_function_stub(func) -> tuple[set[str], str]: """Generate a stub and imports for a function.""" sig = inspect.signature(func) if hasattr(func, '__wrapped__'): # unwrap @wraps decorated functions func = func.__wrapped__ globalns = {**getattr(func, '__globals__', {})} glob...
Generate a stub and imports for a function.
generate_function_stub
python
napari/napari
src/napari/utils/stubgen.py
https://github.com/napari/napari/blob/master/src/napari/utils/stubgen.py
BSD-3-Clause
def _get_subclass_methods(cls: type[Any]) -> set[str]: """Return the set of method names defined (only) on a subclass.""" all_methods = set(dir(cls)) base_methods = (dir(base()) for base in cls.__bases__) return all_methods.difference(*base_methods)
Return the set of method names defined (only) on a subclass.
_get_subclass_methods
python
napari/napari
src/napari/utils/stubgen.py
https://github.com/napari/napari/blob/master/src/napari/utils/stubgen.py
BSD-3-Clause
def generate_class_stubs(cls: type) -> tuple[set[str], str]: """Generate a stub and imports for a class.""" bases = ', '.join(f'{b.__module__}.{b.__name__}' for b in cls.__bases__) methods = [] attrs = [] imports = set() local_names = set(cls.__dict__).union(set(cls.__annotations__)) for s...
Generate a stub and imports for a class.
generate_class_stubs
python
napari/napari
src/napari/utils/stubgen.py
https://github.com/napari/napari/blob/master/src/napari/utils/stubgen.py
BSD-3-Clause
def generate_module_stub(module: str | ModuleType, save=True) -> str: """Generate a pyi stub for a module. By default saves to .pyi file with the same name as the module. """ if isinstance(module, str): module = importlib.import_module(module) # try to use __all__, or guess exports nam...
Generate a pyi stub for a module. By default saves to .pyi file with the same name as the module.
generate_module_stub
python
napari/napari
src/napari/utils/stubgen.py
https://github.com/napari/napari/blob/master/src/napari/utils/stubgen.py
BSD-3-Clause
def to_rgb_dict(self) -> dict[str, Any]: """ This differs from baseclass `dict()` by converting colors to rgb. """ th = super().dict() return { k: v if not isinstance(v, Color) else v.as_rgb() for (k, v) in th.items() }
This differs from baseclass `dict()` by converting colors to rgb.
to_rgb_dict
python
napari/napari
src/napari/utils/theme.py
https://github.com/napari/napari/blob/master/src/napari/utils/theme.py
BSD-3-Clause
def get_system_theme() -> str: """Return the system default theme, either 'dark', or 'light'.""" try: from napari._vendor import darkdetect except ImportError: return 'dark' try: id_ = darkdetect.theme().lower() except AttributeError: id_ = 'dark' return id_
Return the system default theme, either 'dark', or 'light'.
get_system_theme
python
napari/napari
src/napari/utils/theme.py
https://github.com/napari/napari/blob/master/src/napari/utils/theme.py
BSD-3-Clause