id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
172,167 | from __future__ import annotations
import asyncio
import logging
import os
import re
import shlex
import shutil
import subprocess
import tempfile
from collections import deque
from enum import Enum
from functools import wraps
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
Deque,
Iterable,
List,
Optional,
Set,
Tuple,
TypeVar,
Union,
cast,
)
from .application.current import get_app
from .application.run_in_terminal import run_in_terminal
from .auto_suggest import AutoSuggest, Suggestion
from .cache import FastDictCache
from .clipboard import ClipboardData
from .completion import (
CompleteEvent,
Completer,
Completion,
DummyCompleter,
get_common_complete_suffix,
)
from .document import Document
from .eventloop import aclosing
from .filters import FilterOrBool, to_filter
from .history import History, InMemoryHistory
from .search import SearchDirection, SearchState
from .selection import PasteMode, SelectionState, SelectionType
from .utils import Event, to_str
from .validation import ValidationError, Validator
_T = TypeVar("_T", bound=Callable[..., Awaitable[None]])
class _Retry(Exception):
"Retry in `_only_one_at_a_time`."
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ...
Any = object()
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
The provided code snippet includes necessary dependencies for implementing the `_only_one_at_a_time` function. Write a Python function `def _only_one_at_a_time(coroutine: _T) -> _T` to solve the following problem:
Decorator that only starts the coroutine only if the previous call has finished. (Used to make sure that we have only one autocompleter, auto suggestor and validator running at a time.) When the coroutine raises `_Retry`, it is restarted.
Here is the function:
def _only_one_at_a_time(coroutine: _T) -> _T:
"""
Decorator that only starts the coroutine only if the previous call has
finished. (Used to make sure that we have only one autocompleter, auto
suggestor and validator running at a time.)
When the coroutine raises `_Retry`, it is restarted.
"""
running = False
@wraps(coroutine)
async def new_coroutine(*a: Any, **kw: Any) -> Any:
nonlocal running
# Don't start a new function, if the previous is still in progress.
if running:
return
running = True
try:
while True:
try:
await coroutine(*a, **kw)
except _Retry:
continue
else:
return None
finally:
running = False
return cast(_T, new_coroutine) | Decorator that only starts the coroutine only if the previous call has finished. (Used to make sure that we have only one autocompleter, auto suggestor and validator running at a time.) When the coroutine raises `_Retry`, it is restarted. |
172,168 | from __future__ import annotations
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from .containers import Window
from .controls import FormattedTextControl
from .dimension import D
from .layout import Layout
E = KeyPressEvent
class Window(Container):
"""
Container that holds a control.
:param content: :class:`.UIControl` instance.
:param width: :class:`.Dimension` instance or callable.
:param height: :class:`.Dimension` instance or callable.
:param z_index: When specified, this can be used to bring element in front
of floating elements.
:param dont_extend_width: When `True`, don't take up more width then the
preferred width reported by the control.
:param dont_extend_height: When `True`, don't take up more width then the
preferred height reported by the control.
:param ignore_content_width: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` width when calculating the dimensions.
:param ignore_content_height: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` height when calculating the dimensions.
:param left_margins: A list of :class:`.Margin` instance to be displayed on
the left. For instance: :class:`~prompt_toolkit.layout.NumberedMargin`
can be one of them in order to show line numbers.
:param right_margins: Like `left_margins`, but on the other side.
:param scroll_offsets: :class:`.ScrollOffsets` instance, representing the
preferred amount of lines/columns to be always visible before/after the
cursor. When both top and bottom are a very high number, the cursor
will be centered vertically most of the time.
:param allow_scroll_beyond_bottom: A `bool` or
:class:`.Filter` instance. When True, allow scrolling so far, that the
top part of the content is not visible anymore, while there is still
empty space available at the bottom of the window. In the Vi editor for
instance, this is possible. You will see tildes while the top part of
the body is hidden.
:param wrap_lines: A `bool` or :class:`.Filter` instance. When True, don't
scroll horizontally, but wrap lines instead.
:param get_vertical_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
(When this is `None`, the scroll is only determined by the last and
current cursor position.)
:param get_horizontal_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
:param always_hide_cursor: A `bool` or
:class:`.Filter` instance. When True, never display the cursor, even
when the user control specifies a cursor position.
:param cursorline: A `bool` or :class:`.Filter` instance. When True,
display a cursorline.
:param cursorcolumn: A `bool` or :class:`.Filter` instance. When True,
display a cursorcolumn.
:param colorcolumns: A list of :class:`.ColorColumn` instances that
describe the columns to be highlighted, or a callable that returns such
a list.
:param align: :class:`.WindowAlign` value or callable that returns an
:class:`.WindowAlign` value. alignment of content.
:param style: A style string. Style to be applied to all the cells in this
window. (This can be a callable that returns a string.)
:param char: (string) Character to be used for filling the background. This
can also be a callable that returns a character.
:param get_line_prefix: None or a callable that returns formatted text to
be inserted before a line. It takes a line number (int) and a
wrap_count and returns formatted text. This can be used for
implementation of line continuations, things like Vim "breakindent" and
so on.
"""
def __init__(
self,
content: UIControl | None = None,
width: AnyDimension = None,
height: AnyDimension = None,
z_index: int | None = None,
dont_extend_width: FilterOrBool = False,
dont_extend_height: FilterOrBool = False,
ignore_content_width: FilterOrBool = False,
ignore_content_height: FilterOrBool = False,
left_margins: Sequence[Margin] | None = None,
right_margins: Sequence[Margin] | None = None,
scroll_offsets: ScrollOffsets | None = None,
allow_scroll_beyond_bottom: FilterOrBool = False,
wrap_lines: FilterOrBool = False,
get_vertical_scroll: Callable[[Window], int] | None = None,
get_horizontal_scroll: Callable[[Window], int] | None = None,
always_hide_cursor: FilterOrBool = False,
cursorline: FilterOrBool = False,
cursorcolumn: FilterOrBool = False,
colorcolumns: (
None | list[ColorColumn] | Callable[[], list[ColorColumn]]
) = None,
align: WindowAlign | Callable[[], WindowAlign] = WindowAlign.LEFT,
style: str | Callable[[], str] = "",
char: None | str | Callable[[], str] = None,
get_line_prefix: GetLinePrefixCallable | None = None,
) -> None:
self.allow_scroll_beyond_bottom = to_filter(allow_scroll_beyond_bottom)
self.always_hide_cursor = to_filter(always_hide_cursor)
self.wrap_lines = to_filter(wrap_lines)
self.cursorline = to_filter(cursorline)
self.cursorcolumn = to_filter(cursorcolumn)
self.content = content or DummyControl()
self.dont_extend_width = to_filter(dont_extend_width)
self.dont_extend_height = to_filter(dont_extend_height)
self.ignore_content_width = to_filter(ignore_content_width)
self.ignore_content_height = to_filter(ignore_content_height)
self.left_margins = left_margins or []
self.right_margins = right_margins or []
self.scroll_offsets = scroll_offsets or ScrollOffsets()
self.get_vertical_scroll = get_vertical_scroll
self.get_horizontal_scroll = get_horizontal_scroll
self.colorcolumns = colorcolumns or []
self.align = align
self.style = style
self.char = char
self.get_line_prefix = get_line_prefix
self.width = width
self.height = height
self.z_index = z_index
# Cache for the screens generated by the margin.
self._ui_content_cache: SimpleCache[
tuple[int, int, int], UIContent
] = SimpleCache(maxsize=8)
self._margin_width_cache: SimpleCache[tuple[Margin, int], int] = SimpleCache(
maxsize=1
)
self.reset()
def __repr__(self) -> str:
return "Window(content=%r)" % self.content
def reset(self) -> None:
self.content.reset()
#: Scrolling position of the main content.
self.vertical_scroll = 0
self.horizontal_scroll = 0
# Vertical scroll 2: this is the vertical offset that a line is
# scrolled if a single line (the one that contains the cursor) consumes
# all of the vertical space.
self.vertical_scroll_2 = 0
#: Keep render information (mappings between buffer input and render
#: output.)
self.render_info: WindowRenderInfo | None = None
def _get_margin_width(self, margin: Margin) -> int:
"""
Return the width for this margin.
(Calculate only once per render time.)
"""
# Margin.get_width, needs to have a UIContent instance.
def get_ui_content() -> UIContent:
return self._get_ui_content(width=0, height=0)
def get_width() -> int:
return margin.get_width(get_ui_content)
key = (margin, get_app().render_counter)
return self._margin_width_cache.get(key, get_width)
def _get_total_margin_width(self) -> int:
"""
Calculate and return the width of the margin (left + right).
"""
return sum(self._get_margin_width(m) for m in self.left_margins) + sum(
self._get_margin_width(m) for m in self.right_margins
)
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Calculate the preferred width for this window.
"""
def preferred_content_width() -> int | None:
"""Content width: is only calculated if no exact width for the
window was given."""
if self.ignore_content_width():
return None
# Calculate the width of the margin.
total_margin_width = self._get_total_margin_width()
# Window of the content. (Can be `None`.)
preferred_width = self.content.preferred_width(
max_available_width - total_margin_width
)
if preferred_width is not None:
# Include width of the margins.
preferred_width += total_margin_width
return preferred_width
# Merge.
return self._merge_dimensions(
dimension=to_dimension(self.width),
get_preferred=preferred_content_width,
dont_extend=self.dont_extend_width(),
)
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Calculate the preferred height for this window.
"""
def preferred_content_height() -> int | None:
"""Content height: is only calculated if no exact height for the
window was given."""
if self.ignore_content_height():
return None
total_margin_width = self._get_total_margin_width()
wrap_lines = self.wrap_lines()
return self.content.preferred_height(
width - total_margin_width,
max_available_height,
wrap_lines,
self.get_line_prefix,
)
return self._merge_dimensions(
dimension=to_dimension(self.height),
get_preferred=preferred_content_height,
dont_extend=self.dont_extend_height(),
)
def _merge_dimensions(
dimension: Dimension | None,
get_preferred: Callable[[], int | None],
dont_extend: bool = False,
) -> Dimension:
"""
Take the Dimension from this `Window` class and the received preferred
size from the `UIControl` and return a `Dimension` to report to the
parent container.
"""
dimension = dimension or Dimension()
# When a preferred dimension was explicitly given to the Window,
# ignore the UIControl.
preferred: int | None
if dimension.preferred_specified:
preferred = dimension.preferred
else:
# Otherwise, calculate the preferred dimension from the UI control
# content.
preferred = get_preferred()
# When a 'preferred' dimension is given by the UIControl, make sure
# that it stays within the bounds of the Window.
if preferred is not None:
if dimension.max_specified:
preferred = min(preferred, dimension.max)
if dimension.min_specified:
preferred = max(preferred, dimension.min)
# When a `dont_extend` flag has been given, use the preferred dimension
# also as the max dimension.
max_: int | None
min_: int | None
if dont_extend and preferred is not None:
max_ = min(dimension.max, preferred)
else:
max_ = dimension.max if dimension.max_specified else None
min_ = dimension.min if dimension.min_specified else None
return Dimension(
min=min_, max=max_, preferred=preferred, weight=dimension.weight
)
def _get_ui_content(self, width: int, height: int) -> UIContent:
"""
Create a `UIContent` instance.
"""
def get_content() -> UIContent:
return self.content.create_content(width=width, height=height)
key = (get_app().render_counter, width, height)
return self._ui_content_cache.get(key, get_content)
def _get_digraph_char(self) -> str | None:
"Return `False`, or the Digraph symbol to be used."
app = get_app()
if app.quoted_insert:
return "^"
if app.vi_state.waiting_for_digraph:
if app.vi_state.digraph_symbol1:
return app.vi_state.digraph_symbol1
return "?"
return None
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: int | None,
) -> None:
"""
Write window to screen. This renders the user control, the margins and
copies everything over to the absolute position at the given screen.
"""
# If dont_extend_width/height was given. Then reduce width/height in
# WritePosition if the parent wanted us to paint in a bigger area.
# (This happens if this window is bundled with another window in a
# HSplit/VSplit, but with different size requirements.)
write_position = WritePosition(
xpos=write_position.xpos,
ypos=write_position.ypos,
width=write_position.width,
height=write_position.height,
)
if self.dont_extend_width():
write_position.width = min(
write_position.width,
self.preferred_width(write_position.width).preferred,
)
if self.dont_extend_height():
write_position.height = min(
write_position.height,
self.preferred_height(
write_position.width, write_position.height
).preferred,
)
# Draw
z_index = z_index if self.z_index is None else self.z_index
draw_func = partial(
self._write_to_screen_at_index,
screen,
mouse_handlers,
write_position,
parent_style,
erase_bg,
)
if z_index is None or z_index <= 0:
# When no z_index is given, draw right away.
draw_func()
else:
# Otherwise, postpone.
screen.draw_with_z_index(z_index=z_index, draw_func=draw_func)
def _write_to_screen_at_index(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
) -> None:
# Don't bother writing invisible windows.
# (We save some time, but also avoid applying last-line styling.)
if write_position.height <= 0 or write_position.width <= 0:
return
# Calculate margin sizes.
left_margin_widths = [self._get_margin_width(m) for m in self.left_margins]
right_margin_widths = [self._get_margin_width(m) for m in self.right_margins]
total_margin_width = sum(left_margin_widths + right_margin_widths)
# Render UserControl.
ui_content = self.content.create_content(
write_position.width - total_margin_width, write_position.height
)
assert isinstance(ui_content, UIContent)
# Scroll content.
wrap_lines = self.wrap_lines()
self._scroll(
ui_content, write_position.width - total_margin_width, write_position.height
)
# Erase background and fill with `char`.
self._fill_bg(screen, write_position, erase_bg)
# Resolve `align` attribute.
align = self.align() if callable(self.align) else self.align
# Write body
visible_line_to_row_col, rowcol_to_yx = self._copy_body(
ui_content,
screen,
write_position,
sum(left_margin_widths),
write_position.width - total_margin_width,
self.vertical_scroll,
self.horizontal_scroll,
wrap_lines=wrap_lines,
highlight_lines=True,
vertical_scroll_2=self.vertical_scroll_2,
always_hide_cursor=self.always_hide_cursor(),
has_focus=get_app().layout.current_control == self.content,
align=align,
get_line_prefix=self.get_line_prefix,
)
# Remember render info. (Set before generating the margins. They need this.)
x_offset = write_position.xpos + sum(left_margin_widths)
y_offset = write_position.ypos
render_info = WindowRenderInfo(
window=self,
ui_content=ui_content,
horizontal_scroll=self.horizontal_scroll,
vertical_scroll=self.vertical_scroll,
window_width=write_position.width - total_margin_width,
window_height=write_position.height,
configured_scroll_offsets=self.scroll_offsets,
visible_line_to_row_col=visible_line_to_row_col,
rowcol_to_yx=rowcol_to_yx,
x_offset=x_offset,
y_offset=y_offset,
wrap_lines=wrap_lines,
)
self.render_info = render_info
# Set mouse handlers.
def mouse_handler(mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Wrapper around the mouse_handler of the `UIControl` that turns
screen coordinates into line coordinates.
Returns `NotImplemented` if no UI invalidation should be done.
"""
# Don't handle mouse events outside of the current modal part of
# the UI.
if self not in get_app().layout.walk_through_modal_area():
return NotImplemented
# Find row/col position first.
yx_to_rowcol = {v: k for k, v in rowcol_to_yx.items()}
y = mouse_event.position.y
x = mouse_event.position.x
# If clicked below the content area, look for a position in the
# last line instead.
max_y = write_position.ypos + len(visible_line_to_row_col) - 1
y = min(max_y, y)
result: NotImplementedOrNone
while x >= 0:
try:
row, col = yx_to_rowcol[y, x]
except KeyError:
# Try again. (When clicking on the right side of double
# width characters, or on the right side of the input.)
x -= 1
else:
# Found position, call handler of UIControl.
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=col, y=row),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
break
else:
# nobreak.
# (No x/y coordinate found for the content. This happens in
# case of a DummyControl, that does not have any content.
# Report (0,0) instead.)
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=0, y=0),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
# If it returns NotImplemented, handle it here.
if result == NotImplemented:
result = self._mouse_handler(mouse_event)
return result
mouse_handlers.set_mouse_handler_for_range(
x_min=write_position.xpos + sum(left_margin_widths),
x_max=write_position.xpos + write_position.width - total_margin_width,
y_min=write_position.ypos,
y_max=write_position.ypos + write_position.height,
handler=mouse_handler,
)
# Render and copy margins.
move_x = 0
def render_margin(m: Margin, width: int) -> UIContent:
"Render margin. Return `Screen`."
# Retrieve margin fragments.
fragments = m.create_margin(render_info, width, write_position.height)
# Turn it into a UIContent object.
# already rendered those fragments using this size.)
return FormattedTextControl(fragments).create_content(
width + 1, write_position.height
)
for m, width in zip(self.left_margins, left_margin_widths):
if width > 0: # (ConditionalMargin returns a zero width. -- Don't render.)
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
move_x = write_position.width - sum(right_margin_widths)
for m, width in zip(self.right_margins, right_margin_widths):
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
# Apply 'self.style'
self._apply_style(screen, write_position, parent_style)
# Tell the screen that this user control has been painted at this
# position.
screen.visible_windows_to_write_positions[self] = write_position
def _copy_body(
self,
ui_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
vertical_scroll: int = 0,
horizontal_scroll: int = 0,
wrap_lines: bool = False,
highlight_lines: bool = False,
vertical_scroll_2: int = 0,
always_hide_cursor: bool = False,
has_focus: bool = False,
align: WindowAlign = WindowAlign.LEFT,
get_line_prefix: Callable[[int, int], AnyFormattedText] | None = None,
) -> tuple[dict[int, tuple[int, int]], dict[tuple[int, int], tuple[int, int]]]:
"""
Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple.
:param get_line_prefix: None or a callable that takes a line number
(int) and a wrap_count (int) and returns formatted text.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
line_count = ui_content.line_count
new_buffer = new_screen.data_buffer
empty_char = _CHAR_CACHE["", ""]
# Map visible line number to (row, col) of input.
# 'col' will always be zero if line wrapping is off.
visible_line_to_row_col: dict[int, tuple[int, int]] = {}
# Maps (row, col) from the input to (y, x) screen coordinates.
rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
def copy_line(
line: StyleAndTextTuples,
lineno: int,
x: int,
y: int,
is_input: bool = False,
) -> tuple[int, int]:
"""
Copy over a single line to the output screen. This can wrap over
multiple lines in the output. It will call the prefix (prompt)
function before every line.
"""
if is_input:
current_rowcol_to_yx = rowcol_to_yx
else:
current_rowcol_to_yx = {} # Throwaway dictionary.
# Draw line prefix.
if is_input and get_line_prefix:
prompt = to_formatted_text(get_line_prefix(lineno, 0))
x, y = copy_line(prompt, lineno, x, y, is_input=False)
# Scroll horizontally.
skipped = 0 # Characters skipped because of horizontal scrolling.
if horizontal_scroll and is_input:
h_scroll = horizontal_scroll
line = explode_text_fragments(line)
while h_scroll > 0 and line:
h_scroll -= get_cwidth(line[0][1])
skipped += 1
del line[:1] # Remove first character.
x -= h_scroll # When scrolling over double width character,
# this can end up being negative.
# Align this line. (Note that this doesn't work well when we use
# get_line_prefix and that function returns variable width prefixes.)
if align == WindowAlign.CENTER:
line_width = fragment_list_width(line)
if line_width < width:
x += (width - line_width) // 2
elif align == WindowAlign.RIGHT:
line_width = fragment_list_width(line)
if line_width < width:
x += width - line_width
col = 0
wrap_count = 0
for style, text, *_ in line:
new_buffer_row = new_buffer[y + ypos]
# Remember raw VT escape sequences. (E.g. FinalTerm's
# escape sequences.)
if "[ZeroWidthEscape]" in style:
new_screen.zero_width_escapes[y + ypos][x + xpos] += text
continue
for c in text:
char = _CHAR_CACHE[c, style]
char_width = char.width
# Wrap when the line width is exceeded.
if wrap_lines and x + char_width > width:
visible_line_to_row_col[y + 1] = (
lineno,
visible_line_to_row_col[y][1] + x,
)
y += 1
wrap_count += 1
x = 0
# Insert line prefix (continuation prompt).
if is_input and get_line_prefix:
prompt = to_formatted_text(
get_line_prefix(lineno, wrap_count)
)
x, y = copy_line(prompt, lineno, x, y, is_input=False)
new_buffer_row = new_buffer[y + ypos]
if y >= write_position.height:
return x, y # Break out of all for loops.
# Set character in screen and shift 'x'.
if x >= 0 and y >= 0 and x < width:
new_buffer_row[x + xpos] = char
# When we print a multi width character, make sure
# to erase the neighbours positions in the screen.
# (The empty string if different from everything,
# so next redraw this cell will repaint anyway.)
if char_width > 1:
for i in range(1, char_width):
new_buffer_row[x + xpos + i] = empty_char
# If this is a zero width characters, then it's
# probably part of a decomposed unicode character.
# See: https://en.wikipedia.org/wiki/Unicode_equivalence
# Merge it in the previous cell.
elif char_width == 0:
# Handle all character widths. If the previous
# character is a multiwidth character, then
# merge it two positions back.
for pw in [2, 1]: # Previous character width.
if (
x - pw >= 0
and new_buffer_row[x + xpos - pw].width == pw
):
prev_char = new_buffer_row[x + xpos - pw]
char2 = _CHAR_CACHE[
prev_char.char + c, prev_char.style
]
new_buffer_row[x + xpos - pw] = char2
# Keep track of write position for each character.
current_rowcol_to_yx[lineno, col + skipped] = (
y + ypos,
x + xpos,
)
col += 1
x += char_width
return x, y
# Copy content.
def copy() -> int:
y = -vertical_scroll_2
lineno = vertical_scroll
while y < write_position.height and lineno < line_count:
# Take the next line and copy it in the real screen.
line = ui_content.get_line(lineno)
visible_line_to_row_col[y] = (lineno, horizontal_scroll)
# Copy margin and actual line.
x = 0
x, y = copy_line(line, lineno, x, y, is_input=True)
lineno += 1
y += 1
return y
copy()
def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
"Translate row/col from UIContent to real Screen coordinates."
try:
y, x = rowcol_to_yx[row, col]
except KeyError:
# Normally this should never happen. (It is a bug, if it happens.)
# But to be sure, return (0, 0)
return Point(x=0, y=0)
# raise ValueError(
# 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
# 'horizontal_scroll=%r, height=%r' %
# (row, col, vertical_scroll, horizontal_scroll, write_position.height))
else:
return Point(x=x, y=y)
# Set cursor and menu positions.
if ui_content.cursor_position:
screen_cursor_position = cursor_pos_to_screen_pos(
ui_content.cursor_position.y, ui_content.cursor_position.x
)
if has_focus:
new_screen.set_cursor_position(self, screen_cursor_position)
if always_hide_cursor:
new_screen.show_cursor = False
else:
new_screen.show_cursor = ui_content.show_cursor
self._highlight_digraph(new_screen)
if highlight_lines:
self._highlight_cursorlines(
new_screen,
screen_cursor_position,
xpos,
ypos,
width,
write_position.height,
)
# Draw input characters from the input processor queue.
if has_focus and ui_content.cursor_position:
self._show_key_processor_key_buffer(new_screen)
# Set menu position.
if ui_content.menu_position:
new_screen.set_menu_position(
self,
cursor_pos_to_screen_pos(
ui_content.menu_position.y, ui_content.menu_position.x
),
)
# Update output screen height.
new_screen.height = max(new_screen.height, ypos + write_position.height)
return visible_line_to_row_col, rowcol_to_yx
def _fill_bg(
self, screen: Screen, write_position: WritePosition, erase_bg: bool
) -> None:
"""
Erase/fill the background.
(Useful for floats and when a `char` has been given.)
"""
char: str | None
if callable(self.char):
char = self.char()
else:
char = self.char
if erase_bg or char:
wp = write_position
char_obj = _CHAR_CACHE[char or " ", ""]
for y in range(wp.ypos, wp.ypos + wp.height):
row = screen.data_buffer[y]
for x in range(wp.xpos, wp.xpos + wp.width):
row[x] = char_obj
def _apply_style(
self, new_screen: Screen, write_position: WritePosition, parent_style: str
) -> None:
# Apply `self.style`.
style = parent_style + " " + to_str(self.style)
new_screen.fill_area(write_position, style=style, after=False)
# Apply the 'last-line' class to the last line of each Window. This can
# be used to apply an 'underline' to the user control.
wp = WritePosition(
write_position.xpos,
write_position.ypos + write_position.height - 1,
write_position.width,
1,
)
new_screen.fill_area(wp, "class:last-line", after=True)
def _highlight_digraph(self, new_screen: Screen) -> None:
"""
When we are in Vi digraph mode, put a question mark underneath the
cursor.
"""
digraph_char = self._get_digraph_char()
if digraph_char:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
digraph_char, "class:digraph"
]
def _show_key_processor_key_buffer(self, new_screen: Screen) -> None:
"""
When the user is typing a key binding that consists of several keys,
display the last pressed key if the user is in insert mode and the key
is meaningful to be displayed.
E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
first 'j' needs to be displayed in order to get some feedback.
"""
app = get_app()
key_buffer = app.key_processor.key_buffer
if key_buffer and _in_insert_mode() and not app.is_done:
# The textual data for the given key. (Can be a VT100 escape
# sequence.)
data = key_buffer[-1].data
# Display only if this is a 1 cell width character.
if get_cwidth(data) == 1:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
data, "class:partial-key-binding"
]
def _highlight_cursorlines(
self, new_screen: Screen, cpos: Point, x: int, y: int, width: int, height: int
) -> None:
"""
Highlight cursor row/column.
"""
cursor_line_style = " class:cursor-line "
cursor_column_style = " class:cursor-column "
data_buffer = new_screen.data_buffer
# Highlight cursor line.
if self.cursorline():
row = data_buffer[cpos.y]
for x in range(x, x + width):
original_char = row[x]
row[x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_line_style
]
# Highlight cursor column.
if self.cursorcolumn():
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[cpos.x]
row[cpos.x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_column_style
]
# Highlight color columns
colorcolumns = self.colorcolumns
if callable(colorcolumns):
colorcolumns = colorcolumns()
for cc in colorcolumns:
assert isinstance(cc, ColorColumn)
column = cc.position
if column < x + width: # Only draw when visible.
color_column_style = " " + cc.style
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[column + x]
row[column + x] = _CHAR_CACHE[
original_char.char, original_char.style + color_column_style
]
def _copy_margin(
self,
margin_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
) -> None:
"""
Copy characters from the margin screen to the real screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
self._copy_body(margin_content, new_screen, margin_write_position, 0, width)
def _scroll(self, ui_content: UIContent, width: int, height: int) -> None:
"""
Scroll body. Ensure that the cursor is visible.
"""
if self.wrap_lines():
func = self._scroll_when_linewrapping
else:
func = self._scroll_without_linewrapping
func(ui_content, width, height)
def _scroll_when_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
scroll_offsets_bottom = self.scroll_offsets.bottom
scroll_offsets_top = self.scroll_offsets.top
# We don't have horizontal scrolling.
self.horizontal_scroll = 0
def get_line_height(lineno: int) -> int:
return ui_content.get_height_for_line(lineno, width, self.get_line_prefix)
# When there is no space, reset `vertical_scroll_2` to zero and abort.
# This can happen if the margin is bigger than the window width.
# Otherwise the text height will become "infinite" (a big number) and
# the copy_line will spend a huge amount of iterations trying to render
# nothing.
if width <= 0:
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = 0
return
# If the current line consumes more than the whole window height,
# then we have to scroll vertically inside this line. (We don't take
# the scroll offsets into account for this.)
# Also, ignore the scroll offsets in this case. Just set the vertical
# scroll to this line.
line_height = get_line_height(ui_content.cursor_position.y)
if line_height > height - scroll_offsets_top:
# Calculate the height of the text before the cursor (including
# line prefixes).
text_before_height = ui_content.get_height_for_line(
ui_content.cursor_position.y,
width,
self.get_line_prefix,
slice_stop=ui_content.cursor_position.x,
)
# Adjust scroll offset.
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = min(
text_before_height - 1, # Keep the cursor visible.
line_height
- height, # Avoid blank lines at the bottom when scolling up again.
self.vertical_scroll_2,
)
self.vertical_scroll_2 = max(
0, text_before_height - height, self.vertical_scroll_2
)
return
else:
self.vertical_scroll_2 = 0
# Current line doesn't consume the whole height. Take scroll offsets into account.
def get_min_vertical_scroll() -> int:
# Make sure that the cursor line is not below the bottom.
# (Calculate how many lines can be shown between the cursor and the .)
used_height = 0
prev_lineno = ui_content.cursor_position.y
for lineno in range(ui_content.cursor_position.y, -1, -1):
used_height += get_line_height(lineno)
if used_height > height - scroll_offsets_bottom:
return prev_lineno
else:
prev_lineno = lineno
return 0
def get_max_vertical_scroll() -> int:
# Make sure that the cursor line is not above the top.
prev_lineno = ui_content.cursor_position.y
used_height = 0
for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > scroll_offsets_top:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
def get_topmost_visible() -> int:
"""
Calculate the upper most line that can be visible, while the bottom
is still visible. We should not allow scroll more than this if
`allow_scroll_beyond_bottom` is false.
"""
prev_lineno = ui_content.line_count - 1
used_height = 0
for lineno in range(ui_content.line_count - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > height:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
# Scroll vertically. (Make sure that the whole line which contains the
# cursor is visible.
topmost_visible = get_topmost_visible()
# Note: the `min(topmost_visible, ...)` is to make sure that we
# don't require scrolling up because of the bottom scroll offset,
# when we are at the end of the document.
self.vertical_scroll = max(
self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll())
)
self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
# Disallow scrolling beyond bottom?
if not self.allow_scroll_beyond_bottom():
self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
def _scroll_without_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
cursor_position = ui_content.cursor_position or Point(x=0, y=0)
# Without line wrapping, we will never have to scroll vertically inside
# a single line.
self.vertical_scroll_2 = 0
if ui_content.line_count == 0:
self.vertical_scroll = 0
self.horizontal_scroll = 0
return
else:
current_line_text = fragment_list_to_text(
ui_content.get_line(cursor_position.y)
)
def do_scroll(
current_scroll: int,
scroll_offset_start: int,
scroll_offset_end: int,
cursor_pos: int,
window_size: int,
content_size: int,
) -> int:
"Scrolling algorithm. Used for both horizontal and vertical scrolling."
# Calculate the scroll offset to apply.
# This can obviously never be more than have the screen size. Also, when the
# cursor appears at the top or bottom, we don't apply the offset.
scroll_offset_start = int(
min(scroll_offset_start, window_size / 2, cursor_pos)
)
scroll_offset_end = int(
min(scroll_offset_end, window_size / 2, content_size - 1 - cursor_pos)
)
# Prevent negative scroll offsets.
if current_scroll < 0:
current_scroll = 0
# Scroll back if we scrolled to much and there's still space to show more of the document.
if (
not self.allow_scroll_beyond_bottom()
and current_scroll > content_size - window_size
):
current_scroll = max(0, content_size - window_size)
# Scroll up if cursor is before visible part.
if current_scroll > cursor_pos - scroll_offset_start:
current_scroll = max(0, cursor_pos - scroll_offset_start)
# Scroll down if cursor is after visible part.
if current_scroll < (cursor_pos + 1) - window_size + scroll_offset_end:
current_scroll = (cursor_pos + 1) - window_size + scroll_offset_end
return current_scroll
# When a preferred scroll is given, take that first into account.
if self.get_vertical_scroll:
self.vertical_scroll = self.get_vertical_scroll(self)
assert isinstance(self.vertical_scroll, int)
if self.get_horizontal_scroll:
self.horizontal_scroll = self.get_horizontal_scroll(self)
assert isinstance(self.horizontal_scroll, int)
# Update horizontal/vertical scroll to make sure that the cursor
# remains visible.
offsets = self.scroll_offsets
self.vertical_scroll = do_scroll(
current_scroll=self.vertical_scroll,
scroll_offset_start=offsets.top,
scroll_offset_end=offsets.bottom,
cursor_pos=ui_content.cursor_position.y,
window_size=height,
content_size=ui_content.line_count,
)
if self.get_line_prefix:
current_line_prefix_width = fragment_list_width(
to_formatted_text(self.get_line_prefix(ui_content.cursor_position.y, 0))
)
else:
current_line_prefix_width = 0
self.horizontal_scroll = do_scroll(
current_scroll=self.horizontal_scroll,
scroll_offset_start=offsets.left,
scroll_offset_end=offsets.right,
cursor_pos=get_cwidth(current_line_text[: ui_content.cursor_position.x]),
window_size=width - current_line_prefix_width,
# We can only analyse the current line. Calculating the width off
# all the lines is too expensive.
content_size=max(
get_cwidth(current_line_text), self.horizontal_scroll + width
),
)
def _mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Mouse handler. Called when the UI control doesn't handle this
particular event.
Return `NotImplemented` if nothing was done as a consequence of this
key binding (no UI invalidate required in that case).
"""
if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
self._scroll_down()
return None
elif mouse_event.event_type == MouseEventType.SCROLL_UP:
self._scroll_up()
return None
return NotImplemented
def _scroll_down(self) -> None:
"Scroll window down."
info = self.render_info
if info is None:
return
if self.vertical_scroll < info.content_height - info.window_height:
if info.cursor_position.y <= info.configured_scroll_offsets.top:
self.content.move_cursor_down()
self.vertical_scroll += 1
def _scroll_up(self) -> None:
"Scroll window up."
info = self.render_info
if info is None:
return
if info.vertical_scroll > 0:
# TODO: not entirely correct yet in case of line wrapping and long lines.
if (
info.cursor_position.y
>= info.window_height - 1 - info.configured_scroll_offsets.bottom
):
self.content.move_cursor_up()
self.vertical_scroll -= 1
def get_key_bindings(self) -> KeyBindingsBase | None:
return self.content.get_key_bindings()
def get_children(self) -> list[Container]:
return []
class FormattedTextControl(UIControl):
"""
Control that displays formatted text. This can be either plain text, an
:class:`~prompt_toolkit.formatted_text.HTML` object an
:class:`~prompt_toolkit.formatted_text.ANSI` object, a list of ``(style_str,
text)`` tuples or a callable that takes no argument and returns one of
those, depending on how you prefer to do the formatting. See
``prompt_toolkit.layout.formatted_text`` for more information.
(It's mostly optimized for rather small widgets, like toolbars, menus, etc...)
When this UI control has the focus, the cursor will be shown in the upper
left corner of this control by default. There are two ways for specifying
the cursor position:
- Pass a `get_cursor_position` function which returns a `Point` instance
with the current cursor position.
- If the (formatted) text is passed as a list of ``(style, text)`` tuples
and there is one that looks like ``('[SetCursorPosition]', '')``, then
this will specify the cursor position.
Mouse support:
The list of fragments can also contain tuples of three items, looking like:
(style_str, text, handler). When mouse support is enabled and the user
clicks on this fragment, then the given handler is called. That handler
should accept two inputs: (Application, MouseEvent) and it should
either handle the event or return `NotImplemented` in case we want the
containing Window to handle this event.
:param focusable: `bool` or :class:`.Filter`: Tell whether this control is
focusable.
:param text: Text or formatted text to be displayed.
:param style: Style string applied to the content. (If you want to style
the whole :class:`~prompt_toolkit.layout.Window`, pass the style to the
:class:`~prompt_toolkit.layout.Window` instead.)
:param key_bindings: a :class:`.KeyBindings` object.
:param get_cursor_position: A callable that returns the cursor position as
a `Point` instance.
"""
def __init__(
self,
text: AnyFormattedText = "",
style: str = "",
focusable: FilterOrBool = False,
key_bindings: KeyBindingsBase | None = None,
show_cursor: bool = True,
modal: bool = False,
get_cursor_position: Callable[[], Point | None] | None = None,
) -> None:
self.text = text # No type check on 'text'. This is done dynamically.
self.style = style
self.focusable = to_filter(focusable)
# Key bindings.
self.key_bindings = key_bindings
self.show_cursor = show_cursor
self.modal = modal
self.get_cursor_position = get_cursor_position
#: Cache for the content.
self._content_cache: SimpleCache[Hashable, UIContent] = SimpleCache(maxsize=18)
self._fragment_cache: SimpleCache[int, StyleAndTextTuples] = SimpleCache(
maxsize=1
)
# Only cache one fragment list. We don't need the previous item.
# Render info for the mouse support.
self._fragments: StyleAndTextTuples | None = None
def reset(self) -> None:
self._fragments = None
def is_focusable(self) -> bool:
return self.focusable()
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.text!r})"
def _get_formatted_text_cached(self) -> StyleAndTextTuples:
"""
Get fragments, but only retrieve fragments once during one render run.
(This function is called several times during one rendering, because
we also need those for calculating the dimensions.)
"""
return self._fragment_cache.get(
get_app().render_counter, lambda: to_formatted_text(self.text, self.style)
)
def preferred_width(self, max_available_width: int) -> int:
"""
Return the preferred width for this control.
That is the width of the longest line.
"""
text = fragment_list_to_text(self._get_formatted_text_cached())
line_lengths = [get_cwidth(l) for l in text.split("\n")]
return max(line_lengths)
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int | None:
"""
Return the preferred height for this control.
"""
content = self.create_content(width, None)
if wrap_lines:
height = 0
for i in range(content.line_count):
height += content.get_height_for_line(i, width, get_line_prefix)
if height >= max_available_height:
return max_available_height
return height
else:
return content.line_count
def create_content(self, width: int, height: int | None) -> UIContent:
# Get fragments
fragments_with_mouse_handlers = self._get_formatted_text_cached()
fragment_lines_with_mouse_handlers = list(
split_lines(fragments_with_mouse_handlers)
)
# Strip mouse handlers from fragments.
fragment_lines: list[StyleAndTextTuples] = [
[(item[0], item[1]) for item in line]
for line in fragment_lines_with_mouse_handlers
]
# Keep track of the fragments with mouse handler, for later use in
# `mouse_handler`.
self._fragments = fragments_with_mouse_handlers
# If there is a `[SetCursorPosition]` in the fragment list, set the
# cursor position here.
def get_cursor_position(
fragment: str = "[SetCursorPosition]",
) -> Point | None:
for y, line in enumerate(fragment_lines):
x = 0
for style_str, text, *_ in line:
if fragment in style_str:
return Point(x=x, y=y)
x += len(text)
return None
# If there is a `[SetMenuPosition]`, set the menu over here.
def get_menu_position() -> Point | None:
return get_cursor_position("[SetMenuPosition]")
cursor_position = (self.get_cursor_position or get_cursor_position)()
# Create content, or take it from the cache.
key = (tuple(fragments_with_mouse_handlers), width, cursor_position)
def get_content() -> UIContent:
return UIContent(
get_line=lambda i: fragment_lines[i],
line_count=len(fragment_lines),
show_cursor=self.show_cursor,
cursor_position=cursor_position,
menu_position=get_menu_position(),
)
return self._content_cache.get(key, get_content)
def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Handle mouse events.
(When the fragment list contained mouse handlers and the user clicked on
on any of these, the matching handler is called. This handler can still
return `NotImplemented` in case we want the
:class:`~prompt_toolkit.layout.Window` to handle this particular
event.)
"""
if self._fragments:
# Read the generator.
fragments_for_line = list(split_lines(self._fragments))
try:
fragments = fragments_for_line[mouse_event.position.y]
except IndexError:
return NotImplemented
else:
# Find position in the fragment list.
xpos = mouse_event.position.x
# Find mouse handler for this character.
count = 0
for item in fragments:
count += len(item[1])
if count > xpos:
if len(item) >= 3:
# Handler found. Call it.
# (Handler can return NotImplemented, so return
# that result.)
handler = item[2] # type: ignore
return handler(mouse_event)
else:
break
# Otherwise, don't handle here.
return NotImplemented
def is_modal(self) -> bool:
return self.modal
def get_key_bindings(self) -> KeyBindingsBase | None:
return self.key_bindings
D = Dimension
class Layout:
"""
The layout for a prompt_toolkit
:class:`~prompt_toolkit.application.Application`.
This also keeps track of which user control is focused.
:param container: The "root" container for the layout.
:param focused_element: element to be focused initially. (Can be anything
the `focus` function accepts.)
"""
def __init__(
self,
container: AnyContainer,
focused_element: FocusableElement | None = None,
) -> None:
self.container = to_container(container)
self._stack: list[Window] = []
# Map search BufferControl back to the original BufferControl.
# This is used to keep track of when exactly we are searching, and for
# applying the search.
# When a link exists in this dictionary, that means the search is
# currently active.
# Map: search_buffer_control -> original buffer control.
self.search_links: dict[SearchBufferControl, BufferControl] = {}
# Mapping that maps the children in the layout to their parent.
# This relationship is calculated dynamically, each time when the UI
# is rendered. (UI elements have only references to their children.)
self._child_to_parent: dict[Container, Container] = {}
if focused_element is None:
try:
self._stack.append(next(self.find_all_windows()))
except StopIteration as e:
raise InvalidLayoutError(
"Invalid layout. The layout does not contain any Window object."
) from e
else:
self.focus(focused_element)
# List of visible windows.
self.visible_windows: list[Window] = [] # List of `Window` objects.
def __repr__(self) -> str:
return f"Layout({self.container!r}, current_window={self.current_window!r})"
def find_all_windows(self) -> Generator[Window, None, None]:
"""
Find all the :class:`.UIControl` objects in this layout.
"""
for item in self.walk():
if isinstance(item, Window):
yield item
def find_all_controls(self) -> Iterable[UIControl]:
for container in self.find_all_windows():
yield container.content
def focus(self, value: FocusableElement) -> None:
"""
Focus the given UI element.
`value` can be either:
- a :class:`.UIControl`
- a :class:`.Buffer` instance or the name of a :class:`.Buffer`
- a :class:`.Window`
- Any container object. In this case we will focus the :class:`.Window`
from this container that was focused most recent, or the very first
focusable :class:`.Window` of the container.
"""
# BufferControl by buffer name.
if isinstance(value, str):
for control in self.find_all_controls():
if isinstance(control, BufferControl) and control.buffer.name == value:
self.focus(control)
return
raise ValueError(f"Couldn't find Buffer in the current layout: {value!r}.")
# BufferControl by buffer object.
elif isinstance(value, Buffer):
for control in self.find_all_controls():
if isinstance(control, BufferControl) and control.buffer == value:
self.focus(control)
return
raise ValueError(f"Couldn't find Buffer in the current layout: {value!r}.")
# Focus UIControl.
elif isinstance(value, UIControl):
if value not in self.find_all_controls():
raise ValueError(
"Invalid value. Container does not appear in the layout."
)
if not value.is_focusable():
raise ValueError("Invalid value. UIControl is not focusable.")
self.current_control = value
# Otherwise, expecting any Container object.
else:
value = to_container(value)
if isinstance(value, Window):
# This is a `Window`: focus that.
if value not in self.find_all_windows():
raise ValueError(
"Invalid value. Window does not appear in the layout: %r"
% (value,)
)
self.current_window = value
else:
# Focus a window in this container.
# If we have many windows as part of this container, and some
# of them have been focused before, take the last focused
# item. (This is very useful when the UI is composed of more
# complex sub components.)
windows = []
for c in walk(value, skip_hidden=True):
if isinstance(c, Window) and c.content.is_focusable():
windows.append(c)
# Take the first one that was focused before.
for w in reversed(self._stack):
if w in windows:
self.current_window = w
return
# None was focused before: take the very first focusable window.
if windows:
self.current_window = windows[0]
return
raise ValueError(
f"Invalid value. Container cannot be focused: {value!r}"
)
def has_focus(self, value: FocusableElement) -> bool:
"""
Check whether the given control has the focus.
:param value: :class:`.UIControl` or :class:`.Window` instance.
"""
if isinstance(value, str):
if self.current_buffer is None:
return False
return self.current_buffer.name == value
if isinstance(value, Buffer):
return self.current_buffer == value
if isinstance(value, UIControl):
return self.current_control == value
else:
value = to_container(value)
if isinstance(value, Window):
return self.current_window == value
else:
# Check whether this "container" is focused. This is true if
# one of the elements inside is focused.
for element in walk(value):
if element == self.current_window:
return True
return False
def current_control(self) -> UIControl:
"""
Get the :class:`.UIControl` to currently has the focus.
"""
return self._stack[-1].content
def current_control(self, control: UIControl) -> None:
"""
Set the :class:`.UIControl` to receive the focus.
"""
for window in self.find_all_windows():
if window.content == control:
self.current_window = window
return
raise ValueError("Control not found in the user interface.")
def current_window(self) -> Window:
"Return the :class:`.Window` object that is currently focused."
return self._stack[-1]
def current_window(self, value: Window) -> None:
"Set the :class:`.Window` object to be currently focused."
self._stack.append(value)
def is_searching(self) -> bool:
"True if we are searching right now."
return self.current_control in self.search_links
def search_target_buffer_control(self) -> BufferControl | None:
"""
Return the :class:`.BufferControl` in which we are searching or `None`.
"""
# Not every `UIControl` is a `BufferControl`. This only applies to
# `BufferControl`.
control = self.current_control
if isinstance(control, SearchBufferControl):
return self.search_links.get(control)
else:
return None
def get_focusable_windows(self) -> Iterable[Window]:
"""
Return all the :class:`.Window` objects which are focusable (in the
'modal' area).
"""
for w in self.walk_through_modal_area():
if isinstance(w, Window) and w.content.is_focusable():
yield w
def get_visible_focusable_windows(self) -> list[Window]:
"""
Return a list of :class:`.Window` objects that are focusable.
"""
# focusable windows are windows that are visible, but also part of the
# modal container. Make sure to keep the ordering.
visible_windows = self.visible_windows
return [w for w in self.get_focusable_windows() if w in visible_windows]
def current_buffer(self) -> Buffer | None:
"""
The currently focused :class:`~.Buffer` or `None`.
"""
ui_control = self.current_control
if isinstance(ui_control, BufferControl):
return ui_control.buffer
return None
def get_buffer_by_name(self, buffer_name: str) -> Buffer | None:
"""
Look in the layout for a buffer with the given name.
Return `None` when nothing was found.
"""
for w in self.walk():
if isinstance(w, Window) and isinstance(w.content, BufferControl):
if w.content.buffer.name == buffer_name:
return w.content.buffer
return None
def buffer_has_focus(self) -> bool:
"""
Return `True` if the currently focused control is a
:class:`.BufferControl`. (For instance, used to determine whether the
default key bindings should be active or not.)
"""
ui_control = self.current_control
return isinstance(ui_control, BufferControl)
def previous_control(self) -> UIControl:
"""
Get the :class:`.UIControl` to previously had the focus.
"""
try:
return self._stack[-2].content
except IndexError:
return self._stack[-1].content
def focus_last(self) -> None:
"""
Give the focus to the last focused control.
"""
if len(self._stack) > 1:
self._stack = self._stack[:-1]
def focus_next(self) -> None:
"""
Focus the next visible/focusable Window.
"""
windows = self.get_visible_focusable_windows()
if len(windows) > 0:
try:
index = windows.index(self.current_window)
except ValueError:
index = 0
else:
index = (index + 1) % len(windows)
self.focus(windows[index])
def focus_previous(self) -> None:
"""
Focus the previous visible/focusable Window.
"""
windows = self.get_visible_focusable_windows()
if len(windows) > 0:
try:
index = windows.index(self.current_window)
except ValueError:
index = 0
else:
index = (index - 1) % len(windows)
self.focus(windows[index])
def walk(self) -> Iterable[Container]:
"""
Walk through all the layout nodes (and their children) and yield them.
"""
yield from walk(self.container)
def walk_through_modal_area(self) -> Iterable[Container]:
"""
Walk through all the containers which are in the current 'modal' part
of the layout.
"""
# Go up in the tree, and find the root. (it will be a part of the
# layout, if the focus is in a modal part.)
root: Container = self.current_window
while not root.is_modal() and root in self._child_to_parent:
root = self._child_to_parent[root]
yield from walk(root)
def update_parents_relations(self) -> None:
"""
Update child->parent relationships mapping.
"""
parents = {}
def walk(e: Container) -> None:
for c in e.get_children():
parents[c] = e
walk(c)
walk(self.container)
self._child_to_parent = parents
def reset(self) -> None:
# Remove all search links when the UI starts.
# (Important, for instance when control-c is been pressed while
# searching. The prompt cancels, but next `run()` call the search
# links are still there.)
self.search_links.clear()
self.container.reset()
def get_parent(self, container: Container) -> Container | None:
"""
Return the parent container for the given container, or ``None``, if it
wasn't found.
"""
try:
return self._child_to_parent[container]
except KeyError:
return None
The provided code snippet includes necessary dependencies for implementing the `create_dummy_layout` function. Write a Python function `def create_dummy_layout() -> Layout` to solve the following problem:
Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits.
Here is the function:
def create_dummy_layout() -> Layout:
"""
Create a dummy layout for use in an 'Application' that doesn't have a
layout specified. When ENTER is pressed, the application quits.
"""
kb = KeyBindings()
@kb.add("enter")
def enter(event: E) -> None:
event.app.exit()
control = FormattedTextControl(
HTML("No layout specified. Press <reverse>ENTER</reverse> to quit."),
key_bindings=kb,
)
window = Window(content=control, height=D(min=1))
return Layout(container=window, focused_element=window) | Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. |
172,169 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters import (
FilterOrBool,
emacs_insert_mode,
to_filter,
vi_insert_mode,
)
from prompt_toolkit.formatted_text import (
AnyFormattedText,
StyleAndTextTuples,
to_formatted_text,
)
from prompt_toolkit.formatted_text.utils import (
fragment_list_to_text,
fragment_list_width,
)
from prompt_toolkit.key_binding import KeyBindingsBase
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
from prompt_toolkit.utils import get_cwidth, take_using_weights, to_int, to_str
from .controls import (
DummyControl,
FormattedTextControl,
GetLinePrefixCallable,
UIContent,
UIControl,
)
from .dimension import (
AnyDimension,
Dimension,
max_layout_dimensions,
sum_layout_dimensions,
to_dimension,
)
from .margins import Margin
from .mouse_handlers import MouseHandlers
from .screen import _CHAR_CACHE, Screen, WritePosition
from .utils import explode_text_fragments
class Window(Container):
"""
Container that holds a control.
:param content: :class:`.UIControl` instance.
:param width: :class:`.Dimension` instance or callable.
:param height: :class:`.Dimension` instance or callable.
:param z_index: When specified, this can be used to bring element in front
of floating elements.
:param dont_extend_width: When `True`, don't take up more width then the
preferred width reported by the control.
:param dont_extend_height: When `True`, don't take up more width then the
preferred height reported by the control.
:param ignore_content_width: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` width when calculating the dimensions.
:param ignore_content_height: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` height when calculating the dimensions.
:param left_margins: A list of :class:`.Margin` instance to be displayed on
the left. For instance: :class:`~prompt_toolkit.layout.NumberedMargin`
can be one of them in order to show line numbers.
:param right_margins: Like `left_margins`, but on the other side.
:param scroll_offsets: :class:`.ScrollOffsets` instance, representing the
preferred amount of lines/columns to be always visible before/after the
cursor. When both top and bottom are a very high number, the cursor
will be centered vertically most of the time.
:param allow_scroll_beyond_bottom: A `bool` or
:class:`.Filter` instance. When True, allow scrolling so far, that the
top part of the content is not visible anymore, while there is still
empty space available at the bottom of the window. In the Vi editor for
instance, this is possible. You will see tildes while the top part of
the body is hidden.
:param wrap_lines: A `bool` or :class:`.Filter` instance. When True, don't
scroll horizontally, but wrap lines instead.
:param get_vertical_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
(When this is `None`, the scroll is only determined by the last and
current cursor position.)
:param get_horizontal_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
:param always_hide_cursor: A `bool` or
:class:`.Filter` instance. When True, never display the cursor, even
when the user control specifies a cursor position.
:param cursorline: A `bool` or :class:`.Filter` instance. When True,
display a cursorline.
:param cursorcolumn: A `bool` or :class:`.Filter` instance. When True,
display a cursorcolumn.
:param colorcolumns: A list of :class:`.ColorColumn` instances that
describe the columns to be highlighted, or a callable that returns such
a list.
:param align: :class:`.WindowAlign` value or callable that returns an
:class:`.WindowAlign` value. alignment of content.
:param style: A style string. Style to be applied to all the cells in this
window. (This can be a callable that returns a string.)
:param char: (string) Character to be used for filling the background. This
can also be a callable that returns a character.
:param get_line_prefix: None or a callable that returns formatted text to
be inserted before a line. It takes a line number (int) and a
wrap_count and returns formatted text. This can be used for
implementation of line continuations, things like Vim "breakindent" and
so on.
"""
def __init__(
self,
content: UIControl | None = None,
width: AnyDimension = None,
height: AnyDimension = None,
z_index: int | None = None,
dont_extend_width: FilterOrBool = False,
dont_extend_height: FilterOrBool = False,
ignore_content_width: FilterOrBool = False,
ignore_content_height: FilterOrBool = False,
left_margins: Sequence[Margin] | None = None,
right_margins: Sequence[Margin] | None = None,
scroll_offsets: ScrollOffsets | None = None,
allow_scroll_beyond_bottom: FilterOrBool = False,
wrap_lines: FilterOrBool = False,
get_vertical_scroll: Callable[[Window], int] | None = None,
get_horizontal_scroll: Callable[[Window], int] | None = None,
always_hide_cursor: FilterOrBool = False,
cursorline: FilterOrBool = False,
cursorcolumn: FilterOrBool = False,
colorcolumns: (
None | list[ColorColumn] | Callable[[], list[ColorColumn]]
) = None,
align: WindowAlign | Callable[[], WindowAlign] = WindowAlign.LEFT,
style: str | Callable[[], str] = "",
char: None | str | Callable[[], str] = None,
get_line_prefix: GetLinePrefixCallable | None = None,
) -> None:
self.allow_scroll_beyond_bottom = to_filter(allow_scroll_beyond_bottom)
self.always_hide_cursor = to_filter(always_hide_cursor)
self.wrap_lines = to_filter(wrap_lines)
self.cursorline = to_filter(cursorline)
self.cursorcolumn = to_filter(cursorcolumn)
self.content = content or DummyControl()
self.dont_extend_width = to_filter(dont_extend_width)
self.dont_extend_height = to_filter(dont_extend_height)
self.ignore_content_width = to_filter(ignore_content_width)
self.ignore_content_height = to_filter(ignore_content_height)
self.left_margins = left_margins or []
self.right_margins = right_margins or []
self.scroll_offsets = scroll_offsets or ScrollOffsets()
self.get_vertical_scroll = get_vertical_scroll
self.get_horizontal_scroll = get_horizontal_scroll
self.colorcolumns = colorcolumns or []
self.align = align
self.style = style
self.char = char
self.get_line_prefix = get_line_prefix
self.width = width
self.height = height
self.z_index = z_index
# Cache for the screens generated by the margin.
self._ui_content_cache: SimpleCache[
tuple[int, int, int], UIContent
] = SimpleCache(maxsize=8)
self._margin_width_cache: SimpleCache[tuple[Margin, int], int] = SimpleCache(
maxsize=1
)
self.reset()
def __repr__(self) -> str:
return "Window(content=%r)" % self.content
def reset(self) -> None:
self.content.reset()
#: Scrolling position of the main content.
self.vertical_scroll = 0
self.horizontal_scroll = 0
# Vertical scroll 2: this is the vertical offset that a line is
# scrolled if a single line (the one that contains the cursor) consumes
# all of the vertical space.
self.vertical_scroll_2 = 0
#: Keep render information (mappings between buffer input and render
#: output.)
self.render_info: WindowRenderInfo | None = None
def _get_margin_width(self, margin: Margin) -> int:
"""
Return the width for this margin.
(Calculate only once per render time.)
"""
# Margin.get_width, needs to have a UIContent instance.
def get_ui_content() -> UIContent:
return self._get_ui_content(width=0, height=0)
def get_width() -> int:
return margin.get_width(get_ui_content)
key = (margin, get_app().render_counter)
return self._margin_width_cache.get(key, get_width)
def _get_total_margin_width(self) -> int:
"""
Calculate and return the width of the margin (left + right).
"""
return sum(self._get_margin_width(m) for m in self.left_margins) + sum(
self._get_margin_width(m) for m in self.right_margins
)
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Calculate the preferred width for this window.
"""
def preferred_content_width() -> int | None:
"""Content width: is only calculated if no exact width for the
window was given."""
if self.ignore_content_width():
return None
# Calculate the width of the margin.
total_margin_width = self._get_total_margin_width()
# Window of the content. (Can be `None`.)
preferred_width = self.content.preferred_width(
max_available_width - total_margin_width
)
if preferred_width is not None:
# Include width of the margins.
preferred_width += total_margin_width
return preferred_width
# Merge.
return self._merge_dimensions(
dimension=to_dimension(self.width),
get_preferred=preferred_content_width,
dont_extend=self.dont_extend_width(),
)
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Calculate the preferred height for this window.
"""
def preferred_content_height() -> int | None:
"""Content height: is only calculated if no exact height for the
window was given."""
if self.ignore_content_height():
return None
total_margin_width = self._get_total_margin_width()
wrap_lines = self.wrap_lines()
return self.content.preferred_height(
width - total_margin_width,
max_available_height,
wrap_lines,
self.get_line_prefix,
)
return self._merge_dimensions(
dimension=to_dimension(self.height),
get_preferred=preferred_content_height,
dont_extend=self.dont_extend_height(),
)
def _merge_dimensions(
dimension: Dimension | None,
get_preferred: Callable[[], int | None],
dont_extend: bool = False,
) -> Dimension:
"""
Take the Dimension from this `Window` class and the received preferred
size from the `UIControl` and return a `Dimension` to report to the
parent container.
"""
dimension = dimension or Dimension()
# When a preferred dimension was explicitly given to the Window,
# ignore the UIControl.
preferred: int | None
if dimension.preferred_specified:
preferred = dimension.preferred
else:
# Otherwise, calculate the preferred dimension from the UI control
# content.
preferred = get_preferred()
# When a 'preferred' dimension is given by the UIControl, make sure
# that it stays within the bounds of the Window.
if preferred is not None:
if dimension.max_specified:
preferred = min(preferred, dimension.max)
if dimension.min_specified:
preferred = max(preferred, dimension.min)
# When a `dont_extend` flag has been given, use the preferred dimension
# also as the max dimension.
max_: int | None
min_: int | None
if dont_extend and preferred is not None:
max_ = min(dimension.max, preferred)
else:
max_ = dimension.max if dimension.max_specified else None
min_ = dimension.min if dimension.min_specified else None
return Dimension(
min=min_, max=max_, preferred=preferred, weight=dimension.weight
)
def _get_ui_content(self, width: int, height: int) -> UIContent:
"""
Create a `UIContent` instance.
"""
def get_content() -> UIContent:
return self.content.create_content(width=width, height=height)
key = (get_app().render_counter, width, height)
return self._ui_content_cache.get(key, get_content)
def _get_digraph_char(self) -> str | None:
"Return `False`, or the Digraph symbol to be used."
app = get_app()
if app.quoted_insert:
return "^"
if app.vi_state.waiting_for_digraph:
if app.vi_state.digraph_symbol1:
return app.vi_state.digraph_symbol1
return "?"
return None
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: int | None,
) -> None:
"""
Write window to screen. This renders the user control, the margins and
copies everything over to the absolute position at the given screen.
"""
# If dont_extend_width/height was given. Then reduce width/height in
# WritePosition if the parent wanted us to paint in a bigger area.
# (This happens if this window is bundled with another window in a
# HSplit/VSplit, but with different size requirements.)
write_position = WritePosition(
xpos=write_position.xpos,
ypos=write_position.ypos,
width=write_position.width,
height=write_position.height,
)
if self.dont_extend_width():
write_position.width = min(
write_position.width,
self.preferred_width(write_position.width).preferred,
)
if self.dont_extend_height():
write_position.height = min(
write_position.height,
self.preferred_height(
write_position.width, write_position.height
).preferred,
)
# Draw
z_index = z_index if self.z_index is None else self.z_index
draw_func = partial(
self._write_to_screen_at_index,
screen,
mouse_handlers,
write_position,
parent_style,
erase_bg,
)
if z_index is None or z_index <= 0:
# When no z_index is given, draw right away.
draw_func()
else:
# Otherwise, postpone.
screen.draw_with_z_index(z_index=z_index, draw_func=draw_func)
def _write_to_screen_at_index(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
) -> None:
# Don't bother writing invisible windows.
# (We save some time, but also avoid applying last-line styling.)
if write_position.height <= 0 or write_position.width <= 0:
return
# Calculate margin sizes.
left_margin_widths = [self._get_margin_width(m) for m in self.left_margins]
right_margin_widths = [self._get_margin_width(m) for m in self.right_margins]
total_margin_width = sum(left_margin_widths + right_margin_widths)
# Render UserControl.
ui_content = self.content.create_content(
write_position.width - total_margin_width, write_position.height
)
assert isinstance(ui_content, UIContent)
# Scroll content.
wrap_lines = self.wrap_lines()
self._scroll(
ui_content, write_position.width - total_margin_width, write_position.height
)
# Erase background and fill with `char`.
self._fill_bg(screen, write_position, erase_bg)
# Resolve `align` attribute.
align = self.align() if callable(self.align) else self.align
# Write body
visible_line_to_row_col, rowcol_to_yx = self._copy_body(
ui_content,
screen,
write_position,
sum(left_margin_widths),
write_position.width - total_margin_width,
self.vertical_scroll,
self.horizontal_scroll,
wrap_lines=wrap_lines,
highlight_lines=True,
vertical_scroll_2=self.vertical_scroll_2,
always_hide_cursor=self.always_hide_cursor(),
has_focus=get_app().layout.current_control == self.content,
align=align,
get_line_prefix=self.get_line_prefix,
)
# Remember render info. (Set before generating the margins. They need this.)
x_offset = write_position.xpos + sum(left_margin_widths)
y_offset = write_position.ypos
render_info = WindowRenderInfo(
window=self,
ui_content=ui_content,
horizontal_scroll=self.horizontal_scroll,
vertical_scroll=self.vertical_scroll,
window_width=write_position.width - total_margin_width,
window_height=write_position.height,
configured_scroll_offsets=self.scroll_offsets,
visible_line_to_row_col=visible_line_to_row_col,
rowcol_to_yx=rowcol_to_yx,
x_offset=x_offset,
y_offset=y_offset,
wrap_lines=wrap_lines,
)
self.render_info = render_info
# Set mouse handlers.
def mouse_handler(mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Wrapper around the mouse_handler of the `UIControl` that turns
screen coordinates into line coordinates.
Returns `NotImplemented` if no UI invalidation should be done.
"""
# Don't handle mouse events outside of the current modal part of
# the UI.
if self not in get_app().layout.walk_through_modal_area():
return NotImplemented
# Find row/col position first.
yx_to_rowcol = {v: k for k, v in rowcol_to_yx.items()}
y = mouse_event.position.y
x = mouse_event.position.x
# If clicked below the content area, look for a position in the
# last line instead.
max_y = write_position.ypos + len(visible_line_to_row_col) - 1
y = min(max_y, y)
result: NotImplementedOrNone
while x >= 0:
try:
row, col = yx_to_rowcol[y, x]
except KeyError:
# Try again. (When clicking on the right side of double
# width characters, or on the right side of the input.)
x -= 1
else:
# Found position, call handler of UIControl.
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=col, y=row),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
break
else:
# nobreak.
# (No x/y coordinate found for the content. This happens in
# case of a DummyControl, that does not have any content.
# Report (0,0) instead.)
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=0, y=0),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
# If it returns NotImplemented, handle it here.
if result == NotImplemented:
result = self._mouse_handler(mouse_event)
return result
mouse_handlers.set_mouse_handler_for_range(
x_min=write_position.xpos + sum(left_margin_widths),
x_max=write_position.xpos + write_position.width - total_margin_width,
y_min=write_position.ypos,
y_max=write_position.ypos + write_position.height,
handler=mouse_handler,
)
# Render and copy margins.
move_x = 0
def render_margin(m: Margin, width: int) -> UIContent:
"Render margin. Return `Screen`."
# Retrieve margin fragments.
fragments = m.create_margin(render_info, width, write_position.height)
# Turn it into a UIContent object.
# already rendered those fragments using this size.)
return FormattedTextControl(fragments).create_content(
width + 1, write_position.height
)
for m, width in zip(self.left_margins, left_margin_widths):
if width > 0: # (ConditionalMargin returns a zero width. -- Don't render.)
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
move_x = write_position.width - sum(right_margin_widths)
for m, width in zip(self.right_margins, right_margin_widths):
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
# Apply 'self.style'
self._apply_style(screen, write_position, parent_style)
# Tell the screen that this user control has been painted at this
# position.
screen.visible_windows_to_write_positions[self] = write_position
def _copy_body(
self,
ui_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
vertical_scroll: int = 0,
horizontal_scroll: int = 0,
wrap_lines: bool = False,
highlight_lines: bool = False,
vertical_scroll_2: int = 0,
always_hide_cursor: bool = False,
has_focus: bool = False,
align: WindowAlign = WindowAlign.LEFT,
get_line_prefix: Callable[[int, int], AnyFormattedText] | None = None,
) -> tuple[dict[int, tuple[int, int]], dict[tuple[int, int], tuple[int, int]]]:
"""
Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple.
:param get_line_prefix: None or a callable that takes a line number
(int) and a wrap_count (int) and returns formatted text.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
line_count = ui_content.line_count
new_buffer = new_screen.data_buffer
empty_char = _CHAR_CACHE["", ""]
# Map visible line number to (row, col) of input.
# 'col' will always be zero if line wrapping is off.
visible_line_to_row_col: dict[int, tuple[int, int]] = {}
# Maps (row, col) from the input to (y, x) screen coordinates.
rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
def copy_line(
line: StyleAndTextTuples,
lineno: int,
x: int,
y: int,
is_input: bool = False,
) -> tuple[int, int]:
"""
Copy over a single line to the output screen. This can wrap over
multiple lines in the output. It will call the prefix (prompt)
function before every line.
"""
if is_input:
current_rowcol_to_yx = rowcol_to_yx
else:
current_rowcol_to_yx = {} # Throwaway dictionary.
# Draw line prefix.
if is_input and get_line_prefix:
prompt = to_formatted_text(get_line_prefix(lineno, 0))
x, y = copy_line(prompt, lineno, x, y, is_input=False)
# Scroll horizontally.
skipped = 0 # Characters skipped because of horizontal scrolling.
if horizontal_scroll and is_input:
h_scroll = horizontal_scroll
line = explode_text_fragments(line)
while h_scroll > 0 and line:
h_scroll -= get_cwidth(line[0][1])
skipped += 1
del line[:1] # Remove first character.
x -= h_scroll # When scrolling over double width character,
# this can end up being negative.
# Align this line. (Note that this doesn't work well when we use
# get_line_prefix and that function returns variable width prefixes.)
if align == WindowAlign.CENTER:
line_width = fragment_list_width(line)
if line_width < width:
x += (width - line_width) // 2
elif align == WindowAlign.RIGHT:
line_width = fragment_list_width(line)
if line_width < width:
x += width - line_width
col = 0
wrap_count = 0
for style, text, *_ in line:
new_buffer_row = new_buffer[y + ypos]
# Remember raw VT escape sequences. (E.g. FinalTerm's
# escape sequences.)
if "[ZeroWidthEscape]" in style:
new_screen.zero_width_escapes[y + ypos][x + xpos] += text
continue
for c in text:
char = _CHAR_CACHE[c, style]
char_width = char.width
# Wrap when the line width is exceeded.
if wrap_lines and x + char_width > width:
visible_line_to_row_col[y + 1] = (
lineno,
visible_line_to_row_col[y][1] + x,
)
y += 1
wrap_count += 1
x = 0
# Insert line prefix (continuation prompt).
if is_input and get_line_prefix:
prompt = to_formatted_text(
get_line_prefix(lineno, wrap_count)
)
x, y = copy_line(prompt, lineno, x, y, is_input=False)
new_buffer_row = new_buffer[y + ypos]
if y >= write_position.height:
return x, y # Break out of all for loops.
# Set character in screen and shift 'x'.
if x >= 0 and y >= 0 and x < width:
new_buffer_row[x + xpos] = char
# When we print a multi width character, make sure
# to erase the neighbours positions in the screen.
# (The empty string if different from everything,
# so next redraw this cell will repaint anyway.)
if char_width > 1:
for i in range(1, char_width):
new_buffer_row[x + xpos + i] = empty_char
# If this is a zero width characters, then it's
# probably part of a decomposed unicode character.
# See: https://en.wikipedia.org/wiki/Unicode_equivalence
# Merge it in the previous cell.
elif char_width == 0:
# Handle all character widths. If the previous
# character is a multiwidth character, then
# merge it two positions back.
for pw in [2, 1]: # Previous character width.
if (
x - pw >= 0
and new_buffer_row[x + xpos - pw].width == pw
):
prev_char = new_buffer_row[x + xpos - pw]
char2 = _CHAR_CACHE[
prev_char.char + c, prev_char.style
]
new_buffer_row[x + xpos - pw] = char2
# Keep track of write position for each character.
current_rowcol_to_yx[lineno, col + skipped] = (
y + ypos,
x + xpos,
)
col += 1
x += char_width
return x, y
# Copy content.
def copy() -> int:
y = -vertical_scroll_2
lineno = vertical_scroll
while y < write_position.height and lineno < line_count:
# Take the next line and copy it in the real screen.
line = ui_content.get_line(lineno)
visible_line_to_row_col[y] = (lineno, horizontal_scroll)
# Copy margin and actual line.
x = 0
x, y = copy_line(line, lineno, x, y, is_input=True)
lineno += 1
y += 1
return y
copy()
def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
"Translate row/col from UIContent to real Screen coordinates."
try:
y, x = rowcol_to_yx[row, col]
except KeyError:
# Normally this should never happen. (It is a bug, if it happens.)
# But to be sure, return (0, 0)
return Point(x=0, y=0)
# raise ValueError(
# 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
# 'horizontal_scroll=%r, height=%r' %
# (row, col, vertical_scroll, horizontal_scroll, write_position.height))
else:
return Point(x=x, y=y)
# Set cursor and menu positions.
if ui_content.cursor_position:
screen_cursor_position = cursor_pos_to_screen_pos(
ui_content.cursor_position.y, ui_content.cursor_position.x
)
if has_focus:
new_screen.set_cursor_position(self, screen_cursor_position)
if always_hide_cursor:
new_screen.show_cursor = False
else:
new_screen.show_cursor = ui_content.show_cursor
self._highlight_digraph(new_screen)
if highlight_lines:
self._highlight_cursorlines(
new_screen,
screen_cursor_position,
xpos,
ypos,
width,
write_position.height,
)
# Draw input characters from the input processor queue.
if has_focus and ui_content.cursor_position:
self._show_key_processor_key_buffer(new_screen)
# Set menu position.
if ui_content.menu_position:
new_screen.set_menu_position(
self,
cursor_pos_to_screen_pos(
ui_content.menu_position.y, ui_content.menu_position.x
),
)
# Update output screen height.
new_screen.height = max(new_screen.height, ypos + write_position.height)
return visible_line_to_row_col, rowcol_to_yx
def _fill_bg(
self, screen: Screen, write_position: WritePosition, erase_bg: bool
) -> None:
"""
Erase/fill the background.
(Useful for floats and when a `char` has been given.)
"""
char: str | None
if callable(self.char):
char = self.char()
else:
char = self.char
if erase_bg or char:
wp = write_position
char_obj = _CHAR_CACHE[char or " ", ""]
for y in range(wp.ypos, wp.ypos + wp.height):
row = screen.data_buffer[y]
for x in range(wp.xpos, wp.xpos + wp.width):
row[x] = char_obj
def _apply_style(
self, new_screen: Screen, write_position: WritePosition, parent_style: str
) -> None:
# Apply `self.style`.
style = parent_style + " " + to_str(self.style)
new_screen.fill_area(write_position, style=style, after=False)
# Apply the 'last-line' class to the last line of each Window. This can
# be used to apply an 'underline' to the user control.
wp = WritePosition(
write_position.xpos,
write_position.ypos + write_position.height - 1,
write_position.width,
1,
)
new_screen.fill_area(wp, "class:last-line", after=True)
def _highlight_digraph(self, new_screen: Screen) -> None:
"""
When we are in Vi digraph mode, put a question mark underneath the
cursor.
"""
digraph_char = self._get_digraph_char()
if digraph_char:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
digraph_char, "class:digraph"
]
def _show_key_processor_key_buffer(self, new_screen: Screen) -> None:
"""
When the user is typing a key binding that consists of several keys,
display the last pressed key if the user is in insert mode and the key
is meaningful to be displayed.
E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
first 'j' needs to be displayed in order to get some feedback.
"""
app = get_app()
key_buffer = app.key_processor.key_buffer
if key_buffer and _in_insert_mode() and not app.is_done:
# The textual data for the given key. (Can be a VT100 escape
# sequence.)
data = key_buffer[-1].data
# Display only if this is a 1 cell width character.
if get_cwidth(data) == 1:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
data, "class:partial-key-binding"
]
def _highlight_cursorlines(
self, new_screen: Screen, cpos: Point, x: int, y: int, width: int, height: int
) -> None:
"""
Highlight cursor row/column.
"""
cursor_line_style = " class:cursor-line "
cursor_column_style = " class:cursor-column "
data_buffer = new_screen.data_buffer
# Highlight cursor line.
if self.cursorline():
row = data_buffer[cpos.y]
for x in range(x, x + width):
original_char = row[x]
row[x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_line_style
]
# Highlight cursor column.
if self.cursorcolumn():
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[cpos.x]
row[cpos.x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_column_style
]
# Highlight color columns
colorcolumns = self.colorcolumns
if callable(colorcolumns):
colorcolumns = colorcolumns()
for cc in colorcolumns:
assert isinstance(cc, ColorColumn)
column = cc.position
if column < x + width: # Only draw when visible.
color_column_style = " " + cc.style
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[column + x]
row[column + x] = _CHAR_CACHE[
original_char.char, original_char.style + color_column_style
]
def _copy_margin(
self,
margin_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
) -> None:
"""
Copy characters from the margin screen to the real screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
self._copy_body(margin_content, new_screen, margin_write_position, 0, width)
def _scroll(self, ui_content: UIContent, width: int, height: int) -> None:
"""
Scroll body. Ensure that the cursor is visible.
"""
if self.wrap_lines():
func = self._scroll_when_linewrapping
else:
func = self._scroll_without_linewrapping
func(ui_content, width, height)
def _scroll_when_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
scroll_offsets_bottom = self.scroll_offsets.bottom
scroll_offsets_top = self.scroll_offsets.top
# We don't have horizontal scrolling.
self.horizontal_scroll = 0
def get_line_height(lineno: int) -> int:
return ui_content.get_height_for_line(lineno, width, self.get_line_prefix)
# When there is no space, reset `vertical_scroll_2` to zero and abort.
# This can happen if the margin is bigger than the window width.
# Otherwise the text height will become "infinite" (a big number) and
# the copy_line will spend a huge amount of iterations trying to render
# nothing.
if width <= 0:
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = 0
return
# If the current line consumes more than the whole window height,
# then we have to scroll vertically inside this line. (We don't take
# the scroll offsets into account for this.)
# Also, ignore the scroll offsets in this case. Just set the vertical
# scroll to this line.
line_height = get_line_height(ui_content.cursor_position.y)
if line_height > height - scroll_offsets_top:
# Calculate the height of the text before the cursor (including
# line prefixes).
text_before_height = ui_content.get_height_for_line(
ui_content.cursor_position.y,
width,
self.get_line_prefix,
slice_stop=ui_content.cursor_position.x,
)
# Adjust scroll offset.
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = min(
text_before_height - 1, # Keep the cursor visible.
line_height
- height, # Avoid blank lines at the bottom when scolling up again.
self.vertical_scroll_2,
)
self.vertical_scroll_2 = max(
0, text_before_height - height, self.vertical_scroll_2
)
return
else:
self.vertical_scroll_2 = 0
# Current line doesn't consume the whole height. Take scroll offsets into account.
def get_min_vertical_scroll() -> int:
# Make sure that the cursor line is not below the bottom.
# (Calculate how many lines can be shown between the cursor and the .)
used_height = 0
prev_lineno = ui_content.cursor_position.y
for lineno in range(ui_content.cursor_position.y, -1, -1):
used_height += get_line_height(lineno)
if used_height > height - scroll_offsets_bottom:
return prev_lineno
else:
prev_lineno = lineno
return 0
def get_max_vertical_scroll() -> int:
# Make sure that the cursor line is not above the top.
prev_lineno = ui_content.cursor_position.y
used_height = 0
for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > scroll_offsets_top:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
def get_topmost_visible() -> int:
"""
Calculate the upper most line that can be visible, while the bottom
is still visible. We should not allow scroll more than this if
`allow_scroll_beyond_bottom` is false.
"""
prev_lineno = ui_content.line_count - 1
used_height = 0
for lineno in range(ui_content.line_count - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > height:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
# Scroll vertically. (Make sure that the whole line which contains the
# cursor is visible.
topmost_visible = get_topmost_visible()
# Note: the `min(topmost_visible, ...)` is to make sure that we
# don't require scrolling up because of the bottom scroll offset,
# when we are at the end of the document.
self.vertical_scroll = max(
self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll())
)
self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
# Disallow scrolling beyond bottom?
if not self.allow_scroll_beyond_bottom():
self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
def _scroll_without_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
cursor_position = ui_content.cursor_position or Point(x=0, y=0)
# Without line wrapping, we will never have to scroll vertically inside
# a single line.
self.vertical_scroll_2 = 0
if ui_content.line_count == 0:
self.vertical_scroll = 0
self.horizontal_scroll = 0
return
else:
current_line_text = fragment_list_to_text(
ui_content.get_line(cursor_position.y)
)
def do_scroll(
current_scroll: int,
scroll_offset_start: int,
scroll_offset_end: int,
cursor_pos: int,
window_size: int,
content_size: int,
) -> int:
"Scrolling algorithm. Used for both horizontal and vertical scrolling."
# Calculate the scroll offset to apply.
# This can obviously never be more than have the screen size. Also, when the
# cursor appears at the top or bottom, we don't apply the offset.
scroll_offset_start = int(
min(scroll_offset_start, window_size / 2, cursor_pos)
)
scroll_offset_end = int(
min(scroll_offset_end, window_size / 2, content_size - 1 - cursor_pos)
)
# Prevent negative scroll offsets.
if current_scroll < 0:
current_scroll = 0
# Scroll back if we scrolled to much and there's still space to show more of the document.
if (
not self.allow_scroll_beyond_bottom()
and current_scroll > content_size - window_size
):
current_scroll = max(0, content_size - window_size)
# Scroll up if cursor is before visible part.
if current_scroll > cursor_pos - scroll_offset_start:
current_scroll = max(0, cursor_pos - scroll_offset_start)
# Scroll down if cursor is after visible part.
if current_scroll < (cursor_pos + 1) - window_size + scroll_offset_end:
current_scroll = (cursor_pos + 1) - window_size + scroll_offset_end
return current_scroll
# When a preferred scroll is given, take that first into account.
if self.get_vertical_scroll:
self.vertical_scroll = self.get_vertical_scroll(self)
assert isinstance(self.vertical_scroll, int)
if self.get_horizontal_scroll:
self.horizontal_scroll = self.get_horizontal_scroll(self)
assert isinstance(self.horizontal_scroll, int)
# Update horizontal/vertical scroll to make sure that the cursor
# remains visible.
offsets = self.scroll_offsets
self.vertical_scroll = do_scroll(
current_scroll=self.vertical_scroll,
scroll_offset_start=offsets.top,
scroll_offset_end=offsets.bottom,
cursor_pos=ui_content.cursor_position.y,
window_size=height,
content_size=ui_content.line_count,
)
if self.get_line_prefix:
current_line_prefix_width = fragment_list_width(
to_formatted_text(self.get_line_prefix(ui_content.cursor_position.y, 0))
)
else:
current_line_prefix_width = 0
self.horizontal_scroll = do_scroll(
current_scroll=self.horizontal_scroll,
scroll_offset_start=offsets.left,
scroll_offset_end=offsets.right,
cursor_pos=get_cwidth(current_line_text[: ui_content.cursor_position.x]),
window_size=width - current_line_prefix_width,
# We can only analyse the current line. Calculating the width off
# all the lines is too expensive.
content_size=max(
get_cwidth(current_line_text), self.horizontal_scroll + width
),
)
def _mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Mouse handler. Called when the UI control doesn't handle this
particular event.
Return `NotImplemented` if nothing was done as a consequence of this
key binding (no UI invalidate required in that case).
"""
if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
self._scroll_down()
return None
elif mouse_event.event_type == MouseEventType.SCROLL_UP:
self._scroll_up()
return None
return NotImplemented
def _scroll_down(self) -> None:
"Scroll window down."
info = self.render_info
if info is None:
return
if self.vertical_scroll < info.content_height - info.window_height:
if info.cursor_position.y <= info.configured_scroll_offsets.top:
self.content.move_cursor_down()
self.vertical_scroll += 1
def _scroll_up(self) -> None:
"Scroll window up."
info = self.render_info
if info is None:
return
if info.vertical_scroll > 0:
# TODO: not entirely correct yet in case of line wrapping and long lines.
if (
info.cursor_position.y
>= info.window_height - 1 - info.configured_scroll_offsets.bottom
):
self.content.move_cursor_up()
self.vertical_scroll -= 1
def get_key_bindings(self) -> KeyBindingsBase | None:
return self.content.get_key_bindings()
def get_children(self) -> list[Container]:
return []
class FormattedTextControl(UIControl):
"""
Control that displays formatted text. This can be either plain text, an
:class:`~prompt_toolkit.formatted_text.HTML` object an
:class:`~prompt_toolkit.formatted_text.ANSI` object, a list of ``(style_str,
text)`` tuples or a callable that takes no argument and returns one of
those, depending on how you prefer to do the formatting. See
``prompt_toolkit.layout.formatted_text`` for more information.
(It's mostly optimized for rather small widgets, like toolbars, menus, etc...)
When this UI control has the focus, the cursor will be shown in the upper
left corner of this control by default. There are two ways for specifying
the cursor position:
- Pass a `get_cursor_position` function which returns a `Point` instance
with the current cursor position.
- If the (formatted) text is passed as a list of ``(style, text)`` tuples
and there is one that looks like ``('[SetCursorPosition]', '')``, then
this will specify the cursor position.
Mouse support:
The list of fragments can also contain tuples of three items, looking like:
(style_str, text, handler). When mouse support is enabled and the user
clicks on this fragment, then the given handler is called. That handler
should accept two inputs: (Application, MouseEvent) and it should
either handle the event or return `NotImplemented` in case we want the
containing Window to handle this event.
:param focusable: `bool` or :class:`.Filter`: Tell whether this control is
focusable.
:param text: Text or formatted text to be displayed.
:param style: Style string applied to the content. (If you want to style
the whole :class:`~prompt_toolkit.layout.Window`, pass the style to the
:class:`~prompt_toolkit.layout.Window` instead.)
:param key_bindings: a :class:`.KeyBindings` object.
:param get_cursor_position: A callable that returns the cursor position as
a `Point` instance.
"""
def __init__(
self,
text: AnyFormattedText = "",
style: str = "",
focusable: FilterOrBool = False,
key_bindings: KeyBindingsBase | None = None,
show_cursor: bool = True,
modal: bool = False,
get_cursor_position: Callable[[], Point | None] | None = None,
) -> None:
self.text = text # No type check on 'text'. This is done dynamically.
self.style = style
self.focusable = to_filter(focusable)
# Key bindings.
self.key_bindings = key_bindings
self.show_cursor = show_cursor
self.modal = modal
self.get_cursor_position = get_cursor_position
#: Cache for the content.
self._content_cache: SimpleCache[Hashable, UIContent] = SimpleCache(maxsize=18)
self._fragment_cache: SimpleCache[int, StyleAndTextTuples] = SimpleCache(
maxsize=1
)
# Only cache one fragment list. We don't need the previous item.
# Render info for the mouse support.
self._fragments: StyleAndTextTuples | None = None
def reset(self) -> None:
self._fragments = None
def is_focusable(self) -> bool:
return self.focusable()
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.text!r})"
def _get_formatted_text_cached(self) -> StyleAndTextTuples:
"""
Get fragments, but only retrieve fragments once during one render run.
(This function is called several times during one rendering, because
we also need those for calculating the dimensions.)
"""
return self._fragment_cache.get(
get_app().render_counter, lambda: to_formatted_text(self.text, self.style)
)
def preferred_width(self, max_available_width: int) -> int:
"""
Return the preferred width for this control.
That is the width of the longest line.
"""
text = fragment_list_to_text(self._get_formatted_text_cached())
line_lengths = [get_cwidth(l) for l in text.split("\n")]
return max(line_lengths)
def preferred_height(
self,
width: int,
max_available_height: int,
wrap_lines: bool,
get_line_prefix: GetLinePrefixCallable | None,
) -> int | None:
"""
Return the preferred height for this control.
"""
content = self.create_content(width, None)
if wrap_lines:
height = 0
for i in range(content.line_count):
height += content.get_height_for_line(i, width, get_line_prefix)
if height >= max_available_height:
return max_available_height
return height
else:
return content.line_count
def create_content(self, width: int, height: int | None) -> UIContent:
# Get fragments
fragments_with_mouse_handlers = self._get_formatted_text_cached()
fragment_lines_with_mouse_handlers = list(
split_lines(fragments_with_mouse_handlers)
)
# Strip mouse handlers from fragments.
fragment_lines: list[StyleAndTextTuples] = [
[(item[0], item[1]) for item in line]
for line in fragment_lines_with_mouse_handlers
]
# Keep track of the fragments with mouse handler, for later use in
# `mouse_handler`.
self._fragments = fragments_with_mouse_handlers
# If there is a `[SetCursorPosition]` in the fragment list, set the
# cursor position here.
def get_cursor_position(
fragment: str = "[SetCursorPosition]",
) -> Point | None:
for y, line in enumerate(fragment_lines):
x = 0
for style_str, text, *_ in line:
if fragment in style_str:
return Point(x=x, y=y)
x += len(text)
return None
# If there is a `[SetMenuPosition]`, set the menu over here.
def get_menu_position() -> Point | None:
return get_cursor_position("[SetMenuPosition]")
cursor_position = (self.get_cursor_position or get_cursor_position)()
# Create content, or take it from the cache.
key = (tuple(fragments_with_mouse_handlers), width, cursor_position)
def get_content() -> UIContent:
return UIContent(
get_line=lambda i: fragment_lines[i],
line_count=len(fragment_lines),
show_cursor=self.show_cursor,
cursor_position=cursor_position,
menu_position=get_menu_position(),
)
return self._content_cache.get(key, get_content)
def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Handle mouse events.
(When the fragment list contained mouse handlers and the user clicked on
on any of these, the matching handler is called. This handler can still
return `NotImplemented` in case we want the
:class:`~prompt_toolkit.layout.Window` to handle this particular
event.)
"""
if self._fragments:
# Read the generator.
fragments_for_line = list(split_lines(self._fragments))
try:
fragments = fragments_for_line[mouse_event.position.y]
except IndexError:
return NotImplemented
else:
# Find position in the fragment list.
xpos = mouse_event.position.x
# Find mouse handler for this character.
count = 0
for item in fragments:
count += len(item[1])
if count > xpos:
if len(item) >= 3:
# Handler found. Call it.
# (Handler can return NotImplemented, so return
# that result.)
handler = item[2] # type: ignore
return handler(mouse_event)
else:
break
# Otherwise, don't handle here.
return NotImplemented
def is_modal(self) -> bool:
return self.modal
def get_key_bindings(self) -> KeyBindingsBase | None:
return self.key_bindings
The provided code snippet includes necessary dependencies for implementing the `_window_too_small` function. Write a Python function `def _window_too_small() -> Window` to solve the following problem:
Create a `Window` that displays the 'Window too small' text.
Here is the function:
def _window_too_small() -> Window:
"Create a `Window` that displays the 'Window too small' text."
return Window(
FormattedTextControl(text=[("class:window-too-small", " Window too small... ")])
) | Create a `Window` that displays the 'Window too small' text. |
172,170 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters import (
FilterOrBool,
emacs_insert_mode,
to_filter,
vi_insert_mode,
)
from prompt_toolkit.formatted_text import (
AnyFormattedText,
StyleAndTextTuples,
to_formatted_text,
)
from prompt_toolkit.formatted_text.utils import (
fragment_list_to_text,
fragment_list_width,
)
from prompt_toolkit.key_binding import KeyBindingsBase
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
from prompt_toolkit.utils import get_cwidth, take_using_weights, to_int, to_str
from .controls import (
DummyControl,
FormattedTextControl,
GetLinePrefixCallable,
UIContent,
UIControl,
)
from .dimension import (
AnyDimension,
Dimension,
max_layout_dimensions,
sum_layout_dimensions,
to_dimension,
)
from .margins import Margin
from .mouse_handlers import MouseHandlers
from .screen import _CHAR_CACHE, Screen, WritePosition
from .utils import explode_text_fragments
AnyContainer = Union[Container, "MagicContainer"]
class Window(Container):
"""
Container that holds a control.
:param content: :class:`.UIControl` instance.
:param width: :class:`.Dimension` instance or callable.
:param height: :class:`.Dimension` instance or callable.
:param z_index: When specified, this can be used to bring element in front
of floating elements.
:param dont_extend_width: When `True`, don't take up more width then the
preferred width reported by the control.
:param dont_extend_height: When `True`, don't take up more width then the
preferred height reported by the control.
:param ignore_content_width: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` width when calculating the dimensions.
:param ignore_content_height: A `bool` or :class:`.Filter` instance. Ignore
the :class:`.UIContent` height when calculating the dimensions.
:param left_margins: A list of :class:`.Margin` instance to be displayed on
the left. For instance: :class:`~prompt_toolkit.layout.NumberedMargin`
can be one of them in order to show line numbers.
:param right_margins: Like `left_margins`, but on the other side.
:param scroll_offsets: :class:`.ScrollOffsets` instance, representing the
preferred amount of lines/columns to be always visible before/after the
cursor. When both top and bottom are a very high number, the cursor
will be centered vertically most of the time.
:param allow_scroll_beyond_bottom: A `bool` or
:class:`.Filter` instance. When True, allow scrolling so far, that the
top part of the content is not visible anymore, while there is still
empty space available at the bottom of the window. In the Vi editor for
instance, this is possible. You will see tildes while the top part of
the body is hidden.
:param wrap_lines: A `bool` or :class:`.Filter` instance. When True, don't
scroll horizontally, but wrap lines instead.
:param get_vertical_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
(When this is `None`, the scroll is only determined by the last and
current cursor position.)
:param get_horizontal_scroll: Callable that takes this window
instance as input and returns a preferred vertical scroll.
:param always_hide_cursor: A `bool` or
:class:`.Filter` instance. When True, never display the cursor, even
when the user control specifies a cursor position.
:param cursorline: A `bool` or :class:`.Filter` instance. When True,
display a cursorline.
:param cursorcolumn: A `bool` or :class:`.Filter` instance. When True,
display a cursorcolumn.
:param colorcolumns: A list of :class:`.ColorColumn` instances that
describe the columns to be highlighted, or a callable that returns such
a list.
:param align: :class:`.WindowAlign` value or callable that returns an
:class:`.WindowAlign` value. alignment of content.
:param style: A style string. Style to be applied to all the cells in this
window. (This can be a callable that returns a string.)
:param char: (string) Character to be used for filling the background. This
can also be a callable that returns a character.
:param get_line_prefix: None or a callable that returns formatted text to
be inserted before a line. It takes a line number (int) and a
wrap_count and returns formatted text. This can be used for
implementation of line continuations, things like Vim "breakindent" and
so on.
"""
def __init__(
self,
content: UIControl | None = None,
width: AnyDimension = None,
height: AnyDimension = None,
z_index: int | None = None,
dont_extend_width: FilterOrBool = False,
dont_extend_height: FilterOrBool = False,
ignore_content_width: FilterOrBool = False,
ignore_content_height: FilterOrBool = False,
left_margins: Sequence[Margin] | None = None,
right_margins: Sequence[Margin] | None = None,
scroll_offsets: ScrollOffsets | None = None,
allow_scroll_beyond_bottom: FilterOrBool = False,
wrap_lines: FilterOrBool = False,
get_vertical_scroll: Callable[[Window], int] | None = None,
get_horizontal_scroll: Callable[[Window], int] | None = None,
always_hide_cursor: FilterOrBool = False,
cursorline: FilterOrBool = False,
cursorcolumn: FilterOrBool = False,
colorcolumns: (
None | list[ColorColumn] | Callable[[], list[ColorColumn]]
) = None,
align: WindowAlign | Callable[[], WindowAlign] = WindowAlign.LEFT,
style: str | Callable[[], str] = "",
char: None | str | Callable[[], str] = None,
get_line_prefix: GetLinePrefixCallable | None = None,
) -> None:
self.allow_scroll_beyond_bottom = to_filter(allow_scroll_beyond_bottom)
self.always_hide_cursor = to_filter(always_hide_cursor)
self.wrap_lines = to_filter(wrap_lines)
self.cursorline = to_filter(cursorline)
self.cursorcolumn = to_filter(cursorcolumn)
self.content = content or DummyControl()
self.dont_extend_width = to_filter(dont_extend_width)
self.dont_extend_height = to_filter(dont_extend_height)
self.ignore_content_width = to_filter(ignore_content_width)
self.ignore_content_height = to_filter(ignore_content_height)
self.left_margins = left_margins or []
self.right_margins = right_margins or []
self.scroll_offsets = scroll_offsets or ScrollOffsets()
self.get_vertical_scroll = get_vertical_scroll
self.get_horizontal_scroll = get_horizontal_scroll
self.colorcolumns = colorcolumns or []
self.align = align
self.style = style
self.char = char
self.get_line_prefix = get_line_prefix
self.width = width
self.height = height
self.z_index = z_index
# Cache for the screens generated by the margin.
self._ui_content_cache: SimpleCache[
tuple[int, int, int], UIContent
] = SimpleCache(maxsize=8)
self._margin_width_cache: SimpleCache[tuple[Margin, int], int] = SimpleCache(
maxsize=1
)
self.reset()
def __repr__(self) -> str:
return "Window(content=%r)" % self.content
def reset(self) -> None:
self.content.reset()
#: Scrolling position of the main content.
self.vertical_scroll = 0
self.horizontal_scroll = 0
# Vertical scroll 2: this is the vertical offset that a line is
# scrolled if a single line (the one that contains the cursor) consumes
# all of the vertical space.
self.vertical_scroll_2 = 0
#: Keep render information (mappings between buffer input and render
#: output.)
self.render_info: WindowRenderInfo | None = None
def _get_margin_width(self, margin: Margin) -> int:
"""
Return the width for this margin.
(Calculate only once per render time.)
"""
# Margin.get_width, needs to have a UIContent instance.
def get_ui_content() -> UIContent:
return self._get_ui_content(width=0, height=0)
def get_width() -> int:
return margin.get_width(get_ui_content)
key = (margin, get_app().render_counter)
return self._margin_width_cache.get(key, get_width)
def _get_total_margin_width(self) -> int:
"""
Calculate and return the width of the margin (left + right).
"""
return sum(self._get_margin_width(m) for m in self.left_margins) + sum(
self._get_margin_width(m) for m in self.right_margins
)
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Calculate the preferred width for this window.
"""
def preferred_content_width() -> int | None:
"""Content width: is only calculated if no exact width for the
window was given."""
if self.ignore_content_width():
return None
# Calculate the width of the margin.
total_margin_width = self._get_total_margin_width()
# Window of the content. (Can be `None`.)
preferred_width = self.content.preferred_width(
max_available_width - total_margin_width
)
if preferred_width is not None:
# Include width of the margins.
preferred_width += total_margin_width
return preferred_width
# Merge.
return self._merge_dimensions(
dimension=to_dimension(self.width),
get_preferred=preferred_content_width,
dont_extend=self.dont_extend_width(),
)
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Calculate the preferred height for this window.
"""
def preferred_content_height() -> int | None:
"""Content height: is only calculated if no exact height for the
window was given."""
if self.ignore_content_height():
return None
total_margin_width = self._get_total_margin_width()
wrap_lines = self.wrap_lines()
return self.content.preferred_height(
width - total_margin_width,
max_available_height,
wrap_lines,
self.get_line_prefix,
)
return self._merge_dimensions(
dimension=to_dimension(self.height),
get_preferred=preferred_content_height,
dont_extend=self.dont_extend_height(),
)
def _merge_dimensions(
dimension: Dimension | None,
get_preferred: Callable[[], int | None],
dont_extend: bool = False,
) -> Dimension:
"""
Take the Dimension from this `Window` class and the received preferred
size from the `UIControl` and return a `Dimension` to report to the
parent container.
"""
dimension = dimension or Dimension()
# When a preferred dimension was explicitly given to the Window,
# ignore the UIControl.
preferred: int | None
if dimension.preferred_specified:
preferred = dimension.preferred
else:
# Otherwise, calculate the preferred dimension from the UI control
# content.
preferred = get_preferred()
# When a 'preferred' dimension is given by the UIControl, make sure
# that it stays within the bounds of the Window.
if preferred is not None:
if dimension.max_specified:
preferred = min(preferred, dimension.max)
if dimension.min_specified:
preferred = max(preferred, dimension.min)
# When a `dont_extend` flag has been given, use the preferred dimension
# also as the max dimension.
max_: int | None
min_: int | None
if dont_extend and preferred is not None:
max_ = min(dimension.max, preferred)
else:
max_ = dimension.max if dimension.max_specified else None
min_ = dimension.min if dimension.min_specified else None
return Dimension(
min=min_, max=max_, preferred=preferred, weight=dimension.weight
)
def _get_ui_content(self, width: int, height: int) -> UIContent:
"""
Create a `UIContent` instance.
"""
def get_content() -> UIContent:
return self.content.create_content(width=width, height=height)
key = (get_app().render_counter, width, height)
return self._ui_content_cache.get(key, get_content)
def _get_digraph_char(self) -> str | None:
"Return `False`, or the Digraph symbol to be used."
app = get_app()
if app.quoted_insert:
return "^"
if app.vi_state.waiting_for_digraph:
if app.vi_state.digraph_symbol1:
return app.vi_state.digraph_symbol1
return "?"
return None
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: int | None,
) -> None:
"""
Write window to screen. This renders the user control, the margins and
copies everything over to the absolute position at the given screen.
"""
# If dont_extend_width/height was given. Then reduce width/height in
# WritePosition if the parent wanted us to paint in a bigger area.
# (This happens if this window is bundled with another window in a
# HSplit/VSplit, but with different size requirements.)
write_position = WritePosition(
xpos=write_position.xpos,
ypos=write_position.ypos,
width=write_position.width,
height=write_position.height,
)
if self.dont_extend_width():
write_position.width = min(
write_position.width,
self.preferred_width(write_position.width).preferred,
)
if self.dont_extend_height():
write_position.height = min(
write_position.height,
self.preferred_height(
write_position.width, write_position.height
).preferred,
)
# Draw
z_index = z_index if self.z_index is None else self.z_index
draw_func = partial(
self._write_to_screen_at_index,
screen,
mouse_handlers,
write_position,
parent_style,
erase_bg,
)
if z_index is None or z_index <= 0:
# When no z_index is given, draw right away.
draw_func()
else:
# Otherwise, postpone.
screen.draw_with_z_index(z_index=z_index, draw_func=draw_func)
def _write_to_screen_at_index(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
) -> None:
# Don't bother writing invisible windows.
# (We save some time, but also avoid applying last-line styling.)
if write_position.height <= 0 or write_position.width <= 0:
return
# Calculate margin sizes.
left_margin_widths = [self._get_margin_width(m) for m in self.left_margins]
right_margin_widths = [self._get_margin_width(m) for m in self.right_margins]
total_margin_width = sum(left_margin_widths + right_margin_widths)
# Render UserControl.
ui_content = self.content.create_content(
write_position.width - total_margin_width, write_position.height
)
assert isinstance(ui_content, UIContent)
# Scroll content.
wrap_lines = self.wrap_lines()
self._scroll(
ui_content, write_position.width - total_margin_width, write_position.height
)
# Erase background and fill with `char`.
self._fill_bg(screen, write_position, erase_bg)
# Resolve `align` attribute.
align = self.align() if callable(self.align) else self.align
# Write body
visible_line_to_row_col, rowcol_to_yx = self._copy_body(
ui_content,
screen,
write_position,
sum(left_margin_widths),
write_position.width - total_margin_width,
self.vertical_scroll,
self.horizontal_scroll,
wrap_lines=wrap_lines,
highlight_lines=True,
vertical_scroll_2=self.vertical_scroll_2,
always_hide_cursor=self.always_hide_cursor(),
has_focus=get_app().layout.current_control == self.content,
align=align,
get_line_prefix=self.get_line_prefix,
)
# Remember render info. (Set before generating the margins. They need this.)
x_offset = write_position.xpos + sum(left_margin_widths)
y_offset = write_position.ypos
render_info = WindowRenderInfo(
window=self,
ui_content=ui_content,
horizontal_scroll=self.horizontal_scroll,
vertical_scroll=self.vertical_scroll,
window_width=write_position.width - total_margin_width,
window_height=write_position.height,
configured_scroll_offsets=self.scroll_offsets,
visible_line_to_row_col=visible_line_to_row_col,
rowcol_to_yx=rowcol_to_yx,
x_offset=x_offset,
y_offset=y_offset,
wrap_lines=wrap_lines,
)
self.render_info = render_info
# Set mouse handlers.
def mouse_handler(mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Wrapper around the mouse_handler of the `UIControl` that turns
screen coordinates into line coordinates.
Returns `NotImplemented` if no UI invalidation should be done.
"""
# Don't handle mouse events outside of the current modal part of
# the UI.
if self not in get_app().layout.walk_through_modal_area():
return NotImplemented
# Find row/col position first.
yx_to_rowcol = {v: k for k, v in rowcol_to_yx.items()}
y = mouse_event.position.y
x = mouse_event.position.x
# If clicked below the content area, look for a position in the
# last line instead.
max_y = write_position.ypos + len(visible_line_to_row_col) - 1
y = min(max_y, y)
result: NotImplementedOrNone
while x >= 0:
try:
row, col = yx_to_rowcol[y, x]
except KeyError:
# Try again. (When clicking on the right side of double
# width characters, or on the right side of the input.)
x -= 1
else:
# Found position, call handler of UIControl.
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=col, y=row),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
break
else:
# nobreak.
# (No x/y coordinate found for the content. This happens in
# case of a DummyControl, that does not have any content.
# Report (0,0) instead.)
result = self.content.mouse_handler(
MouseEvent(
position=Point(x=0, y=0),
event_type=mouse_event.event_type,
button=mouse_event.button,
modifiers=mouse_event.modifiers,
)
)
# If it returns NotImplemented, handle it here.
if result == NotImplemented:
result = self._mouse_handler(mouse_event)
return result
mouse_handlers.set_mouse_handler_for_range(
x_min=write_position.xpos + sum(left_margin_widths),
x_max=write_position.xpos + write_position.width - total_margin_width,
y_min=write_position.ypos,
y_max=write_position.ypos + write_position.height,
handler=mouse_handler,
)
# Render and copy margins.
move_x = 0
def render_margin(m: Margin, width: int) -> UIContent:
"Render margin. Return `Screen`."
# Retrieve margin fragments.
fragments = m.create_margin(render_info, width, write_position.height)
# Turn it into a UIContent object.
# already rendered those fragments using this size.)
return FormattedTextControl(fragments).create_content(
width + 1, write_position.height
)
for m, width in zip(self.left_margins, left_margin_widths):
if width > 0: # (ConditionalMargin returns a zero width. -- Don't render.)
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
move_x = write_position.width - sum(right_margin_widths)
for m, width in zip(self.right_margins, right_margin_widths):
# Create screen for margin.
margin_content = render_margin(m, width)
# Copy and shift X.
self._copy_margin(margin_content, screen, write_position, move_x, width)
move_x += width
# Apply 'self.style'
self._apply_style(screen, write_position, parent_style)
# Tell the screen that this user control has been painted at this
# position.
screen.visible_windows_to_write_positions[self] = write_position
def _copy_body(
self,
ui_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
vertical_scroll: int = 0,
horizontal_scroll: int = 0,
wrap_lines: bool = False,
highlight_lines: bool = False,
vertical_scroll_2: int = 0,
always_hide_cursor: bool = False,
has_focus: bool = False,
align: WindowAlign = WindowAlign.LEFT,
get_line_prefix: Callable[[int, int], AnyFormattedText] | None = None,
) -> tuple[dict[int, tuple[int, int]], dict[tuple[int, int], tuple[int, int]]]:
"""
Copy the UIContent into the output screen.
Return (visible_line_to_row_col, rowcol_to_yx) tuple.
:param get_line_prefix: None or a callable that takes a line number
(int) and a wrap_count (int) and returns formatted text.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
line_count = ui_content.line_count
new_buffer = new_screen.data_buffer
empty_char = _CHAR_CACHE["", ""]
# Map visible line number to (row, col) of input.
# 'col' will always be zero if line wrapping is off.
visible_line_to_row_col: dict[int, tuple[int, int]] = {}
# Maps (row, col) from the input to (y, x) screen coordinates.
rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
def copy_line(
line: StyleAndTextTuples,
lineno: int,
x: int,
y: int,
is_input: bool = False,
) -> tuple[int, int]:
"""
Copy over a single line to the output screen. This can wrap over
multiple lines in the output. It will call the prefix (prompt)
function before every line.
"""
if is_input:
current_rowcol_to_yx = rowcol_to_yx
else:
current_rowcol_to_yx = {} # Throwaway dictionary.
# Draw line prefix.
if is_input and get_line_prefix:
prompt = to_formatted_text(get_line_prefix(lineno, 0))
x, y = copy_line(prompt, lineno, x, y, is_input=False)
# Scroll horizontally.
skipped = 0 # Characters skipped because of horizontal scrolling.
if horizontal_scroll and is_input:
h_scroll = horizontal_scroll
line = explode_text_fragments(line)
while h_scroll > 0 and line:
h_scroll -= get_cwidth(line[0][1])
skipped += 1
del line[:1] # Remove first character.
x -= h_scroll # When scrolling over double width character,
# this can end up being negative.
# Align this line. (Note that this doesn't work well when we use
# get_line_prefix and that function returns variable width prefixes.)
if align == WindowAlign.CENTER:
line_width = fragment_list_width(line)
if line_width < width:
x += (width - line_width) // 2
elif align == WindowAlign.RIGHT:
line_width = fragment_list_width(line)
if line_width < width:
x += width - line_width
col = 0
wrap_count = 0
for style, text, *_ in line:
new_buffer_row = new_buffer[y + ypos]
# Remember raw VT escape sequences. (E.g. FinalTerm's
# escape sequences.)
if "[ZeroWidthEscape]" in style:
new_screen.zero_width_escapes[y + ypos][x + xpos] += text
continue
for c in text:
char = _CHAR_CACHE[c, style]
char_width = char.width
# Wrap when the line width is exceeded.
if wrap_lines and x + char_width > width:
visible_line_to_row_col[y + 1] = (
lineno,
visible_line_to_row_col[y][1] + x,
)
y += 1
wrap_count += 1
x = 0
# Insert line prefix (continuation prompt).
if is_input and get_line_prefix:
prompt = to_formatted_text(
get_line_prefix(lineno, wrap_count)
)
x, y = copy_line(prompt, lineno, x, y, is_input=False)
new_buffer_row = new_buffer[y + ypos]
if y >= write_position.height:
return x, y # Break out of all for loops.
# Set character in screen and shift 'x'.
if x >= 0 and y >= 0 and x < width:
new_buffer_row[x + xpos] = char
# When we print a multi width character, make sure
# to erase the neighbours positions in the screen.
# (The empty string if different from everything,
# so next redraw this cell will repaint anyway.)
if char_width > 1:
for i in range(1, char_width):
new_buffer_row[x + xpos + i] = empty_char
# If this is a zero width characters, then it's
# probably part of a decomposed unicode character.
# See: https://en.wikipedia.org/wiki/Unicode_equivalence
# Merge it in the previous cell.
elif char_width == 0:
# Handle all character widths. If the previous
# character is a multiwidth character, then
# merge it two positions back.
for pw in [2, 1]: # Previous character width.
if (
x - pw >= 0
and new_buffer_row[x + xpos - pw].width == pw
):
prev_char = new_buffer_row[x + xpos - pw]
char2 = _CHAR_CACHE[
prev_char.char + c, prev_char.style
]
new_buffer_row[x + xpos - pw] = char2
# Keep track of write position for each character.
current_rowcol_to_yx[lineno, col + skipped] = (
y + ypos,
x + xpos,
)
col += 1
x += char_width
return x, y
# Copy content.
def copy() -> int:
y = -vertical_scroll_2
lineno = vertical_scroll
while y < write_position.height and lineno < line_count:
# Take the next line and copy it in the real screen.
line = ui_content.get_line(lineno)
visible_line_to_row_col[y] = (lineno, horizontal_scroll)
# Copy margin and actual line.
x = 0
x, y = copy_line(line, lineno, x, y, is_input=True)
lineno += 1
y += 1
return y
copy()
def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
"Translate row/col from UIContent to real Screen coordinates."
try:
y, x = rowcol_to_yx[row, col]
except KeyError:
# Normally this should never happen. (It is a bug, if it happens.)
# But to be sure, return (0, 0)
return Point(x=0, y=0)
# raise ValueError(
# 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
# 'horizontal_scroll=%r, height=%r' %
# (row, col, vertical_scroll, horizontal_scroll, write_position.height))
else:
return Point(x=x, y=y)
# Set cursor and menu positions.
if ui_content.cursor_position:
screen_cursor_position = cursor_pos_to_screen_pos(
ui_content.cursor_position.y, ui_content.cursor_position.x
)
if has_focus:
new_screen.set_cursor_position(self, screen_cursor_position)
if always_hide_cursor:
new_screen.show_cursor = False
else:
new_screen.show_cursor = ui_content.show_cursor
self._highlight_digraph(new_screen)
if highlight_lines:
self._highlight_cursorlines(
new_screen,
screen_cursor_position,
xpos,
ypos,
width,
write_position.height,
)
# Draw input characters from the input processor queue.
if has_focus and ui_content.cursor_position:
self._show_key_processor_key_buffer(new_screen)
# Set menu position.
if ui_content.menu_position:
new_screen.set_menu_position(
self,
cursor_pos_to_screen_pos(
ui_content.menu_position.y, ui_content.menu_position.x
),
)
# Update output screen height.
new_screen.height = max(new_screen.height, ypos + write_position.height)
return visible_line_to_row_col, rowcol_to_yx
def _fill_bg(
self, screen: Screen, write_position: WritePosition, erase_bg: bool
) -> None:
"""
Erase/fill the background.
(Useful for floats and when a `char` has been given.)
"""
char: str | None
if callable(self.char):
char = self.char()
else:
char = self.char
if erase_bg or char:
wp = write_position
char_obj = _CHAR_CACHE[char or " ", ""]
for y in range(wp.ypos, wp.ypos + wp.height):
row = screen.data_buffer[y]
for x in range(wp.xpos, wp.xpos + wp.width):
row[x] = char_obj
def _apply_style(
self, new_screen: Screen, write_position: WritePosition, parent_style: str
) -> None:
# Apply `self.style`.
style = parent_style + " " + to_str(self.style)
new_screen.fill_area(write_position, style=style, after=False)
# Apply the 'last-line' class to the last line of each Window. This can
# be used to apply an 'underline' to the user control.
wp = WritePosition(
write_position.xpos,
write_position.ypos + write_position.height - 1,
write_position.width,
1,
)
new_screen.fill_area(wp, "class:last-line", after=True)
def _highlight_digraph(self, new_screen: Screen) -> None:
"""
When we are in Vi digraph mode, put a question mark underneath the
cursor.
"""
digraph_char = self._get_digraph_char()
if digraph_char:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
digraph_char, "class:digraph"
]
def _show_key_processor_key_buffer(self, new_screen: Screen) -> None:
"""
When the user is typing a key binding that consists of several keys,
display the last pressed key if the user is in insert mode and the key
is meaningful to be displayed.
E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
first 'j' needs to be displayed in order to get some feedback.
"""
app = get_app()
key_buffer = app.key_processor.key_buffer
if key_buffer and _in_insert_mode() and not app.is_done:
# The textual data for the given key. (Can be a VT100 escape
# sequence.)
data = key_buffer[-1].data
# Display only if this is a 1 cell width character.
if get_cwidth(data) == 1:
cpos = new_screen.get_cursor_position(self)
new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
data, "class:partial-key-binding"
]
def _highlight_cursorlines(
self, new_screen: Screen, cpos: Point, x: int, y: int, width: int, height: int
) -> None:
"""
Highlight cursor row/column.
"""
cursor_line_style = " class:cursor-line "
cursor_column_style = " class:cursor-column "
data_buffer = new_screen.data_buffer
# Highlight cursor line.
if self.cursorline():
row = data_buffer[cpos.y]
for x in range(x, x + width):
original_char = row[x]
row[x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_line_style
]
# Highlight cursor column.
if self.cursorcolumn():
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[cpos.x]
row[cpos.x] = _CHAR_CACHE[
original_char.char, original_char.style + cursor_column_style
]
# Highlight color columns
colorcolumns = self.colorcolumns
if callable(colorcolumns):
colorcolumns = colorcolumns()
for cc in colorcolumns:
assert isinstance(cc, ColorColumn)
column = cc.position
if column < x + width: # Only draw when visible.
color_column_style = " " + cc.style
for y2 in range(y, y + height):
row = data_buffer[y2]
original_char = row[column + x]
row[column + x] = _CHAR_CACHE[
original_char.char, original_char.style + color_column_style
]
def _copy_margin(
self,
margin_content: UIContent,
new_screen: Screen,
write_position: WritePosition,
move_x: int,
width: int,
) -> None:
"""
Copy characters from the margin screen to the real screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
self._copy_body(margin_content, new_screen, margin_write_position, 0, width)
def _scroll(self, ui_content: UIContent, width: int, height: int) -> None:
"""
Scroll body. Ensure that the cursor is visible.
"""
if self.wrap_lines():
func = self._scroll_when_linewrapping
else:
func = self._scroll_without_linewrapping
func(ui_content, width, height)
def _scroll_when_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
scroll_offsets_bottom = self.scroll_offsets.bottom
scroll_offsets_top = self.scroll_offsets.top
# We don't have horizontal scrolling.
self.horizontal_scroll = 0
def get_line_height(lineno: int) -> int:
return ui_content.get_height_for_line(lineno, width, self.get_line_prefix)
# When there is no space, reset `vertical_scroll_2` to zero and abort.
# This can happen if the margin is bigger than the window width.
# Otherwise the text height will become "infinite" (a big number) and
# the copy_line will spend a huge amount of iterations trying to render
# nothing.
if width <= 0:
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = 0
return
# If the current line consumes more than the whole window height,
# then we have to scroll vertically inside this line. (We don't take
# the scroll offsets into account for this.)
# Also, ignore the scroll offsets in this case. Just set the vertical
# scroll to this line.
line_height = get_line_height(ui_content.cursor_position.y)
if line_height > height - scroll_offsets_top:
# Calculate the height of the text before the cursor (including
# line prefixes).
text_before_height = ui_content.get_height_for_line(
ui_content.cursor_position.y,
width,
self.get_line_prefix,
slice_stop=ui_content.cursor_position.x,
)
# Adjust scroll offset.
self.vertical_scroll = ui_content.cursor_position.y
self.vertical_scroll_2 = min(
text_before_height - 1, # Keep the cursor visible.
line_height
- height, # Avoid blank lines at the bottom when scolling up again.
self.vertical_scroll_2,
)
self.vertical_scroll_2 = max(
0, text_before_height - height, self.vertical_scroll_2
)
return
else:
self.vertical_scroll_2 = 0
# Current line doesn't consume the whole height. Take scroll offsets into account.
def get_min_vertical_scroll() -> int:
# Make sure that the cursor line is not below the bottom.
# (Calculate how many lines can be shown between the cursor and the .)
used_height = 0
prev_lineno = ui_content.cursor_position.y
for lineno in range(ui_content.cursor_position.y, -1, -1):
used_height += get_line_height(lineno)
if used_height > height - scroll_offsets_bottom:
return prev_lineno
else:
prev_lineno = lineno
return 0
def get_max_vertical_scroll() -> int:
# Make sure that the cursor line is not above the top.
prev_lineno = ui_content.cursor_position.y
used_height = 0
for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > scroll_offsets_top:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
def get_topmost_visible() -> int:
"""
Calculate the upper most line that can be visible, while the bottom
is still visible. We should not allow scroll more than this if
`allow_scroll_beyond_bottom` is false.
"""
prev_lineno = ui_content.line_count - 1
used_height = 0
for lineno in range(ui_content.line_count - 1, -1, -1):
used_height += get_line_height(lineno)
if used_height > height:
return prev_lineno
else:
prev_lineno = lineno
return prev_lineno
# Scroll vertically. (Make sure that the whole line which contains the
# cursor is visible.
topmost_visible = get_topmost_visible()
# Note: the `min(topmost_visible, ...)` is to make sure that we
# don't require scrolling up because of the bottom scroll offset,
# when we are at the end of the document.
self.vertical_scroll = max(
self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll())
)
self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
# Disallow scrolling beyond bottom?
if not self.allow_scroll_beyond_bottom():
self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
def _scroll_without_linewrapping(
self, ui_content: UIContent, width: int, height: int
) -> None:
"""
Scroll to make sure the cursor position is visible and that we maintain
the requested scroll offset.
Set `self.horizontal_scroll/vertical_scroll`.
"""
cursor_position = ui_content.cursor_position or Point(x=0, y=0)
# Without line wrapping, we will never have to scroll vertically inside
# a single line.
self.vertical_scroll_2 = 0
if ui_content.line_count == 0:
self.vertical_scroll = 0
self.horizontal_scroll = 0
return
else:
current_line_text = fragment_list_to_text(
ui_content.get_line(cursor_position.y)
)
def do_scroll(
current_scroll: int,
scroll_offset_start: int,
scroll_offset_end: int,
cursor_pos: int,
window_size: int,
content_size: int,
) -> int:
"Scrolling algorithm. Used for both horizontal and vertical scrolling."
# Calculate the scroll offset to apply.
# This can obviously never be more than have the screen size. Also, when the
# cursor appears at the top or bottom, we don't apply the offset.
scroll_offset_start = int(
min(scroll_offset_start, window_size / 2, cursor_pos)
)
scroll_offset_end = int(
min(scroll_offset_end, window_size / 2, content_size - 1 - cursor_pos)
)
# Prevent negative scroll offsets.
if current_scroll < 0:
current_scroll = 0
# Scroll back if we scrolled to much and there's still space to show more of the document.
if (
not self.allow_scroll_beyond_bottom()
and current_scroll > content_size - window_size
):
current_scroll = max(0, content_size - window_size)
# Scroll up if cursor is before visible part.
if current_scroll > cursor_pos - scroll_offset_start:
current_scroll = max(0, cursor_pos - scroll_offset_start)
# Scroll down if cursor is after visible part.
if current_scroll < (cursor_pos + 1) - window_size + scroll_offset_end:
current_scroll = (cursor_pos + 1) - window_size + scroll_offset_end
return current_scroll
# When a preferred scroll is given, take that first into account.
if self.get_vertical_scroll:
self.vertical_scroll = self.get_vertical_scroll(self)
assert isinstance(self.vertical_scroll, int)
if self.get_horizontal_scroll:
self.horizontal_scroll = self.get_horizontal_scroll(self)
assert isinstance(self.horizontal_scroll, int)
# Update horizontal/vertical scroll to make sure that the cursor
# remains visible.
offsets = self.scroll_offsets
self.vertical_scroll = do_scroll(
current_scroll=self.vertical_scroll,
scroll_offset_start=offsets.top,
scroll_offset_end=offsets.bottom,
cursor_pos=ui_content.cursor_position.y,
window_size=height,
content_size=ui_content.line_count,
)
if self.get_line_prefix:
current_line_prefix_width = fragment_list_width(
to_formatted_text(self.get_line_prefix(ui_content.cursor_position.y, 0))
)
else:
current_line_prefix_width = 0
self.horizontal_scroll = do_scroll(
current_scroll=self.horizontal_scroll,
scroll_offset_start=offsets.left,
scroll_offset_end=offsets.right,
cursor_pos=get_cwidth(current_line_text[: ui_content.cursor_position.x]),
window_size=width - current_line_prefix_width,
# We can only analyse the current line. Calculating the width off
# all the lines is too expensive.
content_size=max(
get_cwidth(current_line_text), self.horizontal_scroll + width
),
)
def _mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
"""
Mouse handler. Called when the UI control doesn't handle this
particular event.
Return `NotImplemented` if nothing was done as a consequence of this
key binding (no UI invalidate required in that case).
"""
if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
self._scroll_down()
return None
elif mouse_event.event_type == MouseEventType.SCROLL_UP:
self._scroll_up()
return None
return NotImplemented
def _scroll_down(self) -> None:
"Scroll window down."
info = self.render_info
if info is None:
return
if self.vertical_scroll < info.content_height - info.window_height:
if info.cursor_position.y <= info.configured_scroll_offsets.top:
self.content.move_cursor_down()
self.vertical_scroll += 1
def _scroll_up(self) -> None:
"Scroll window up."
info = self.render_info
if info is None:
return
if info.vertical_scroll > 0:
# TODO: not entirely correct yet in case of line wrapping and long lines.
if (
info.cursor_position.y
>= info.window_height - 1 - info.configured_scroll_offsets.bottom
):
self.content.move_cursor_up()
self.vertical_scroll -= 1
def get_key_bindings(self) -> KeyBindingsBase | None:
return self.content.get_key_bindings()
def get_children(self) -> list[Container]:
return []
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
The provided code snippet includes necessary dependencies for implementing the `to_window` function. Write a Python function `def to_window(container: AnyContainer) -> Window` to solve the following problem:
Make sure that the given argument is a :class:`.Window`.
Here is the function:
def to_window(container: AnyContainer) -> Window:
"""
Make sure that the given argument is a :class:`.Window`.
"""
if isinstance(container, Window):
return container
elif hasattr(container, "__pt_container__"):
return to_window(cast("MagicContainer", container).__pt_container__())
else:
raise ValueError(f"Not a Window object: {container!r}.") | Make sure that the given argument is a :class:`.Window`. |
172,171 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters import (
FilterOrBool,
emacs_insert_mode,
to_filter,
vi_insert_mode,
)
from prompt_toolkit.formatted_text import (
AnyFormattedText,
StyleAndTextTuples,
to_formatted_text,
)
from prompt_toolkit.formatted_text.utils import (
fragment_list_to_text,
fragment_list_width,
)
from prompt_toolkit.key_binding import KeyBindingsBase
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
from prompt_toolkit.utils import get_cwidth, take_using_weights, to_int, to_str
from .controls import (
DummyControl,
FormattedTextControl,
GetLinePrefixCallable,
UIContent,
UIControl,
)
from .dimension import (
AnyDimension,
Dimension,
max_layout_dimensions,
sum_layout_dimensions,
to_dimension,
)
from .margins import Margin
from .mouse_handlers import MouseHandlers
from .screen import _CHAR_CACHE, Screen, WritePosition
from .utils import explode_text_fragments
class Container(metaclass=ABCMeta):
"""
Base class for user interface layout.
"""
def reset(self) -> None:
"""
Reset the state of this container and all the children.
(E.g. reset scroll offsets, etc...)
"""
def preferred_width(self, max_available_width: int) -> Dimension:
"""
Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
desired width for this container.
"""
def preferred_height(self, width: int, max_available_height: int) -> Dimension:
"""
Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
desired height for this container.
"""
def write_to_screen(
self,
screen: Screen,
mouse_handlers: MouseHandlers,
write_position: WritePosition,
parent_style: str,
erase_bg: bool,
z_index: int | None,
) -> None:
"""
Write the actual content to the screen.
:param screen: :class:`~prompt_toolkit.layout.screen.Screen`
:param mouse_handlers: :class:`~prompt_toolkit.layout.mouse_handlers.MouseHandlers`.
:param parent_style: Style string to pass to the :class:`.Window`
object. This will be applied to all content of the windows.
:class:`.VSplit` and :class:`.HSplit` can use it to pass their
style down to the windows that they contain.
:param z_index: Used for propagating z_index from parent to child.
"""
def is_modal(self) -> bool:
"""
When this container is modal, key bindings from parent containers are
not taken into account if a user control in this container is focused.
"""
return False
def get_key_bindings(self) -> KeyBindingsBase | None:
"""
Returns a :class:`.KeyBindings` object. These bindings become active when any
user control in this container has the focus, except if any containers
between this container and the focused user control is modal.
"""
return None
def get_children(self) -> list[Container]:
"""
Return the list of child :class:`.Container` objects.
"""
return []
AnyContainer = Union[Container, "MagicContainer"]
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
The provided code snippet includes necessary dependencies for implementing the `is_container` function. Write a Python function `def is_container(value: object) -> TypeGuard[AnyContainer]` to solve the following problem:
Checks whether the given value is a container object (for use in assert statements).
Here is the function:
def is_container(value: object) -> TypeGuard[AnyContainer]:
"""
Checks whether the given value is a container object
(for use in assert statements).
"""
if isinstance(value, Container):
return True
if hasattr(value, "__pt_container__"):
return is_container(cast("MagicContainer", value).__pt_container__())
return False | Checks whether the given value is a container object (for use in assert statements). |
172,172 | from __future__ import annotations
import math
from itertools import zip_longest
from typing import (
TYPE_CHECKING,
Callable,
Dict,
Iterable,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from weakref import WeakKeyDictionary
from prompt_toolkit.application.current import get_app
from prompt_toolkit.buffer import CompletionState
from prompt_toolkit.completion import Completion
from prompt_toolkit.data_structures import Point
from prompt_toolkit.filters import (
Condition,
FilterOrBool,
has_completions,
is_done,
to_filter,
)
from prompt_toolkit.formatted_text import (
StyleAndTextTuples,
fragment_list_width,
to_formatted_text,
)
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from prompt_toolkit.layout.utils import explode_text_fragments
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
from prompt_toolkit.utils import get_cwidth
from .containers import ConditionalContainer, HSplit, ScrollOffsets, Window
from .controls import GetLinePrefixCallable, UIContent, UIControl
from .dimension import Dimension
from .margins import ScrollbarMargin
def _trim_formatted_text(
formatted_text: StyleAndTextTuples, max_width: int
) -> tuple[StyleAndTextTuples, int]:
"""
Trim the text to `max_width`, append dots when the text is too long.
Returns (text, width) tuple.
"""
width = fragment_list_width(formatted_text)
# When the text is too wide, trim it.
if width > max_width:
result = [] # Text fragments.
remaining_width = max_width - 3
for style_and_ch in explode_text_fragments(formatted_text):
ch_width = get_cwidth(style_and_ch[1])
if ch_width <= remaining_width:
result.append(style_and_ch)
remaining_width -= ch_width
else:
break
result.append(("", "..."))
return result, max_width - remaining_width
else:
return formatted_text, width
def cast(typ: Type[_T], val: Any) -> _T: ...
def cast(typ: str, val: Any) -> Any: ...
def cast(typ: object, val: Any) -> Any: ...
The provided code snippet includes necessary dependencies for implementing the `_get_menu_item_fragments` function. Write a Python function `def _get_menu_item_fragments( completion: Completion, is_current_completion: bool, width: int, space_after: bool = False, ) -> StyleAndTextTuples` to solve the following problem:
Get the style/text tuples for a menu item, styled and trimmed to the given width.
Here is the function:
def _get_menu_item_fragments(
completion: Completion,
is_current_completion: bool,
width: int,
space_after: bool = False,
) -> StyleAndTextTuples:
"""
Get the style/text tuples for a menu item, styled and trimmed to the given
width.
"""
if is_current_completion:
style_str = "class:completion-menu.completion.current {} {}".format(
completion.style,
completion.selected_style,
)
else:
style_str = "class:completion-menu.completion " + completion.style
text, tw = _trim_formatted_text(
completion.display, (width - 2 if space_after else width - 1)
)
padding = " " * (width - 1 - tw)
return to_formatted_text(
cast(StyleAndTextTuples, []) + [("", " ")] + text + [("", padding)],
style=style_str,
) | Get the style/text tuples for a menu item, styled and trimmed to the given width. |
172,173 | from __future__ import annotations
import re
from abc import ABCMeta, abstractmethod
from typing import (
TYPE_CHECKING,
Callable,
Hashable,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import SimpleCache
from prompt_toolkit.document import Document
from prompt_toolkit.filters import FilterOrBool, to_filter, vi_insert_multiple_mode
from prompt_toolkit.formatted_text import (
AnyFormattedText,
StyleAndTextTuples,
to_formatted_text,
)
from prompt_toolkit.formatted_text.utils import fragment_list_len, fragment_list_to_text
from prompt_toolkit.search import SearchDirection
from prompt_toolkit.utils import to_int, to_str
from .utils import explode_text_fragments
class Processor(metaclass=ABCMeta):
"""
Manipulate the fragments for a given line in a
:class:`~prompt_toolkit.layout.controls.BufferControl`.
"""
def apply_transformation(
self, transformation_input: TransformationInput
) -> Transformation:
"""
Apply transformation. Returns a :class:`.Transformation` instance.
:param transformation_input: :class:`.TransformationInput` object.
"""
return Transformation(transformation_input.fragments)
class DummyProcessor(Processor):
"""
A `Processor` that doesn't do anything.
"""
def apply_transformation(
self, transformation_input: TransformationInput
) -> Transformation:
return Transformation(transformation_input.fragments)
class _MergedProcessor(Processor):
"""
Processor that groups multiple other `Processor` objects, but exposes an
API as if it is one `Processor`.
"""
def __init__(self, processors: list[Processor]):
self.processors = processors
def apply_transformation(self, ti: TransformationInput) -> Transformation:
source_to_display_functions = [ti.source_to_display]
display_to_source_functions = []
fragments = ti.fragments
def source_to_display(i: int) -> int:
"""Translate x position from the buffer to the x position in the
processor fragments list."""
for f in source_to_display_functions:
i = f(i)
return i
for p in self.processors:
transformation = p.apply_transformation(
TransformationInput(
ti.buffer_control,
ti.document,
ti.lineno,
source_to_display,
fragments,
ti.width,
ti.height,
)
)
fragments = transformation.fragments
display_to_source_functions.append(transformation.display_to_source)
source_to_display_functions.append(transformation.source_to_display)
def display_to_source(i: int) -> int:
for f in reversed(display_to_source_functions):
i = f(i)
return i
# In the case of a nested _MergedProcessor, each processor wants to
# receive a 'source_to_display' function (as part of the
# TransformationInput) that has everything in the chain before
# included, because it can be called as part of the
# `apply_transformation` function. However, this first
# `source_to_display` should not be part of the output that we are
# returning. (This is the most consistent with `display_to_source`.)
del source_to_display_functions[:1]
return Transformation(fragments, source_to_display, display_to_source)
The provided code snippet includes necessary dependencies for implementing the `merge_processors` function. Write a Python function `def merge_processors(processors: list[Processor]) -> Processor` to solve the following problem:
Merge multiple `Processor` objects into one.
Here is the function:
def merge_processors(processors: list[Processor]) -> Processor:
"""
Merge multiple `Processor` objects into one.
"""
if len(processors) == 0:
return DummyProcessor()
if len(processors) == 1:
return processors[0] # Nothing to merge.
return _MergedProcessor(processors) | Merge multiple `Processor` objects into one. |
172,174 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or smaller, it tries to keep in
between min and max.
:param min: Minimum size.
:param max: Maximum size.
:param weight: For a VSplit/HSplit, the actual size will be determined
by taking the proportion of weights from all the children.
E.g. When there are two children, one with a weight of 1,
and the other with a weight of 2, the second will always be
twice as big as the first, if the min/max values allow it.
:param preferred: Preferred size.
"""
def __init__(
self,
min: int | None = None,
max: int | None = None,
weight: int | None = None,
preferred: int | None = None,
) -> None:
if weight is not None:
assert weight >= 0 # Also cannot be a float.
assert min is None or min >= 0
assert max is None or max >= 0
assert preferred is None or preferred >= 0
self.min_specified = min is not None
self.max_specified = max is not None
self.preferred_specified = preferred is not None
self.weight_specified = weight is not None
if min is None:
min = 0 # Smallest possible value.
if max is None: # 0-values are allowed, so use "is None"
max = 1000**10 # Something huge.
if preferred is None:
preferred = min
if weight is None:
weight = 1
self.min = min
self.max = max
self.preferred = preferred
self.weight = weight
# Don't allow situations where max < min. (This would be a bug.)
if max < min:
raise ValueError("Invalid Dimension: max < min.")
# Make sure that the 'preferred' size is always in the min..max range.
if self.preferred < self.min:
self.preferred = self.min
if self.preferred > self.max:
self.preferred = self.max
def exact(cls, amount: int) -> Dimension:
"""
Return a :class:`.Dimension` with an exact size. (min, max and
preferred set to ``amount``).
"""
return cls(min=amount, max=amount, preferred=amount)
def zero(cls) -> Dimension:
"""
Create a dimension that represents a zero size. (Used for 'invisible'
controls.)
"""
return cls.exact(amount=0)
def is_zero(self) -> bool:
"True if this `Dimension` represents a zero size."
return self.preferred == 0 or self.max == 0
def __repr__(self) -> str:
fields = []
if self.min_specified:
fields.append("min=%r" % self.min)
if self.max_specified:
fields.append("max=%r" % self.max)
if self.preferred_specified:
fields.append("preferred=%r" % self.preferred)
if self.weight_specified:
fields.append("weight=%r" % self.weight)
return "Dimension(%s)" % ", ".join(fields)
The provided code snippet includes necessary dependencies for implementing the `sum_layout_dimensions` function. Write a Python function `def sum_layout_dimensions(dimensions: list[Dimension]) -> Dimension` to solve the following problem:
Sum a list of :class:`.Dimension` instances.
Here is the function:
def sum_layout_dimensions(dimensions: list[Dimension]) -> Dimension:
"""
Sum a list of :class:`.Dimension` instances.
"""
min = sum(d.min for d in dimensions)
max = sum(d.max for d in dimensions)
preferred = sum(d.preferred for d in dimensions)
return Dimension(min=min, max=max, preferred=preferred) | Sum a list of :class:`.Dimension` instances. |
172,175 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or smaller, it tries to keep in
between min and max.
:param min: Minimum size.
:param max: Maximum size.
:param weight: For a VSplit/HSplit, the actual size will be determined
by taking the proportion of weights from all the children.
E.g. When there are two children, one with a weight of 1,
and the other with a weight of 2, the second will always be
twice as big as the first, if the min/max values allow it.
:param preferred: Preferred size.
"""
def __init__(
self,
min: int | None = None,
max: int | None = None,
weight: int | None = None,
preferred: int | None = None,
) -> None:
if weight is not None:
assert weight >= 0 # Also cannot be a float.
assert min is None or min >= 0
assert max is None or max >= 0
assert preferred is None or preferred >= 0
self.min_specified = min is not None
self.max_specified = max is not None
self.preferred_specified = preferred is not None
self.weight_specified = weight is not None
if min is None:
min = 0 # Smallest possible value.
if max is None: # 0-values are allowed, so use "is None"
max = 1000**10 # Something huge.
if preferred is None:
preferred = min
if weight is None:
weight = 1
self.min = min
self.max = max
self.preferred = preferred
self.weight = weight
# Don't allow situations where max < min. (This would be a bug.)
if max < min:
raise ValueError("Invalid Dimension: max < min.")
# Make sure that the 'preferred' size is always in the min..max range.
if self.preferred < self.min:
self.preferred = self.min
if self.preferred > self.max:
self.preferred = self.max
def exact(cls, amount: int) -> Dimension:
"""
Return a :class:`.Dimension` with an exact size. (min, max and
preferred set to ``amount``).
"""
return cls(min=amount, max=amount, preferred=amount)
def zero(cls) -> Dimension:
"""
Create a dimension that represents a zero size. (Used for 'invisible'
controls.)
"""
return cls.exact(amount=0)
def is_zero(self) -> bool:
"True if this `Dimension` represents a zero size."
return self.preferred == 0 or self.max == 0
def __repr__(self) -> str:
fields = []
if self.min_specified:
fields.append("min=%r" % self.min)
if self.max_specified:
fields.append("max=%r" % self.max)
if self.preferred_specified:
fields.append("preferred=%r" % self.preferred)
if self.weight_specified:
fields.append("weight=%r" % self.weight)
return "Dimension(%s)" % ", ".join(fields)
The provided code snippet includes necessary dependencies for implementing the `max_layout_dimensions` function. Write a Python function `def max_layout_dimensions(dimensions: list[Dimension]) -> Dimension` to solve the following problem:
Take the maximum of a list of :class:`.Dimension` instances. Used when we have a HSplit/VSplit, and we want to get the best width/height.)
Here is the function:
def max_layout_dimensions(dimensions: list[Dimension]) -> Dimension:
"""
Take the maximum of a list of :class:`.Dimension` instances.
Used when we have a HSplit/VSplit, and we want to get the best width/height.)
"""
if not len(dimensions):
return Dimension.zero()
# If all dimensions are size zero. Return zero.
# (This is important for HSplit/VSplit, to report the right values to their
# parent when all children are invisible.)
if all(d.is_zero() for d in dimensions):
return dimensions[0]
# Ignore empty dimensions. (They should not reduce the size of others.)
dimensions = [d for d in dimensions if not d.is_zero()]
if dimensions:
# Take the highest minimum dimension.
min_ = max(d.min for d in dimensions)
# For the maximum, we would prefer not to go larger than then smallest
# 'max' value, unless other dimensions have a bigger preferred value.
# This seems to work best:
# - We don't want that a widget with a small height in a VSplit would
# shrink other widgets in the split.
# If it doesn't work well enough, then it's up to the UI designer to
# explicitly pass dimensions.
max_ = min(d.max for d in dimensions)
max_ = max(max_, max(d.preferred for d in dimensions))
# Make sure that min>=max. In some scenarios, when certain min..max
# ranges don't have any overlap, we can end up in such an impossible
# situation. In that case, give priority to the max value.
# E.g. taking (1..5) and (8..9) would return (8..5). Instead take (8..8).
if min_ > max_:
max_ = min_
preferred = max(d.preferred for d in dimensions)
return Dimension(min=min_, max=max_, preferred=preferred)
else:
return Dimension() | Take the maximum of a list of :class:`.Dimension` instances. Used when we have a HSplit/VSplit, and we want to get the best width/height.) |
172,176 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or smaller, it tries to keep in
between min and max.
:param min: Minimum size.
:param max: Maximum size.
:param weight: For a VSplit/HSplit, the actual size will be determined
by taking the proportion of weights from all the children.
E.g. When there are two children, one with a weight of 1,
and the other with a weight of 2, the second will always be
twice as big as the first, if the min/max values allow it.
:param preferred: Preferred size.
"""
def __init__(
self,
min: int | None = None,
max: int | None = None,
weight: int | None = None,
preferred: int | None = None,
) -> None:
if weight is not None:
assert weight >= 0 # Also cannot be a float.
assert min is None or min >= 0
assert max is None or max >= 0
assert preferred is None or preferred >= 0
self.min_specified = min is not None
self.max_specified = max is not None
self.preferred_specified = preferred is not None
self.weight_specified = weight is not None
if min is None:
min = 0 # Smallest possible value.
if max is None: # 0-values are allowed, so use "is None"
max = 1000**10 # Something huge.
if preferred is None:
preferred = min
if weight is None:
weight = 1
self.min = min
self.max = max
self.preferred = preferred
self.weight = weight
# Don't allow situations where max < min. (This would be a bug.)
if max < min:
raise ValueError("Invalid Dimension: max < min.")
# Make sure that the 'preferred' size is always in the min..max range.
if self.preferred < self.min:
self.preferred = self.min
if self.preferred > self.max:
self.preferred = self.max
def exact(cls, amount: int) -> Dimension:
"""
Return a :class:`.Dimension` with an exact size. (min, max and
preferred set to ``amount``).
"""
return cls(min=amount, max=amount, preferred=amount)
def zero(cls) -> Dimension:
"""
Create a dimension that represents a zero size. (Used for 'invisible'
controls.)
"""
return cls.exact(amount=0)
def is_zero(self) -> bool:
"True if this `Dimension` represents a zero size."
return self.preferred == 0 or self.max == 0
def __repr__(self) -> str:
fields = []
if self.min_specified:
fields.append("min=%r" % self.min)
if self.max_specified:
fields.append("max=%r" % self.max)
if self.preferred_specified:
fields.append("preferred=%r" % self.preferred)
if self.weight_specified:
fields.append("weight=%r" % self.weight)
return "Dimension(%s)" % ", ".join(fields)
AnyDimension = Union[
None, # None is a valid dimension that will fit anything.
int,
Dimension,
# Callable[[], 'AnyDimension'] # Recursive definition not supported by mypy.
Callable[[], Any],
]
The provided code snippet includes necessary dependencies for implementing the `to_dimension` function. Write a Python function `def to_dimension(value: AnyDimension) -> Dimension` to solve the following problem:
Turn the given object into a `Dimension` object.
Here is the function:
def to_dimension(value: AnyDimension) -> Dimension:
"""
Turn the given object into a `Dimension` object.
"""
if value is None:
return Dimension()
if isinstance(value, int):
return Dimension.exact(value)
if isinstance(value, Dimension):
return value
if callable(value):
return to_dimension(value())
raise ValueError("Not an integer or Dimension object.") | Turn the given object into a `Dimension` object. |
172,177 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or smaller, it tries to keep in
between min and max.
:param min: Minimum size.
:param max: Maximum size.
:param weight: For a VSplit/HSplit, the actual size will be determined
by taking the proportion of weights from all the children.
E.g. When there are two children, one with a weight of 1,
and the other with a weight of 2, the second will always be
twice as big as the first, if the min/max values allow it.
:param preferred: Preferred size.
"""
def __init__(
self,
min: int | None = None,
max: int | None = None,
weight: int | None = None,
preferred: int | None = None,
) -> None:
if weight is not None:
assert weight >= 0 # Also cannot be a float.
assert min is None or min >= 0
assert max is None or max >= 0
assert preferred is None or preferred >= 0
self.min_specified = min is not None
self.max_specified = max is not None
self.preferred_specified = preferred is not None
self.weight_specified = weight is not None
if min is None:
min = 0 # Smallest possible value.
if max is None: # 0-values are allowed, so use "is None"
max = 1000**10 # Something huge.
if preferred is None:
preferred = min
if weight is None:
weight = 1
self.min = min
self.max = max
self.preferred = preferred
self.weight = weight
# Don't allow situations where max < min. (This would be a bug.)
if max < min:
raise ValueError("Invalid Dimension: max < min.")
# Make sure that the 'preferred' size is always in the min..max range.
if self.preferred < self.min:
self.preferred = self.min
if self.preferred > self.max:
self.preferred = self.max
def exact(cls, amount: int) -> Dimension:
"""
Return a :class:`.Dimension` with an exact size. (min, max and
preferred set to ``amount``).
"""
return cls(min=amount, max=amount, preferred=amount)
def zero(cls) -> Dimension:
"""
Create a dimension that represents a zero size. (Used for 'invisible'
controls.)
"""
return cls.exact(amount=0)
def is_zero(self) -> bool:
"True if this `Dimension` represents a zero size."
return self.preferred == 0 or self.max == 0
def __repr__(self) -> str:
fields = []
if self.min_specified:
fields.append("min=%r" % self.min)
if self.max_specified:
fields.append("max=%r" % self.max)
if self.preferred_specified:
fields.append("preferred=%r" % self.preferred)
if self.weight_specified:
fields.append("weight=%r" % self.weight)
return "Dimension(%s)" % ", ".join(fields)
AnyDimension = Union[
None, # None is a valid dimension that will fit anything.
int,
Dimension,
# Callable[[], 'AnyDimension'] # Recursive definition not supported by mypy.
Callable[[], Any],
]
The provided code snippet includes necessary dependencies for implementing the `is_dimension` function. Write a Python function `def is_dimension(value: object) -> TypeGuard[AnyDimension]` to solve the following problem:
Test whether the given value could be a valid dimension. (For usage in an assertion. It's not guaranteed in case of a callable.)
Here is the function:
def is_dimension(value: object) -> TypeGuard[AnyDimension]:
"""
Test whether the given value could be a valid dimension.
(For usage in an assertion. It's not guaranteed in case of a callable.)
"""
if value is None:
return True
if callable(value):
return True # Assume it's a callable that doesn't take arguments.
if isinstance(value, (int, Dimension)):
return True
return False | Test whether the given value could be a valid dimension. (For usage in an assertion. It's not guaranteed in case of a callable.) |
172,178 | import base64
import json
import mimetypes
import os
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
import jinja2
import markupsafe
from jupyter_core.paths import jupyter_path
from traitlets import Bool, Unicode, default
from traitlets.config import Config
from jinja2.loaders import split_template_path
from nbformat import NotebookNode
from nbconvert.filters.highlight import Highlight2HTML
from nbconvert.filters.markdown_mistune import IPythonRenderer, MarkdownWithMath
from nbconvert.filters.widgetsdatatypefilter import WidgetsDataTypeFilter
from .templateexporter import TemplateExporter
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self: _P) -> _P: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]
) -> Optional[bool]: ...
def cwd(cls: Type[_P]) -> _P: ...
def stat(self) -> os.stat_result: ...
def chmod(self, mode: int) -> None: ...
def exists(self) -> bool: ...
def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def group(self) -> str: ...
def is_dir(self) -> bool: ...
def is_file(self) -> bool: ...
if sys.version_info >= (3, 7):
def is_mount(self) -> bool: ...
def is_symlink(self) -> bool: ...
def is_socket(self) -> bool: ...
def is_fifo(self) -> bool: ...
def is_block_device(self) -> bool: ...
def is_char_device(self) -> bool: ...
def iterdir(self: _P) -> Generator[_P, None, None]: ...
def lchmod(self, mode: int) -> None: ...
def lstat(self) -> os.stat_result: ...
def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ...
# Adapted from builtins.open
# Text mode: always returns a TextIOWrapper
def open(
self,
mode: OpenTextMode = ...,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> TextIOWrapper: ...
# Unbuffered binary mode: returns a FileIO
def open(
self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ...
) -> FileIO: ...
# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter
def open(
self,
mode: OpenBinaryModeUpdating,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedRandom: ...
def open(
self,
mode: OpenBinaryModeWriting,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedWriter: ...
def open(
self,
mode: OpenBinaryModeReading,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedReader: ...
# Buffering cannot be determined: fall back to BinaryIO
def open(
self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ...
) -> BinaryIO: ...
# Fallback if mode is not specified
def open(
self,
mode: str,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> IO[Any]: ...
def owner(self) -> str: ...
if sys.version_info >= (3, 9):
def readlink(self: _P) -> _P: ...
if sys.version_info >= (3, 8):
def rename(self: _P, target: Union[str, PurePath]) -> _P: ...
def replace(self: _P, target: Union[str, PurePath]) -> _P: ...
else:
def rename(self, target: Union[str, PurePath]) -> None: ...
def replace(self, target: Union[str, PurePath]) -> None: ...
def resolve(self: _P, strict: bool = ...) -> _P: ...
def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def rmdir(self) -> None: ...
def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ...
def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
if sys.version_info >= (3, 8):
def unlink(self, missing_ok: bool = ...) -> None: ...
else:
def unlink(self) -> None: ...
def home(cls: Type[_P]) -> _P: ...
def absolute(self: _P) -> _P: ...
def expanduser(self: _P) -> _P: ...
def read_bytes(self) -> bytes: ...
def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ...
def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ...
def write_bytes(self, data: bytes) -> int: ...
def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ...
if sys.version_info >= (3, 8):
def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ...
def jupyter_path(*subdirs: str) -> List[str]:
"""Return a list of directories to search for data files
JUPYTER_PATH environment variable has highest priority.
If the JUPYTER_PREFER_ENV_PATH environment variable is set, the environment-level
directories will have priority over user-level directories.
If the Python site.ENABLE_USER_SITE variable is True, we also add the
appropriate Python user site subdirectory to the user-level directories.
If ``*subdirs`` are given, that subdirectory will be added to each element.
Examples:
>>> jupyter_path()
['~/.local/jupyter', '/usr/local/share/jupyter']
>>> jupyter_path('kernels')
['~/.local/jupyter/kernels', '/usr/local/share/jupyter/kernels']
"""
paths: List[str] = []
# highest priority is explicit environment variable
if os.environ.get("JUPYTER_PATH"):
paths.extend(p.rstrip(os.sep) for p in os.environ["JUPYTER_PATH"].split(os.pathsep))
# Next is environment or user, depending on the JUPYTER_PREFER_ENV_PATH flag
user = [jupyter_data_dir()]
if site.ENABLE_USER_SITE:
# Check if site.getuserbase() exists to be compatible with virtualenv,
# which often does not have this method.
userbase: Optional[str]
userbase = site.getuserbase() if hasattr(site, "getuserbase") else site.USER_BASE
if userbase:
userdir = os.path.join(userbase, "share", "jupyter")
if userdir not in user:
user.append(userdir)
env = [p for p in ENV_JUPYTER_PATH if p not in SYSTEM_JUPYTER_PATH]
if prefer_environment_over_user():
paths.extend(env)
paths.extend(user)
else:
paths.extend(user)
paths.extend(env)
# finally, system
paths.extend(SYSTEM_JUPYTER_PATH)
# add subdir, if requested
if subdirs:
paths = [pjoin(p, *subdirs) for p in paths]
return paths
The provided code snippet includes necessary dependencies for implementing the `find_lab_theme` function. Write a Python function `def find_lab_theme(theme_name)` to solve the following problem:
Find a JupyterLab theme location by name. Parameters ---------- theme_name : str The name of the labextension theme you want to find. Raises ------ ValueError If the theme was not found, or if it was not specific enough. Returns ------- theme_name: str Full theme name (with scope, if any) labextension_path : Path The path to the found labextension on the system.
Here is the function:
def find_lab_theme(theme_name):
"""
Find a JupyterLab theme location by name.
Parameters
----------
theme_name : str
The name of the labextension theme you want to find.
Raises
------
ValueError
If the theme was not found, or if it was not specific enough.
Returns
-------
theme_name: str
Full theme name (with scope, if any)
labextension_path : Path
The path to the found labextension on the system.
"""
paths = jupyter_path("labextensions")
matching_themes = []
theme_path = None
for path in paths:
for dirpath, dirnames, filenames in os.walk(path):
# If it's a federated labextension that contains themes
if "package.json" in filenames and "themes" in dirnames:
# TODO Find the theme name in the JS code instead?
# TODO Find if it's a light or dark theme?
with open(Path(dirpath) / "package.json", encoding="utf-8") as fobj:
labext_name = json.loads(fobj.read())["name"]
if labext_name == theme_name or theme_name in labext_name.split("/"):
matching_themes.append(labext_name)
full_theme_name = labext_name
theme_path = Path(dirpath) / "themes" / labext_name
if len(matching_themes) == 0:
msg = f'Could not find lab theme "{theme_name}"'
raise ValueError(msg)
if len(matching_themes) > 1:
msg = (
f'Found multiple themes matching "{theme_name}": {matching_themes}. '
"Please be more specific about which theme you want to use."
)
raise ValueError(msg)
return full_theme_name, theme_path | Find a JupyterLab theme location by name. Parameters ---------- theme_name : str The name of the labextension theme you want to find. Raises ------ ValueError If the theme was not found, or if it was not specific enough. Returns ------- theme_name: str Full theme name (with scope, if any) labextension_path : Path The path to the found labextension on the system. |
172,179 | import os
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from traitlets import Bool, Instance, Integer, List, Unicode, default
from nbconvert.utils import _contextlib_chdir
from .latex import LatexExporter
The provided code snippet includes necessary dependencies for implementing the `prepend_to_env_search_path` function. Write a Python function `def prepend_to_env_search_path(varname, value, envdict)` to solve the following problem:
Add value to the environment variable varname in envdict e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ)
Here is the function:
def prepend_to_env_search_path(varname, value, envdict):
"""Add value to the environment variable varname in envdict
e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ)
"""
if not value:
return # Nothing to add
envdict[varname] = value + os.pathsep + envdict.get(varname, "") | Add value to the environment variable varname in envdict e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ) |
172,180 | import html
import json
import os
import typing as t
import uuid
import warnings
from pathlib import Path
from jinja2 import (
BaseLoader,
ChoiceLoader,
DictLoader,
Environment,
FileSystemLoader,
TemplateNotFound,
)
from jupyter_core.paths import jupyter_path
from nbformat import NotebookNode
from traitlets import Bool, Dict, HasTraits, List, Unicode, default, observe, validate
from traitlets.config import Config
from traitlets.utils.importstring import import_item
from nbconvert import filters
from .exporter import Exporter
The provided code snippet includes necessary dependencies for implementing the `recursive_update` function. Write a Python function `def recursive_update(target, new)` to solve the following problem:
Recursively update one dictionary using another. None values will delete their keys.
Here is the function:
def recursive_update(target, new):
"""Recursively update one dictionary using another.
None values will delete their keys.
"""
for k, v in new.items():
if isinstance(v, dict):
if k not in target:
target[k] = {}
recursive_update(target[k], v)
if not target[k]:
# Prune empty subdicts
del target[k]
elif v is None:
target.pop(k, None)
else:
target[k] = v
return target # return for convenience | Recursively update one dictionary using another. None values will delete their keys. |
172,181 | import html
import json
import os
import typing as t
import uuid
import warnings
from pathlib import Path
from jinja2 import (
BaseLoader,
ChoiceLoader,
DictLoader,
Environment,
FileSystemLoader,
TemplateNotFound,
)
from jupyter_core.paths import jupyter_path
from nbformat import NotebookNode
from traitlets import Bool, Dict, HasTraits, List, Unicode, default, observe, validate
from traitlets.config import Config
from traitlets.utils.importstring import import_item
from nbconvert import filters
from .exporter import Exporter
The provided code snippet includes necessary dependencies for implementing the `deprecated` function. Write a Python function `def deprecated(msg)` to solve the following problem:
Emit a deprecation warning.
Here is the function:
def deprecated(msg):
"""Emit a deprecation warning."""
warnings.warn(msg, DeprecationWarning) | Emit a deprecation warning. |
172,182 | import os
import sys
from nbformat import NotebookNode
from traitlets.config import get_config
from traitlets.log import get_logger
from traitlets.utils.importstring import import_item
from .exporter import Exporter
class Exporter(LoggingConfigurable):
"""
Class containing methods that sequentially run a list of preprocessors on a
NotebookNode object and then return the modified NotebookNode object and
accompanying resources dict.
"""
enabled = Bool(True, help="Disable this exporter (and any exporters inherited from it).").tag(
config=True
)
file_extension = FilenameExtension(
help="Extension of the file that should be written to disk"
).tag(config=True)
optimistic_validation = Bool(
False,
help="Reduces the number of validation steps so that it only occurs after all preprocesors have run.",
).tag(config=True)
# MIME type of the result file, for HTTP response headers.
# This is *not* a traitlet, because we want to be able to access it from
# the class, not just on instances.
output_mimetype = ""
# Should this converter be accessible from the notebook front-end?
# If so, should be a friendly name to display (and possibly translated).
export_from_notebook: str = None # type:ignore
# Configurability, allows the user to easily add filters and preprocessors.
preprocessors = List(help="""List of preprocessors, by name or namespace, to enable.""").tag(
config=True
)
_preprocessors = List()
default_preprocessors = List(
[
"nbconvert.preprocessors.TagRemovePreprocessor",
"nbconvert.preprocessors.RegexRemovePreprocessor",
"nbconvert.preprocessors.ClearOutputPreprocessor",
"nbconvert.preprocessors.ExecutePreprocessor",
"nbconvert.preprocessors.coalesce_streams",
"nbconvert.preprocessors.SVG2PDFPreprocessor",
"nbconvert.preprocessors.LatexPreprocessor",
"nbconvert.preprocessors.HighlightMagicsPreprocessor",
"nbconvert.preprocessors.ExtractOutputPreprocessor",
"nbconvert.preprocessors.ClearMetadataPreprocessor",
],
help="""List of preprocessors available by default, by name, namespace,
instance, or type.""",
).tag(config=True)
def __init__(self, config=None, **kw):
"""
Public constructor
Parameters
----------
config : ``traitlets.config.Config``
User configuration instance.
`**kw`
Additional keyword arguments passed to parent __init__
"""
with_default_config = self.default_config
if config:
with_default_config.merge(config)
super().__init__(config=with_default_config, **kw)
self._init_preprocessors()
self._nb_metadata = {}
def default_config(self):
return Config()
def from_notebook_node(
self, nb: NotebookNode, resources: t.Optional[t.Any] = None, **kw: t.Any
) -> t.Tuple[NotebookNode, t.Dict]:
"""
Convert a notebook from a notebook node instance.
Parameters
----------
nb : :class:`~nbformat.NotebookNode`
Notebook node (dict-like with attr-access)
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
`**kw`
Ignored
"""
nb_copy = copy.deepcopy(nb)
resources = self._init_resources(resources)
if "language" in nb["metadata"]:
resources["language"] = nb["metadata"]["language"].lower()
# Preprocess
nb_copy, resources = self._preprocess(nb_copy, resources)
notebook_name = ""
if resources is not None:
name = resources.get("metadata", {}).get("name", "")
path = resources.get("metadata", {}).get("path", "")
notebook_name = os.path.join(path, name)
self._nb_metadata[notebook_name] = nb_copy.metadata
return nb_copy, resources
def from_filename(
self, filename: str, resources: t.Optional[dict] = None, **kw: t.Any
) -> t.Tuple[NotebookNode, t.Dict]:
"""
Convert a notebook from a notebook file.
Parameters
----------
filename : str
Full filename of the notebook file to open and convert.
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
`**kw`
Ignored
"""
# Pull the metadata from the filesystem.
if resources is None:
resources = ResourcesDict()
if "metadata" not in resources or resources["metadata"] == "":
resources["metadata"] = ResourcesDict()
path, basename = os.path.split(filename)
notebook_name = os.path.splitext(basename)[0]
resources["metadata"]["name"] = notebook_name
resources["metadata"]["path"] = path
modified_date = datetime.datetime.fromtimestamp(
os.path.getmtime(filename), tz=datetime.timezone.utc
)
# datetime.strftime date format for ipython
if sys.platform == "win32":
date_format = "%B %d, %Y"
else:
date_format = "%B %-d, %Y"
resources["metadata"]["modified_date"] = modified_date.strftime(date_format)
with open(filename, encoding="utf-8") as f:
return self.from_file(f, resources=resources, **kw)
def from_file(
self, file_stream: t.Any, resources: t.Optional[dict] = None, **kw: t.Any
) -> t.Tuple[NotebookNode, dict]:
"""
Convert a notebook from a notebook file.
Parameters
----------
file_stream : file-like object
Notebook file-like object to convert.
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
`**kw`
Ignored
"""
return self.from_notebook_node(
nbformat.read(file_stream, as_version=4), resources=resources, **kw
)
def register_preprocessor(self, preprocessor, enabled=False):
"""
Register a preprocessor.
Preprocessors are classes that act upon the notebook before it is
passed into the Jinja templating engine. Preprocessors are also
capable of passing additional information to the Jinja
templating engine.
Parameters
----------
preprocessor : `nbconvert.preprocessors.Preprocessor`
A dotted module name, a type, or an instance
enabled : bool
Mark the preprocessor as enabled
"""
if preprocessor is None:
msg = "preprocessor must not be None"
raise TypeError(msg)
isclass = isinstance(preprocessor, type)
constructed = not isclass
# Handle preprocessor's registration based on it's type
if constructed and isinstance(
preprocessor,
str,
):
# Preprocessor is a string, import the namespace and recursively call
# this register_preprocessor method
preprocessor_cls = import_item(preprocessor)
return self.register_preprocessor(preprocessor_cls, enabled)
if constructed and hasattr(preprocessor, "__call__"): # noqa
# Preprocessor is a function, no need to construct it.
# Register and return the preprocessor.
if enabled:
preprocessor.enabled = True
self._preprocessors.append(preprocessor)
return preprocessor
elif isclass and issubclass(preprocessor, HasTraits):
# Preprocessor is configurable. Make sure to pass in new default for
# the enabled flag if one was specified.
self.register_preprocessor(preprocessor(parent=self), enabled)
elif isclass:
# Preprocessor is not configurable, construct it
self.register_preprocessor(preprocessor(), enabled)
else:
# Preprocessor is an instance of something without a __call__
# attribute.
raise TypeError(
"preprocessor must be callable or an importable constructor, got %r" % preprocessor
)
def _init_preprocessors(self):
"""
Register all of the preprocessors needed for this exporter, disabled
unless specified explicitly.
"""
self._preprocessors = []
# Load default preprocessors (not necessarily enabled by default).
for preprocessor in self.default_preprocessors:
self.register_preprocessor(preprocessor)
# Load user-specified preprocessors. Enable by default.
for preprocessor in self.preprocessors:
self.register_preprocessor(preprocessor, enabled=True)
def _init_resources(self, resources):
# Make sure the resources dict is of ResourcesDict type.
if resources is None:
resources = ResourcesDict()
if not isinstance(resources, ResourcesDict):
new_resources = ResourcesDict()
new_resources.update(resources)
resources = new_resources
# Make sure the metadata extension exists in resources
if "metadata" in resources:
if not isinstance(resources["metadata"], ResourcesDict):
new_metadata = ResourcesDict()
new_metadata.update(resources["metadata"])
resources["metadata"] = new_metadata
else:
resources["metadata"] = ResourcesDict()
if not resources["metadata"]["name"]:
resources["metadata"]["name"] = "Notebook"
# Set the output extension
resources["output_extension"] = self.file_extension
return resources
def _validate_preprocessor(self, nbc, preprocessor):
try:
nbformat.validate(nbc, relax_add_props=True)
except nbformat.ValidationError:
self.log.error("Notebook is invalid after preprocessor %s", preprocessor)
raise
def _preprocess(self, nb, resources):
"""
Preprocess the notebook before passing it into the Jinja engine.
To preprocess the notebook is to successively apply all the
enabled preprocessors. Output from each preprocessor is passed
along to the next one.
Parameters
----------
nb : notebook node
notebook that is being exported.
resources : a dict of additional resources that
can be accessed read/write by preprocessors
"""
# Do a copy.deepcopy first,
# we are never safe enough with what the preprocessors could do.
nbc = copy.deepcopy(nb)
resc = copy.deepcopy(resources)
if hasattr(validator, "normalize"):
_, nbc = validator.normalize(nbc)
# Run each preprocessor on the notebook. Carry the output along
# to each preprocessor
for preprocessor in self._preprocessors:
nbc, resc = preprocessor(nbc, resc)
if not self.optimistic_validation:
self._validate_preprocessor(nbc, preprocessor)
if self.optimistic_validation:
self._validate_preprocessor(nbc, preprocessor)
return nbc, resc
The provided code snippet includes necessary dependencies for implementing the `export` function. Write a Python function `def export(exporter, nb, **kw)` to solve the following problem:
Export a notebook object using specific exporter class. Parameters ---------- exporter : ``Exporter`` class or instance Class or instance of the exporter that should be used. If the method initializes its own instance of the class, it is ASSUMED that the class type provided exposes a constructor (``__init__``) with the same signature as the base Exporter class. nb : :class:`~nbformat.NotebookNode` The notebook to export. config : config (optional, keyword arg) User configuration instance. resources : dict (optional, keyword arg) Resources used in the conversion process. Returns ------- tuple output : str The resulting converted notebook. resources : dictionary Dictionary of resources used prior to and during the conversion process.
Here is the function:
def export(exporter, nb, **kw):
"""
Export a notebook object using specific exporter class.
Parameters
----------
exporter : ``Exporter`` class or instance
Class or instance of the exporter that should be used. If the
method initializes its own instance of the class, it is ASSUMED that
the class type provided exposes a constructor (``__init__``) with the same
signature as the base Exporter class.
nb : :class:`~nbformat.NotebookNode`
The notebook to export.
config : config (optional, keyword arg)
User configuration instance.
resources : dict (optional, keyword arg)
Resources used in the conversion process.
Returns
-------
tuple
output : str
The resulting converted notebook.
resources : dictionary
Dictionary of resources used prior to and during the conversion
process.
"""
# Check arguments
if exporter is None:
msg = "Exporter is None"
raise TypeError(msg)
elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
msg = "exporter does not inherit from Exporter (base)"
raise TypeError(msg)
if nb is None:
msg = "nb is None"
raise TypeError(msg)
# Create the exporter
resources = kw.pop("resources", None)
exporter_instance = exporter if isinstance(exporter, Exporter) else exporter(**kw)
# Try to convert the notebook using the appropriate conversion function.
if isinstance(nb, NotebookNode):
output, resources = exporter_instance.from_notebook_node(nb, resources)
elif isinstance(nb, (str,)):
output, resources = exporter_instance.from_filename(nb, resources)
else:
output, resources = exporter_instance.from_file(nb, resources)
return output, resources | Export a notebook object using specific exporter class. Parameters ---------- exporter : ``Exporter`` class or instance Class or instance of the exporter that should be used. If the method initializes its own instance of the class, it is ASSUMED that the class type provided exposes a constructor (``__init__``) with the same signature as the base Exporter class. nb : :class:`~nbformat.NotebookNode` The notebook to export. config : config (optional, keyword arg) User configuration instance. resources : dict (optional, keyword arg) Resources used in the conversion process. Returns ------- tuple output : str The resulting converted notebook. resources : dictionary Dictionary of resources used prior to and during the conversion process. |
172,183 | import json
import os
import sys
from binascii import a2b_base64
from mimetypes import guess_extension
from textwrap import dedent
from traitlets import Set, Unicode
from .base import Preprocessor
def guess_extension(type: str, strict: bool = ...) -> Optional[str]: ...
The provided code snippet includes necessary dependencies for implementing the `guess_extension_without_jpe` function. Write a Python function `def guess_extension_without_jpe(mimetype)` to solve the following problem:
This function fixes a problem with '.jpe' extensions of jpeg images which are then not recognised by latex. For any other case, the function works in the same way as mimetypes.guess_extension
Here is the function:
def guess_extension_without_jpe(mimetype):
"""
This function fixes a problem with '.jpe' extensions
of jpeg images which are then not recognised by latex.
For any other case, the function works in the same way
as mimetypes.guess_extension
"""
ext = guess_extension(mimetype)
if ext == ".jpe":
ext = ".jpeg"
return ext | This function fixes a problem with '.jpe' extensions of jpeg images which are then not recognised by latex. For any other case, the function works in the same way as mimetypes.guess_extension |
172,184 | import json
import os
import sys
from binascii import a2b_base64
from mimetypes import guess_extension
from textwrap import dedent
from traitlets import Set, Unicode
from .base import Preprocessor
The provided code snippet includes necessary dependencies for implementing the `platform_utf_8_encode` function. Write a Python function `def platform_utf_8_encode(data)` to solve the following problem:
Encode data based on platform.
Here is the function:
def platform_utf_8_encode(data):
"""Encode data based on platform."""
if isinstance(data, str):
if sys.platform == "win32":
data = data.replace("\n", "\r\n")
data = data.encode("utf-8")
return data | Encode data based on platform. |
172,185 | import functools
import re
from traitlets.log import get_logger
def get_logger():
"""Grab the global logger instance.
If a global Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
if _logger is None:
from .config import Application
if Application.initialized():
_logger = Application.instance().log
else:
_logger = logging.getLogger("traitlets")
# Add a NullHandler to silence warnings about not being
# initialized, per best practice for libraries.
_logger.addHandler(logging.NullHandler())
return _logger
The provided code snippet includes necessary dependencies for implementing the `cell_preprocessor` function. Write a Python function `def cell_preprocessor(function)` to solve the following problem:
Wrap a function to be executed on all cells of a notebook The wrapped function should have these parameters: cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. index : int Index of the cell being processed
Here is the function:
def cell_preprocessor(function):
"""
Wrap a function to be executed on all cells of a notebook
The wrapped function should have these parameters:
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
index : int
Index of the cell being processed
"""
@functools.wraps(function)
def wrappedfunc(nb, resources):
get_logger().debug("Applying preprocessor: %s", function.__name__)
for index, cell in enumerate(nb.cells):
nb.cells[index], resources = function(cell, resources, index)
return nb, resources
return wrappedfunc | Wrap a function to be executed on all cells of a notebook The wrapped function should have these parameters: cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. index : int Index of the cell being processed |
172,186 | import functools
import re
from traitlets.log import get_logger
cr_pat = re.compile(r".*\r(?=[^\n])")
The provided code snippet includes necessary dependencies for implementing the `coalesce_streams` function. Write a Python function `def coalesce_streams(cell, resources, index)` to solve the following problem:
Merge consecutive sequences of stream output into single stream to prevent extra newlines inserted at flush calls Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows transformers to pass variables into the Jinja engine. index : int Index of the cell being processed
Here is the function:
def coalesce_streams(cell, resources, index):
"""
Merge consecutive sequences of stream output into single stream
to prevent extra newlines inserted at flush calls
Parameters
----------
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary
Additional resources used in the conversion process. Allows
transformers to pass variables into the Jinja engine.
index : int
Index of the cell being processed
"""
outputs = cell.get("outputs", [])
if not outputs:
return cell, resources
last = outputs[0]
new_outputs = [last]
for output in outputs[1:]:
if (
output.output_type == "stream"
and last.output_type == "stream"
and last.name == output.name
):
last.text += output.text
else:
new_outputs.append(output)
last = output
# process \r characters
for output in new_outputs:
if output.output_type == "stream" and "\r" in output.text:
output.text = cr_pat.sub("", output.text)
cell.outputs = new_outputs
return cell, resources | Merge consecutive sequences of stream output into single stream to prevent extra newlines inserted at flush calls Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows transformers to pass variables into the Jinja engine. index : int Index of the cell being processed |
172,187 | import typing as t
from jupyter_client.manager import KernelManager
from nbclient import NotebookClient
from nbclient import execute as _execute
from nbclient.exceptions import CellExecutionError
from nbformat import NotebookNode
from .base import Preprocessor
The provided code snippet includes necessary dependencies for implementing the `executenb` function. Write a Python function `def executenb(*args, **kwargs)` to solve the following problem:
DEPRECATED.
Here is the function:
def executenb(*args, **kwargs):
"""DEPRECATED."""
from warnings import warn
warn(
"The 'nbconvert.preprocessors.execute.executenb' function was moved to nbclient.execute. "
"We recommend importing that library directly.",
FutureWarning,
)
return _execute(*args, **kwargs) | DEPRECATED. |
172,188 | import re
from .pandoc import convert_pandoc
The provided code snippet includes necessary dependencies for implementing the `markdown2html_mistune` function. Write a Python function `def markdown2html_mistune(source)` to solve the following problem:
mistune is unavailable, raise ImportError
Here is the function:
def markdown2html_mistune(source):
"""mistune is unavailable, raise ImportError"""
raise ImportError("markdown2html requires mistune: %s" % _mistune_import_error) | mistune is unavailable, raise ImportError |
172,189 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
source : string
Input string, assumed to be valid in from_format.
from_format : string
Pandoc format of source.
to_format : string
Pandoc format for output.
Returns
-------
out : string
Output as returned by pandoc.
"""
return pandoc(source, from_format, to_format, extra_args=extra_args)
The provided code snippet includes necessary dependencies for implementing the `markdown2latex` function. Write a Python function `def markdown2latex(source, markup="markdown", extra_args=None)` to solve the following problem:
Convert a markdown string to LaTeX via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid markdown. markup : string Markup used by pandoc's reader default : pandoc extended markdown (see https://pandoc.org/README.html#pandocs-markdown) Returns ------- out : string Output as returned by pandoc.
Here is the function:
def markdown2latex(source, markup="markdown", extra_args=None):
"""
Convert a markdown string to LaTeX via pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
source : string
Input string, assumed to be valid markdown.
markup : string
Markup used by pandoc's reader
default : pandoc extended markdown
(see https://pandoc.org/README.html#pandocs-markdown)
Returns
-------
out : string
Output as returned by pandoc.
"""
return convert_pandoc(source, markup, "latex", extra_args=extra_args) | Convert a markdown string to LaTeX via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid markdown. markup : string Markup used by pandoc's reader default : pandoc extended markdown (see https://pandoc.org/README.html#pandocs-markdown) Returns ------- out : string Output as returned by pandoc. |
172,190 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
source : string
Input string, assumed to be valid in from_format.
from_format : string
Pandoc format of source.
to_format : string
Pandoc format for output.
Returns
-------
out : string
Output as returned by pandoc.
"""
return pandoc(source, from_format, to_format, extra_args=extra_args)
The provided code snippet includes necessary dependencies for implementing the `markdown2html_pandoc` function. Write a Python function `def markdown2html_pandoc(source, extra_args=None)` to solve the following problem:
Convert a markdown string to HTML via pandoc.
Here is the function:
def markdown2html_pandoc(source, extra_args=None):
"""
Convert a markdown string to HTML via pandoc.
"""
extra_args = extra_args or ["--mathjax"]
return convert_pandoc(source, "markdown", "html", extra_args=extra_args) | Convert a markdown string to HTML via pandoc. |
172,191 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
source : string
Input string, assumed to be valid in from_format.
from_format : string
Pandoc format of source.
to_format : string
Pandoc format for output.
Returns
-------
out : string
Output as returned by pandoc.
"""
return pandoc(source, from_format, to_format, extra_args=extra_args)
The provided code snippet includes necessary dependencies for implementing the `markdown2asciidoc` function. Write a Python function `def markdown2asciidoc(source, extra_args=None)` to solve the following problem:
Convert a markdown string to asciidoc via pandoc
Here is the function:
def markdown2asciidoc(source, extra_args=None):
"""Convert a markdown string to asciidoc via pandoc"""
extra_args = extra_args or ["--atx-headers"]
asciidoc = convert_pandoc(source, "markdown", "asciidoc", extra_args=extra_args)
# workaround for https://github.com/jgm/pandoc/issues/3068
if "__" in asciidoc:
asciidoc = re.sub(r"\b__([\w \n-]+)__([:,.\n\)])", r"_\1_\2", asciidoc)
# urls / links:
asciidoc = re.sub(r"\(__([\w\/-:\.]+)__\)", r"(_\1_)", asciidoc)
return asciidoc | Convert a markdown string to asciidoc via pandoc |
172,192 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
source : string
Input string, assumed to be valid in from_format.
from_format : string
Pandoc format of source.
to_format : string
Pandoc format for output.
Returns
-------
out : string
Output as returned by pandoc.
"""
return pandoc(source, from_format, to_format, extra_args=extra_args)
The provided code snippet includes necessary dependencies for implementing the `markdown2rst` function. Write a Python function `def markdown2rst(source, extra_args=None)` to solve the following problem:
Convert a markdown string to ReST via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid markdown. Returns ------- out : string Output as returned by pandoc.
Here is the function:
def markdown2rst(source, extra_args=None):
"""
Convert a markdown string to ReST via pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
source : string
Input string, assumed to be valid markdown.
Returns
-------
out : string
Output as returned by pandoc.
"""
return convert_pandoc(source, "markdown", "rst", extra_args=extra_args) | Convert a markdown string to ReST via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid markdown. Returns ------- out : string Output as returned by pandoc. |
172,193 | import re
import markupsafe
_ANSI_RE = re.compile("\x1b\\[(.*?)([@-~])")
The provided code snippet includes necessary dependencies for implementing the `strip_ansi` function. Write a Python function `def strip_ansi(source)` to solve the following problem:
Remove ANSI escape codes from text. Parameters ---------- source : str Source to remove the ANSI from
Here is the function:
def strip_ansi(source):
"""
Remove ANSI escape codes from text.
Parameters
----------
source : str
Source to remove the ANSI from
"""
return _ANSI_RE.sub("", source) | Remove ANSI escape codes from text. Parameters ---------- source : str Source to remove the ANSI from |
172,194 | import re
import markupsafe
def _htmlconverter(fg, bg, bold, underline, inverse):
"""
Return start and end tags for given foreground/background/bold/underline.
"""
if (fg, bg, bold, underline, inverse) == (None, None, False, False, False):
return "", ""
classes = []
styles = []
if inverse:
fg, bg = bg, fg
if isinstance(fg, int):
classes.append(_ANSI_COLORS[fg] + "-fg")
elif fg:
styles.append("color: rgb({},{},{})".format(*fg))
elif inverse:
classes.append("ansi-default-inverse-fg")
if isinstance(bg, int):
classes.append(_ANSI_COLORS[bg] + "-bg")
elif bg:
styles.append("background-color: rgb({},{},{})".format(*bg))
elif inverse:
classes.append("ansi-default-inverse-bg")
if bold:
classes.append("ansi-bold")
if underline:
classes.append("ansi-underline")
starttag = "<span"
if classes:
starttag += ' class="' + " ".join(classes) + '"'
if styles:
starttag += ' style="' + "; ".join(styles) + '"'
starttag += ">"
return starttag, "</span>"
def _ansi2anything(text, converter): # noqa
r"""
Convert ANSI colors to HTML or LaTeX.
See https://en.wikipedia.org/wiki/ANSI_escape_code
Accepts codes like '\x1b[32m' (red) and '\x1b[1;32m' (bold, red).
Non-color escape sequences (not ending with 'm') are filtered out.
Ideally, this should have the same behavior as the function
fixConsole() in notebook/notebook/static/base/js/utils.js.
"""
fg, bg = None, None
bold = False
underline = False
inverse = False
numbers = []
out = []
while text:
m = _ANSI_RE.search(text)
if m:
if m.group(2) == "m":
try:
# Empty code is same as code 0
numbers = [int(n) if n else 0 for n in m.group(1).split(";")]
except ValueError:
pass # Invalid color specification
else:
pass # Not a color code
chunk, text = text[: m.start()], text[m.end() :]
else:
chunk, text = text, ""
if chunk:
starttag, endtag = converter(
fg + 8 if bold and fg in range(8) else fg, # type:ignore
bg,
bold,
underline,
inverse,
)
out.append(starttag)
out.append(chunk)
out.append(endtag)
while numbers:
n = numbers.pop(0)
if n == 0:
# Code 0 (same as empty code): reset everything
fg = bg = None
bold = underline = inverse = False
elif n == 1:
bold = True
elif n == 4:
underline = True
elif n == 5:
# Code 5: blinking
bold = True
elif n == 7:
inverse = True
elif n in (21, 22):
bold = False
elif n == 24:
underline = False
elif n == 27:
inverse = False
elif 30 <= n <= 37:
fg = n - 30
elif n == 38:
try:
fg = _get_extended_color(numbers)
except ValueError:
numbers.clear()
elif n == 39:
fg = None
elif 40 <= n <= 47:
bg = n - 40
elif n == 48:
try:
bg = _get_extended_color(numbers)
except ValueError:
numbers.clear()
elif n == 49:
bg = None
elif 90 <= n <= 97:
fg = n - 90 + 8
elif 100 <= n <= 107:
bg = n - 100 + 8
else:
pass # Unknown codes are ignored
return "".join(out)
The provided code snippet includes necessary dependencies for implementing the `ansi2html` function. Write a Python function `def ansi2html(text)` to solve the following problem:
Convert ANSI colors to HTML colors. Parameters ---------- text : unicode Text containing ANSI colors to convert to HTML
Here is the function:
def ansi2html(text):
"""
Convert ANSI colors to HTML colors.
Parameters
----------
text : unicode
Text containing ANSI colors to convert to HTML
"""
text = markupsafe.escape(text)
return _ansi2anything(text, _htmlconverter) | Convert ANSI colors to HTML colors. Parameters ---------- text : unicode Text containing ANSI colors to convert to HTML |
172,195 | import re
import markupsafe
def _latexconverter(fg, bg, bold, underline, inverse):
"""
Return start and end markup given foreground/background/bold/underline.
"""
if (fg, bg, bold, underline, inverse) == (None, None, False, False, False):
return "", ""
starttag, endtag = "", ""
if inverse:
fg, bg = bg, fg
if isinstance(fg, int):
starttag += r"\textcolor{" + _ANSI_COLORS[fg] + "}{"
endtag = "}" + endtag
elif fg:
# See http://tex.stackexchange.com/a/291102/13684
starttag += r"\def\tcRGB{\textcolor[RGB]}\expandafter"
starttag += r"\tcRGB\expandafter{\detokenize{%s,%s,%s}}{" % fg
endtag = "}" + endtag
elif inverse:
starttag += r"\textcolor{ansi-default-inverse-fg}{"
endtag = "}" + endtag
if isinstance(bg, int):
starttag += r"\setlength{\fboxsep}{0pt}"
starttag += r"\colorbox{" + _ANSI_COLORS[bg] + "}{"
endtag = r"\strut}" + endtag
elif bg:
starttag += r"\setlength{\fboxsep}{0pt}"
# See http://tex.stackexchange.com/a/291102/13684
starttag += r"\def\cbRGB{\colorbox[RGB]}\expandafter"
starttag += r"\cbRGB\expandafter{\detokenize{%s,%s,%s}}{" % bg
endtag = r"\strut}" + endtag
elif inverse:
starttag += r"\setlength{\fboxsep}{0pt}"
starttag += r"\colorbox{ansi-default-inverse-bg}{"
endtag = r"\strut}" + endtag
if bold:
starttag += r"\textbf{"
endtag = "}" + endtag
if underline:
starttag += r"\underline{"
endtag = "}" + endtag
return starttag, endtag
def _ansi2anything(text, converter): # noqa
r"""
Convert ANSI colors to HTML or LaTeX.
See https://en.wikipedia.org/wiki/ANSI_escape_code
Accepts codes like '\x1b[32m' (red) and '\x1b[1;32m' (bold, red).
Non-color escape sequences (not ending with 'm') are filtered out.
Ideally, this should have the same behavior as the function
fixConsole() in notebook/notebook/static/base/js/utils.js.
"""
fg, bg = None, None
bold = False
underline = False
inverse = False
numbers = []
out = []
while text:
m = _ANSI_RE.search(text)
if m:
if m.group(2) == "m":
try:
# Empty code is same as code 0
numbers = [int(n) if n else 0 for n in m.group(1).split(";")]
except ValueError:
pass # Invalid color specification
else:
pass # Not a color code
chunk, text = text[: m.start()], text[m.end() :]
else:
chunk, text = text, ""
if chunk:
starttag, endtag = converter(
fg + 8 if bold and fg in range(8) else fg, # type:ignore
bg,
bold,
underline,
inverse,
)
out.append(starttag)
out.append(chunk)
out.append(endtag)
while numbers:
n = numbers.pop(0)
if n == 0:
# Code 0 (same as empty code): reset everything
fg = bg = None
bold = underline = inverse = False
elif n == 1:
bold = True
elif n == 4:
underline = True
elif n == 5:
# Code 5: blinking
bold = True
elif n == 7:
inverse = True
elif n in (21, 22):
bold = False
elif n == 24:
underline = False
elif n == 27:
inverse = False
elif 30 <= n <= 37:
fg = n - 30
elif n == 38:
try:
fg = _get_extended_color(numbers)
except ValueError:
numbers.clear()
elif n == 39:
fg = None
elif 40 <= n <= 47:
bg = n - 40
elif n == 48:
try:
bg = _get_extended_color(numbers)
except ValueError:
numbers.clear()
elif n == 49:
bg = None
elif 90 <= n <= 97:
fg = n - 90 + 8
elif 100 <= n <= 107:
bg = n - 100 + 8
else:
pass # Unknown codes are ignored
return "".join(out)
The provided code snippet includes necessary dependencies for implementing the `ansi2latex` function. Write a Python function `def ansi2latex(text)` to solve the following problem:
Convert ANSI colors to LaTeX colors. Parameters ---------- text : unicode Text containing ANSI colors to convert to LaTeX
Here is the function:
def ansi2latex(text):
"""
Convert ANSI colors to LaTeX colors.
Parameters
----------
text : unicode
Text containing ANSI colors to convert to LaTeX
"""
return _ansi2anything(text, _latexconverter) | Convert ANSI colors to LaTeX colors. Parameters ---------- text : unicode Text containing ANSI colors to convert to LaTeX |
172,196 | import re
from pandocfilters import RawInline, applyJSONFilters, stringify
def resolve_one_reference(key, val, fmt, meta):
"""
This takes a tuple of arguments that are compatible with ``pandocfilters.walk()`` that
allows identifying hyperlinks in the document and transforms them into valid LaTeX
\\hyperref{} calls so that linking to headers between cells is possible.
See the documentation in ``pandocfilters.walk()`` for further information on the meaning
and specification of ``key``, ``val``, ``fmt``, and ``meta``.
"""
if key == "Link":
text = stringify(val[1])
target = val[2][0]
m = re.match(r"#(.+)$", target)
if m:
# pandoc automatically makes labels for headings.
label = m.group(1).lower()
label = re.sub(r"[^\w-]+", "", label) # Strip HTML entities
text = re.sub(r"_", r"\_", text) # Escape underscores in display text
return RawInline("tex", rf"\hyperref[{label}]{{{text}}}")
# Other elements will be returned unchanged.
def applyJSONFilters(actions, source, format=""):
"""Walk through JSON structure and apply filters
This:
* reads a JSON-formatted pandoc document from a source string
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document as a string
The `actions` argument is a list of functions (see `walk`
for a full description).
The argument `source` is a string encoded JSON object.
The argument `format` is a string describing the output format.
Returns a the new JSON-formatted pandoc document.
"""
doc = json.loads(source)
if 'meta' in doc:
meta = doc['meta']
elif doc[0]: # old API
meta = doc[0]['unMeta']
else:
meta = {}
altered = doc
for action in actions:
altered = walk(altered, action, format, meta)
return json.dumps(altered)
The provided code snippet includes necessary dependencies for implementing the `resolve_references` function. Write a Python function `def resolve_references(source)` to solve the following problem:
This applies the resolve_one_reference to the text passed in via the source argument. This expects content in the form of a string encoded JSON object as represented internally in ``pandoc``.
Here is the function:
def resolve_references(source):
"""
This applies the resolve_one_reference to the text passed in via the source argument.
This expects content in the form of a string encoded JSON object as represented
internally in ``pandoc``.
"""
return applyJSONFilters([resolve_one_reference], source) | This applies the resolve_one_reference to the text passed in via the source argument. This expects content in the form of a string encoded JSON object as represented internally in ``pandoc``. |
172,197 | from html.parser import HTMLParser
class CitationParser(HTMLParser):
"""Citation Parser
Replaces html tags with data-cite attribute with respective latex \\cite.
Inherites from HTMLParser, overrides:
- handle_starttag
- handle_endtag
"""
# number of open tags
opentags = None
# list of found citations
citelist = None # type:ignore
# active citation tag
citetag = None
def __init__(self):
"""Initialize the parser."""
self.citelist = []
self.opentags = 0
HTMLParser.__init__(self)
def get_offset(self):
"""Get the offset position."""
# Compute startposition in source
lin, offset = self.getpos()
pos = 0
for _ in range(lin - 1):
pos = self.data.find("\n", pos) + 1
return pos + offset
def handle_starttag(self, tag, attrs):
"""Handle a start tag."""
# for each tag check if attributes are present and if no citation is active
if self.opentags == 0 and len(attrs) > 0:
for atr, data in attrs:
if atr.lower() == "data-cite":
self.citetag = tag
self.opentags = 1
self.citelist.append([data, self.get_offset()])
return
if tag == self.citetag:
# found an open citation tag but not the starting one
self.opentags += 1 # type:ignore
def handle_endtag(self, tag):
"""Handle an end tag."""
if tag == self.citetag:
# found citation tag check if starting one
if self.opentags == 1:
pos = self.get_offset()
self.citelist[-1].append(pos + len(tag) + 3)
self.opentags -= 1 # type:ignore
def feed(self, data):
"""Handle a feed."""
self.data = data
HTMLParser.feed(self, data)
The provided code snippet includes necessary dependencies for implementing the `citation2latex` function. Write a Python function `def citation2latex(s)` to solve the following problem:
Parse citations in Markdown cells. This looks for HTML tags having a data attribute names ``data-cite`` and replaces it by the call to LaTeX cite command. The transformation looks like this:: <cite data-cite="granger">(Granger, 2013)</cite> Becomes :: \\cite{granger} Any HTML tag can be used, which allows the citations to be formatted in HTML in any manner.
Here is the function:
def citation2latex(s):
"""Parse citations in Markdown cells.
This looks for HTML tags having a data attribute names ``data-cite``
and replaces it by the call to LaTeX cite command. The transformation
looks like this::
<cite data-cite="granger">(Granger, 2013)</cite>
Becomes ::
\\cite{granger}
Any HTML tag can be used, which allows the citations to be formatted
in HTML in any manner.
"""
parser = CitationParser()
parser.feed(s)
parser.close()
outtext = ""
startpos = 0
for citation in parser.citelist:
outtext += s[startpos : citation[1]]
outtext += "\\cite{%s}" % citation[0]
startpos = citation[2] if len(citation) == 3 else -1 # noqa
outtext += s[startpos:] if startpos != -1 else ""
return outtext | Parse citations in Markdown cells. This looks for HTML tags having a data attribute names ``data-cite`` and replaces it by the call to LaTeX cite command. The transformation looks like this:: <cite data-cite="granger">(Granger, 2013)</cite> Becomes :: \\cite{granger} Any HTML tag can be used, which allows the citations to be formatted in HTML in any manner. |
172,198 | from html import escape
from warnings import warn
from traitlets import observe
from traitlets.config import Dict
from nbconvert.utils.base import NbConvertBase
def highlight(code, lexer, formatter, outfile=None):
"""
Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
If ``outfile`` is given and a valid file object (an object
with a ``write`` method), the result will be written to it, otherwise
it is returned as a string.
"""
return format(lex(code, lexer), formatter, outfile)
def get_lexer_by_name(_alias, **options):
"""Get a lexer by an alias.
Raises ClassNotFound if not found.
"""
if not _alias:
raise ClassNotFound('no lexer for alias %r found' % _alias)
# lookup builtin lexers
for module_name, name, aliases, _, _ in LEXERS.values():
if _alias.lower() in aliases:
if name not in _lexer_cache:
_load_lexers(module_name)
return _lexer_cache[name](**options)
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if _alias.lower() in cls.aliases:
return cls(**options)
raise ClassNotFound('no lexer for alias %r found' % _alias)
class ClassNotFound(ValueError):
"""Raised if one of the lookup functions didn't find a matching class."""
IPython3Lexer = build_ipy_lexer(python3=True)
IPythonLexer = build_ipy_lexer(python3=False)
class TextLexer(Lexer):
"""
"Null" lexer, doesn't highlight anything.
"""
name = 'Text only'
aliases = ['text']
filenames = ['*.txt']
mimetypes = ['text/plain']
priority = 0.01
def get_tokens_unprocessed(self, text):
yield 0, Text, text
def analyse_text(text):
return TextLexer.priority
The provided code snippet includes necessary dependencies for implementing the `_pygments_highlight` function. Write a Python function `def _pygments_highlight(source, output_formatter, language="ipython", metadata=None)` to solve the following problem:
Return a syntax-highlighted version of the input source Parameters ---------- source : str source of the cell to highlight output_formatter : Pygments formatter language : str language to highlight the syntax of metadata : NotebookNode cell metadata metadata of the cell to highlight
Here is the function:
def _pygments_highlight(source, output_formatter, language="ipython", metadata=None):
"""
Return a syntax-highlighted version of the input source
Parameters
----------
source : str
source of the cell to highlight
output_formatter : Pygments formatter
language : str
language to highlight the syntax of
metadata : NotebookNode cell metadata
metadata of the cell to highlight
"""
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
# If the cell uses a magic extension language,
# use the magic language instead.
if language.startswith("ipython") and metadata and "magics_language" in metadata:
language = metadata["magics_language"]
lexer = None
if language == "ipython2":
try:
from IPython.lib.lexers import IPythonLexer
except ImportError:
warn("IPython lexer unavailable, falling back on Python")
language = "python"
else:
lexer = IPythonLexer()
elif language == "ipython3":
try:
from IPython.lib.lexers import IPython3Lexer
except ImportError:
warn("IPython3 lexer unavailable, falling back on Python 3")
language = "python3"
else:
lexer = IPython3Lexer()
if lexer is None:
try:
lexer = get_lexer_by_name(language, stripall=True)
except ClassNotFound:
warn("No lexer found for language %r. Treating as plain text." % language)
from pygments.lexers.special import TextLexer
lexer = TextLexer()
return highlight(source, lexer, output_formatter) | Return a syntax-highlighted version of the input source Parameters ---------- source : str source of the cell to highlight output_formatter : Pygments formatter language : str language to highlight the syntax of metadata : NotebookNode cell metadata metadata of the cell to highlight |
172,199 | import base64
import mimetypes
import os
import re
from functools import partial
from html import escape
import bs4
from mistune import PLUGINS, BlockParser, HTMLRenderer, InlineParser, Markdown
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
from nbconvert.filters.strings import add_anchor
The provided code snippet includes necessary dependencies for implementing the `_dotall` function. Write a Python function `def _dotall(pattern)` to solve the following problem:
Make the '.' special character match any character inside the pattern, including a newline. This is implemented with the inline flag `(?s:...)` and is equivalent to using `re.DOTALL` when it is the only pattern used. It is necessary since `mistune>=2.0.0`, where the pattern is passed to the undocumented `re.Scanner`.
Here is the function:
def _dotall(pattern):
"""Make the '.' special character match any character inside the pattern, including a newline.
This is implemented with the inline flag `(?s:...)` and is equivalent to using `re.DOTALL` when
it is the only pattern used. It is necessary since `mistune>=2.0.0`, where the pattern is passed
to the undocumented `re.Scanner`.
"""
return f"(?s:{pattern})" | Make the '.' special character match any character inside the pattern, including a newline. This is implemented with the inline flag `(?s:...)` and is equivalent to using `re.DOTALL` when it is the only pattern used. It is necessary since `mistune>=2.0.0`, where the pattern is passed to the undocumented `re.Scanner`. |
172,200 | import base64
import mimetypes
import os
import re
from functools import partial
from html import escape
import bs4
from mistune import PLUGINS, BlockParser, HTMLRenderer, InlineParser, Markdown
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
from nbconvert.filters.strings import add_anchor
class MarkdownWithMath(Markdown):
"""Markdown text with math enabled."""
def __init__(self, renderer, block=None, inline=None, plugins=None):
"""Initialize the parser."""
if block is None:
block = MathBlockParser()
if inline is None:
inline = MathInlineParser(renderer, hard_wrap=False)
if plugins is None:
plugins = [
# "abbr",
# 'footnotes',
"strikethrough",
"table",
"url",
"task_lists",
"def_list",
]
_plugins = []
for p in plugins:
if isinstance(p, str):
_plugins.append(PLUGINS[p])
else:
_plugins.append(p)
plugins = _plugins
super().__init__(renderer, block, inline, plugins)
def render(self, s):
"""Compatibility method with `mistune==0.8.4`."""
return self.parse(s)
class IPythonRenderer(HTMLRenderer):
"""An ipython html renderer."""
def __init__( # noqa
self,
escape=True,
allow_harmful_protocols=True,
embed_images=False,
exclude_anchor_links=False,
anchor_link_text="¶",
path="",
attachments=None,
):
"""Initialize the renderer."""
super().__init__(escape, allow_harmful_protocols)
self.embed_images = embed_images
self.exclude_anchor_links = exclude_anchor_links
self.anchor_link_text = anchor_link_text
self.path = path
if attachments is not None:
self.attachments = attachments
else:
self.attachments = {}
def block_code(self, code, info=None):
"""Handle block code."""
lang = ""
lexer = None
if info:
try:
lang = info.strip().split(None, 1)[0]
lexer = get_lexer_by_name(lang, stripall=True)
except ClassNotFound:
code = lang + "\n" + code
lang = None # type:ignore
if not lang:
return super().block_code(code)
formatter = HtmlFormatter()
return highlight(code, lexer, formatter)
def block_html(self, html):
"""Handle block html."""
if self.embed_images:
html = self._html_embed_images(html)
return super().block_html(html)
def inline_html(self, html):
"""Handle inline html."""
if self.embed_images:
html = self._html_embed_images(html)
return super().inline_html(html)
def heading(self, text, level):
"""Handle a heading."""
html = super().heading(text, level)
if self.exclude_anchor_links:
return html
return add_anchor(html, anchor_link_text=self.anchor_link_text)
def escape_html(self, text):
"""Escape html content."""
return html_escape(text)
def multiline_math(self, text):
"""Handle mulitline math."""
return text
def block_math(self, text):
"""Handle block math."""
return f"$${self.escape_html(text)}$$"
def latex_environment(self, name, text):
"""Handle a latex environment."""
name, text = self.escape_html(name), self.escape_html(text)
return f"\\begin{{{name}}}{text}\\end{{{name}}}"
def inline_math(self, text):
"""Handle inline math."""
return f"${self.escape_html(text)}$"
def image(self, src, text, title):
"""Rendering a image with title and text.
:param src: source link of the image.
:param text: alt text of the image.
:param title: title text of the image.
"""
attachment_prefix = "attachment:"
if src.startswith(attachment_prefix):
name = src[len(attachment_prefix) :]
if name not in self.attachments:
msg = f"missing attachment: {name}"
raise InvalidNotebook(msg)
attachment = self.attachments[name]
# we choose vector over raster, and lossless over lossy
preferred_mime_types = ["image/svg+xml", "image/png", "image/jpeg"]
for preferred_mime_type in preferred_mime_types:
if preferred_mime_type in attachment:
break
else: # otherwise we choose the first mimetype we can find
preferred_mime_type = list(attachment.keys())[0]
mime_type = preferred_mime_type
data = attachment[mime_type]
src = "data:" + mime_type + ";base64," + data
elif self.embed_images:
base64_url = self._src_to_base64(src)
if base64_url is not None:
src = base64_url
return super().image(src, text, title)
def _src_to_base64(self, src):
"""Turn the source file into a base64 url.
:param src: source link of the file.
:return: the base64 url or None if the file was not found.
"""
src_path = os.path.join(self.path, src)
if not os.path.exists(src_path):
return None
with open(src_path, "rb") as fobj:
mime_type = mimetypes.guess_type(src_path)[0]
base64_data = base64.b64encode(fobj.read())
base64_str = base64_data.replace(b"\n", b"").decode("ascii")
return f"data:{mime_type};base64,{base64_str}"
def _html_embed_images(self, html):
parsed_html = bs4.BeautifulSoup(html, features="html.parser")
imgs = parsed_html.find_all("img")
# Replace img tags's sources by base64 dataurls
for img in imgs:
if "src" not in img.attrs:
continue
base64_url = self._src_to_base64(img.attrs["src"])
if base64_url is not None:
img.attrs["src"] = base64_url
return str(parsed_html)
def escape(text: Any) -> SafeText: ...
The provided code snippet includes necessary dependencies for implementing the `markdown2html_mistune` function. Write a Python function `def markdown2html_mistune(source)` to solve the following problem:
Convert a markdown string to HTML using mistune
Here is the function:
def markdown2html_mistune(source):
"""Convert a markdown string to HTML using mistune"""
return MarkdownWithMath(renderer=IPythonRenderer(escape=False)).render(source) | Convert a markdown string to HTML using mistune |
172,201 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `wrap_text` function. Write a Python function `def wrap_text(text, width=100)` to solve the following problem:
Intelligently wrap text. Wrap text without breaking words if possible. Parameters ---------- text : str Text to wrap. width : int, optional Number of characters to wrap to, default 100.
Here is the function:
def wrap_text(text, width=100):
"""
Intelligently wrap text.
Wrap text without breaking words if possible.
Parameters
----------
text : str
Text to wrap.
width : int, optional
Number of characters to wrap to, default 100.
"""
split_text = text.split("\n")
wrp = map(lambda x: textwrap.wrap(x, width), split_text) # noqa
wrpd = map("\n".join, wrp)
return "\n".join(wrpd) | Intelligently wrap text. Wrap text without breaking words if possible. Parameters ---------- text : str Text to wrap. width : int, optional Number of characters to wrap to, default 100. |
172,202 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
def _get_default_css_sanitizer():
if _USE_BLEACH_CSS_SANITIZER:
return CSSSanitizer(allowed_css_properties=ALLOWED_STYLES)
ALLOWED_SVG_TAGS = {
"a",
"animate",
"animateColor",
"animateMotion",
"animateTransform",
"circle",
"clipPath",
"defs",
"desc",
"ellipse",
"font-face",
"font-face-name",
"font-face-src",
"g",
"glyph",
"hkern",
"line",
"linearGradient",
"marker",
"metadata",
"missing-glyph",
"mpath",
"path",
"polygon",
"polyline",
"radialGradient",
"rect",
"set",
"stop",
"svg",
"switch",
"text",
"title",
"tspan",
"use",
}
ALLOWED_SVG_ATTRIBUTES = {
"accent-height",
"accumulate",
"additive",
"alphabetic",
"arabic-form",
"ascent",
"attributeName",
"attributeType",
"baseProfile",
"bbox",
"begin",
"by",
"calcMode",
"cap-height",
"class",
"clip-path",
"color",
"color-rendering",
"content",
"cx",
"cy",
"d",
"descent",
"display",
"dur",
"dx",
"dy",
"end",
"fill",
"fill-opacity",
"fill-rule",
"font-family",
"font-size",
"font-stretch",
"font-style",
"font-variant",
"font-weight",
"from",
"fx",
"fy",
"g1",
"g2",
"glyph-name",
"gradientUnits",
"hanging",
"height",
"horiz-adv-x",
"horiz-origin-x",
"id",
"ideographic",
"k",
"keyPoints",
"keySplines",
"keyTimes",
"lang",
"marker-end",
"marker-mid",
"marker-start",
"markerHeight",
"markerUnits",
"markerWidth",
"mathematical",
"max",
"min",
"name",
"offset",
"opacity",
"orient",
"origin",
"overline-position",
"overline-thickness",
"panose-1",
"path",
"pathLength",
"points",
"preserveAspectRatio",
"r",
"refX",
"refY",
"repeatCount",
"repeatDur",
"requiredExtensions",
"requiredFeatures",
"restart",
"rotate",
"rx",
"ry",
"slope",
"stemh",
"stemv",
"stop-color",
"stop-opacity",
"strikethrough-position",
"strikethrough-thickness",
"stroke",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-opacity",
"stroke-width",
"style",
"systemLanguage",
"target",
"text-anchor",
"to",
"transform",
"type",
"u1",
"u2",
"underline-position",
"underline-thickness",
"unicode",
"unicode-range",
"units-per-em",
"values",
"version",
"viewBox",
"visibility",
"width",
"widths",
"x",
"x-height",
"x1",
"x2",
"xlink:actuate",
"xlink:arcrole",
"xlink:href",
"xlink:role",
"xlink:show",
"xlink:title",
"xlink:type",
"xml:base",
"xml:lang",
"xml:space",
"y",
"y1",
"y2",
"zoomAndPan",
}
The provided code snippet includes necessary dependencies for implementing the `clean_html` function. Write a Python function `def clean_html(element)` to solve the following problem:
Clean an html element.
Here is the function:
def clean_html(element):
"""Clean an html element."""
element = element.decode() if isinstance(element, bytes) else str(element)
kwargs = {}
css_sanitizer = _get_default_css_sanitizer()
if css_sanitizer:
kwargs['css_sanitizer'] = css_sanitizer
return bleach.clean(
element,
tags=[*bleach.ALLOWED_TAGS, *ALLOWED_SVG_TAGS, "div", "pre", "code", "span"],
strip_comments=False,
attributes={
**bleach.ALLOWED_ATTRIBUTES,
**{svg_tag: list(ALLOWED_SVG_ATTRIBUTES) for svg_tag in ALLOWED_SVG_TAGS},
"*": ["class", "id"],
},
**kwargs,
) | Clean an html element. |
172,203 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
def html2text(element):
"""extract inner text from html
Analog of jQuery's $(element).text()
"""
if isinstance(element, (str,)):
try:
element = ElementTree.fromstring(element)
except Exception:
# failed to parse, just return it unmodified
return element
text = element.text or ""
for child in element:
text += html2text(child)
text += element.tail or ""
return text
def _convert_header_id(header_contents):
"""Convert header contents to valid id value. Takes string as input, returns string.
Note: this may be subject to change in the case of changes to how we wish to generate ids.
For use on markdown headings.
"""
# Valid IDs need to be non-empty and contain no space characters, but are otherwise arbitrary.
# However, these IDs are also used in URL fragments, which are more restrictive, so we URL
# encode any characters that are not valid in URL fragments.
return quote(header_contents.replace(" ", "-"), safe="?/:@!$&'()*+,;=")
The provided code snippet includes necessary dependencies for implementing the `add_anchor` function. Write a Python function `def add_anchor(html, anchor_link_text="¶")` to solve the following problem:
Add an id and an anchor-link to an html header For use on markdown headings
Here is the function:
def add_anchor(html, anchor_link_text="¶"):
"""Add an id and an anchor-link to an html header
For use on markdown headings
"""
try:
h = ElementTree.fromstring(html)
except Exception:
# failed to parse, just return it unmodified
return html
link = _convert_header_id(html2text(h))
h.set("id", link)
a = Element("a", {"class": "anchor-link", "href": "#" + link})
try:
# Test if the anchor link text is HTML (e.g. an image)
a.append(ElementTree.fromstring(anchor_link_text))
except Exception:
# If we fail to parse, assume we've just got regular text
a.text = anchor_link_text
h.append(a)
return ElementTree.tostring(h).decode(encoding="utf-8") | Add an id and an anchor-link to an html header For use on markdown headings |
172,204 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `add_prompts` function. Write a Python function `def add_prompts(code, first=">>> ", cont="... ")` to solve the following problem:
Add prompts to code snippets
Here is the function:
def add_prompts(code, first=">>> ", cont="... "):
"""Add prompts to code snippets"""
new_code = []
code_list = code.split("\n")
new_code.append(first + code_list[0])
for line in code_list[1:]:
new_code.append(cont + line)
return "\n".join(new_code) | Add prompts to code snippets |
172,205 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `strip_dollars` function. Write a Python function `def strip_dollars(text)` to solve the following problem:
Remove all dollar symbols from text Parameters ---------- text : str Text to remove dollars from
Here is the function:
def strip_dollars(text):
"""
Remove all dollar symbols from text
Parameters
----------
text : str
Text to remove dollars from
"""
return text.strip("$") | Remove all dollar symbols from text Parameters ---------- text : str Text to remove dollars from |
172,206 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
files_url_pattern = re.compile(r'(src|href)\=([\'"]?)/?files/')
markdown_url_pattern = re.compile(r"(!?)\[(?P<caption>.*?)\]\(/?files/(?P<location>.*?)\)")
The provided code snippet includes necessary dependencies for implementing the `strip_files_prefix` function. Write a Python function `def strip_files_prefix(text)` to solve the following problem:
Fix all fake URLs that start with ``files/``, stripping out the ``files/`` prefix. Applies to both urls (for html) and relative paths (for markdown paths). Parameters ---------- text : str Text in which to replace 'src="files/real...' with 'src="real...'
Here is the function:
def strip_files_prefix(text):
"""
Fix all fake URLs that start with ``files/``, stripping out the ``files/`` prefix.
Applies to both urls (for html) and relative paths (for markdown paths).
Parameters
----------
text : str
Text in which to replace 'src="files/real...' with 'src="real...'
"""
cleaned_text = files_url_pattern.sub(r"\1=\2", text)
cleaned_text = markdown_url_pattern.sub(r"\1[\2](\3)", cleaned_text)
return cleaned_text | Fix all fake URLs that start with ``files/``, stripping out the ``files/`` prefix. Applies to both urls (for html) and relative paths (for markdown paths). Parameters ---------- text : str Text in which to replace 'src="files/real...' with 'src="real...' |
172,207 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `comment_lines` function. Write a Python function `def comment_lines(text, prefix="# ")` to solve the following problem:
Build a Python comment line from input text. Parameters ---------- text : str Text to comment out. prefix : str Character to append to the start of each line.
Here is the function:
def comment_lines(text, prefix="# "):
"""
Build a Python comment line from input text.
Parameters
----------
text : str
Text to comment out.
prefix : str
Character to append to the start of each line.
"""
# Replace line breaks with line breaks and comment symbols.
# Also add a comment symbol at the beginning to comment out
# the first line.
return prefix + ("\n" + prefix).join(text.split("\n")) | Build a Python comment line from input text. Parameters ---------- text : str Text to comment out. prefix : str Character to append to the start of each line. |
172,208 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `get_lines` function. Write a Python function `def get_lines(text, start=None, end=None)` to solve the following problem:
Split the input text into separate lines and then return the lines that the caller is interested in. Parameters ---------- text : str Text to parse lines from. start : int, optional First line to grab from. end : int, optional Last line to grab from.
Here is the function:
def get_lines(text, start=None, end=None):
"""
Split the input text into separate lines and then return the
lines that the caller is interested in.
Parameters
----------
text : str
Text to parse lines from.
start : int, optional
First line to grab from.
end : int, optional
Last line to grab from.
"""
# Split the input into lines.
lines = text.split("\n")
# Return the right lines.
return "\n".join(lines[start:end]) # re-join | Split the input text into separate lines and then return the lines that the caller is interested in. Parameters ---------- text : str Text to parse lines from. start : int, optional First line to grab from. end : int, optional Last line to grab from. |
172,209 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
class TransformerManager:
"""Applies various transformations to a cell or code block.
The key methods for external use are ``transform_cell()``
and ``check_complete()``.
"""
def __init__(self):
self.cleanup_transforms = [
leading_empty_lines,
leading_indent,
classic_prompt,
ipython_prompt,
]
self.line_transforms = [
cell_magic,
]
self.token_transformers = [
MagicAssign,
SystemAssign,
EscapedCommand,
HelpEnd,
]
def do_one_token_transform(self, lines):
"""Find and run the transform earliest in the code.
Returns (changed, lines).
This method is called repeatedly until changed is False, indicating
that all available transformations are complete.
The tokens following IPython special syntax might not be valid, so
the transformed code is retokenised every time to identify the next
piece of special syntax. Hopefully long code cells are mostly valid
Python, not using lots of IPython special syntax, so this shouldn't be
a performance issue.
"""
tokens_by_line = make_tokens_by_line(lines)
candidates = []
for transformer_cls in self.token_transformers:
transformer = transformer_cls.find(tokens_by_line)
if transformer:
candidates.append(transformer)
if not candidates:
# Nothing to transform
return False, lines
ordered_transformers = sorted(candidates, key=TokenTransformBase.sortby)
for transformer in ordered_transformers:
try:
return True, transformer.transform(lines)
except SyntaxError:
pass
return False, lines
def do_token_transforms(self, lines):
for _ in range(TRANSFORM_LOOP_LIMIT):
changed, lines = self.do_one_token_transform(lines)
if not changed:
return lines
raise RuntimeError("Input transformation still changing after "
"%d iterations. Aborting." % TRANSFORM_LOOP_LIMIT)
def transform_cell(self, cell: str) -> str:
"""Transforms a cell of input code"""
if not cell.endswith('\n'):
cell += '\n' # Ensure the cell has a trailing newline
lines = cell.splitlines(keepends=True)
for transform in self.cleanup_transforms + self.line_transforms:
lines = transform(lines)
lines = self.do_token_transforms(lines)
return ''.join(lines)
def check_complete(self, cell: str):
"""Return whether a block of code is ready to execute, or should be continued
Parameters
----------
cell : string
Python input code, which can be multiline.
Returns
-------
status : str
One of 'complete', 'incomplete', or 'invalid' if source is not a
prefix of valid code.
indent_spaces : int or None
The number of spaces by which to indent the next line of code. If
status is not 'incomplete', this is None.
"""
# Remember if the lines ends in a new line.
ends_with_newline = False
for character in reversed(cell):
if character == '\n':
ends_with_newline = True
break
elif character.strip():
break
else:
continue
if not ends_with_newline:
# Append an newline for consistent tokenization
# See https://bugs.python.org/issue33899
cell += '\n'
lines = cell.splitlines(keepends=True)
if not lines:
return 'complete', None
if lines[-1].endswith('\\'):
# Explicit backslash continuation
return 'incomplete', find_last_indent(lines)
try:
for transform in self.cleanup_transforms:
if not getattr(transform, 'has_side_effects', False):
lines = transform(lines)
except SyntaxError:
return 'invalid', None
if lines[0].startswith('%%'):
# Special case for cell magics - completion marked by blank line
if lines[-1].strip():
return 'incomplete', find_last_indent(lines)
else:
return 'complete', None
try:
for transform in self.line_transforms:
if not getattr(transform, 'has_side_effects', False):
lines = transform(lines)
lines = self.do_token_transforms(lines)
except SyntaxError:
return 'invalid', None
tokens_by_line = make_tokens_by_line(lines)
# Bail if we got one line and there are more closing parentheses than
# the opening ones
if (
len(lines) == 1
and tokens_by_line
and has_sunken_brackets(tokens_by_line[0])
):
return "invalid", None
if not tokens_by_line:
return 'incomplete', find_last_indent(lines)
if tokens_by_line[-1][-1].type != tokenize.ENDMARKER:
# We're in a multiline string or expression
return 'incomplete', find_last_indent(lines)
newline_types = {tokenize.NEWLINE, tokenize.COMMENT, tokenize.ENDMARKER} # type: ignore
# Pop the last line which only contains DEDENTs and ENDMARKER
last_token_line = None
if {t.type for t in tokens_by_line[-1]} in [
{tokenize.DEDENT, tokenize.ENDMARKER},
{tokenize.ENDMARKER}
] and len(tokens_by_line) > 1:
last_token_line = tokens_by_line.pop()
while tokens_by_line[-1] and tokens_by_line[-1][-1].type in newline_types:
tokens_by_line[-1].pop()
if not tokens_by_line[-1]:
return 'incomplete', find_last_indent(lines)
if tokens_by_line[-1][-1].string == ':':
# The last line starts a block (e.g. 'if foo:')
ix = 0
while tokens_by_line[-1][ix].type in {tokenize.INDENT, tokenize.DEDENT}:
ix += 1
indent = tokens_by_line[-1][ix].start[1]
return 'incomplete', indent + 4
if tokens_by_line[-1][0].line.endswith('\\'):
return 'incomplete', None
# At this point, our checks think the code is complete (or invalid).
# We'll use codeop.compile_command to check this with the real parser
try:
with warnings.catch_warnings():
warnings.simplefilter('error', SyntaxWarning)
res = compile_command(''.join(lines), symbol='exec')
except (SyntaxError, OverflowError, ValueError, TypeError,
MemoryError, SyntaxWarning):
return 'invalid', None
else:
if res is None:
return 'incomplete', find_last_indent(lines)
if last_token_line and last_token_line[0].type == tokenize.DEDENT:
if ends_with_newline:
return 'complete', None
return 'incomplete', find_last_indent(lines)
# If there's a blank line at the end, assume we're ready to execute
if not lines[-1].strip():
return 'complete', None
return 'complete', None
The provided code snippet includes necessary dependencies for implementing the `ipython2python` function. Write a Python function `def ipython2python(code)` to solve the following problem:
Transform IPython syntax to pure Python syntax Parameters ---------- code : str IPython code, to be transformed to pure Python
Here is the function:
def ipython2python(code):
"""Transform IPython syntax to pure Python syntax
Parameters
----------
code : str
IPython code, to be transformed to pure Python
"""
try:
from IPython.core.inputtransformer2 import TransformerManager
except ImportError:
warnings.warn(
"IPython is needed to transform IPython syntax to pure Python."
" Install ipython if you need this functionality."
)
return code
else:
isp = TransformerManager()
return isp.transform_cell(code) | Transform IPython syntax to pure Python syntax Parameters ---------- code : str IPython code, to be transformed to pure Python |
172,210 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `posix_path` function. Write a Python function `def posix_path(path)` to solve the following problem:
Turn a path into posix-style path/to/etc Mainly for use in latex on Windows, where native Windows paths are not allowed.
Here is the function:
def posix_path(path):
"""Turn a path into posix-style path/to/etc
Mainly for use in latex on Windows,
where native Windows paths are not allowed.
"""
if os.path.sep != "/":
return path.replace(os.path.sep, "/")
return path | Turn a path into posix-style path/to/etc Mainly for use in latex on Windows, where native Windows paths are not allowed. |
172,211 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `path2url` function. Write a Python function `def path2url(path)` to solve the following problem:
Turn a file path into a URL
Here is the function:
def path2url(path):
"""Turn a file path into a URL"""
parts = path.split(os.path.sep)
return "/".join(quote(part) for part in parts) | Turn a file path into a URL |
172,212 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `ascii_only` function. Write a Python function `def ascii_only(s)` to solve the following problem:
ensure a string is ascii
Here is the function:
def ascii_only(s):
"""ensure a string is ascii"""
return s.encode("ascii", "replace").decode("ascii") | ensure a string is ascii |
172,213 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `prevent_list_blocks` function. Write a Python function `def prevent_list_blocks(s)` to solve the following problem:
Prevent presence of enumerate or itemize blocks in latex headings cells
Here is the function:
def prevent_list_blocks(s):
"""
Prevent presence of enumerate or itemize blocks in latex headings cells
"""
out = re.sub(r"(^\s*\d*)\.", r"\1\.", s)
out = re.sub(r"(^\s*)\-", r"\1\-", out)
out = re.sub(r"(^\s*)\+", r"\1\+", out)
out = re.sub(r"(^\s*)\*", r"\1\*", out)
return out | Prevent presence of enumerate or itemize blocks in latex headings cells |
172,214 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `strip_trailing_newline` function. Write a Python function `def strip_trailing_newline(text)` to solve the following problem:
Strips a newline from the end of text.
Here is the function:
def strip_trailing_newline(text):
"""
Strips a newline from the end of text.
"""
if text.endswith("\n"):
text = text[:-1]
return text | Strips a newline from the end of text. |
172,215 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATTRIBUTES, ALLOWED_SVG_TAGS
The provided code snippet includes necessary dependencies for implementing the `text_base64` function. Write a Python function `def text_base64(text)` to solve the following problem:
Encode base64 text
Here is the function:
def text_base64(text):
"""
Encode base64 text
"""
return base64.b64encode(text.encode()).decode() | Encode base64 text |
172,216 | import re
LATEX_RE_SUBS = ((re.compile(r"\.\.\.+"), r"{\\ldots}"),)
LATEX_SUBS = {
"&": r"\&",
"%": r"\%",
"$": r"\$",
"#": r"\#",
"_": r"\_",
"{": r"\{",
"}": r"\}",
"~": r"\textasciitilde{}",
"^": r"\^{}",
"\\": r"\textbackslash{}",
}
The provided code snippet includes necessary dependencies for implementing the `escape_latex` function. Write a Python function `def escape_latex(text)` to solve the following problem:
Escape characters that may conflict with latex. Parameters ---------- text : str Text containing characters that may conflict with Latex
Here is the function:
def escape_latex(text):
"""
Escape characters that may conflict with latex.
Parameters
----------
text : str
Text containing characters that may conflict with Latex
"""
text = "".join(LATEX_SUBS.get(c, c) for c in text)
for pattern, replacement in LATEX_RE_SUBS:
text = pattern.sub(replacement, text)
return text | Escape characters that may conflict with latex. Parameters ---------- text : str Text containing characters that may conflict with Latex |
172,217 |
The provided code snippet includes necessary dependencies for implementing the `get_metadata` function. Write a Python function `def get_metadata(output, key, mimetype=None)` to solve the following problem:
Resolve an output metadata key If mimetype given, resolve at mimetype level first, then fallback to top-level. Otherwise, just resolve at top-level. Returns None if no data found.
Here is the function:
def get_metadata(output, key, mimetype=None):
"""Resolve an output metadata key
If mimetype given, resolve at mimetype level first,
then fallback to top-level.
Otherwise, just resolve at top-level.
Returns None if no data found.
"""
md = output.get("metadata") or {}
if mimetype and mimetype in md:
value = md[mimetype].get(key)
if value is not None:
return value
return md.get(key) | Resolve an output metadata key If mimetype given, resolve at mimetype level first, then fallback to top-level. Otherwise, just resolve at top-level. Returns None if no data found. |
172,218 | import os
import re
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
# NOTE: Many counters require 2 samples to give accurate results,
# including "% Processor Time" (as by definition, at any instant, a
# thread's CPU usage is either 0 or 100). To read counters like this,
# you should copy this function, but keep the counter open, and call
# CollectQueryData() each time you need to know.
# See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link)
# My older explanation for this was that the "AddCounter" process
# forced the CPU to 100%, but the above makes more sense :)
import win32pdh
if format is None:
format = win32pdh.PDH_FMT_LONG
path = win32pdh.MakeCounterPath( (machine, object, instance, None,
inum, counter))
hq = win32pdh.OpenQuery()
try:
hc = win32pdh.AddCounter(hq, path)
try:
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(hc, format)
return val
finally:
win32pdh.RemoveCounter(hc)
finally:
win32pdh.CloseQuery(hq)
def memusage(processName="python", instance=0):
# from win32pdhutil, part of the win32all package
import win32pdh
return GetPerformanceAttributes("Process", "Virtual Bytes",
processName, instance,
win32pdh.PDH_FMT_LONG, None)
elif sys.platform[:5] == 'linux':
def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'):
"""
Return virtual memory size in bytes of the running python.
"""
try:
with open(_proc_pid_stat, 'r') as f:
l = f.readline().split(' ')
return int(l[22])
except Exception:
return
else:
def memusage():
"""
Return memory usage of running python. [Not implemented]
"""
raise NotImplementedError
The provided code snippet includes necessary dependencies for implementing the `indent` function. Write a Python function `def indent(instr, nspaces=4, ntabs=0, flatten=False)` to solve the following problem:
Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces.
Here is the function:
def indent(instr, nspaces=4, ntabs=0, flatten=False):
"""Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default: 4)
The number of spaces to be indented.
ntabs : int (default: 0)
The number of tabs to be indented.
flatten : bool (default: False)
Whether to scrub existing indentation. If True, all lines will be
aligned to the same indentation. If False, existing indentation will
be strictly increased.
Returns
-------
str|unicode : string indented by ntabs and nspaces.
"""
if instr is None:
return
ind = "\t" * ntabs + " " * nspaces
pat = re.compile("^\\s*", re.MULTILINE) if flatten else re.compile("^", re.MULTILINE)
outstr = re.sub(pat, ind, instr)
if outstr.endswith(os.linesep + ind):
return outstr[: -len(ind)]
else:
return outstr | Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces. |
172,219 | import codecs
import errno
import os
import random
import shutil
import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
try:
with open(_proc_pid_stat, 'r') as f:
l = f.readline().split(' ')
return int(l[13])
except Exception:
return int(100*(time.time()-_load_time[0]))
else:
# os.getpid is not in all platforms available.
# Using time is safe but inaccurate, especially when process
# was suspended or sleeping.
def jiffies(_load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
return int(100*(time.time()-_load_time[0]))
The provided code snippet includes necessary dependencies for implementing the `unicode_std_stream` function. Write a Python function `def unicode_std_stream(stream="stdout")` to solve the following problem:
Get a wrapper to write unicode to stdout/stderr as UTF-8. This ignores environment variables and default encodings, to reliably write unicode to stdout or stderr. :: unicode_std_stream().write(u'ł@e¶ŧ←')
Here is the function:
def unicode_std_stream(stream="stdout"):
"""Get a wrapper to write unicode to stdout/stderr as UTF-8.
This ignores environment variables and default encodings, to reliably write
unicode to stdout or stderr.
::
unicode_std_stream().write(u'ł@e¶ŧ←')
"""
assert stream in ("stdout", "stderr") # noqa
stream = getattr(sys, stream)
try:
stream_b = stream.buffer
except AttributeError:
# sys.stdout has been replaced - use it directly
return stream
return codecs.getwriter("utf-8")(stream_b) | Get a wrapper to write unicode to stdout/stderr as UTF-8. This ignores environment variables and default encodings, to reliably write unicode to stdout or stderr. :: unicode_std_stream().write(u'ł@e¶ŧ←') |
172,220 | import codecs
import errno
import os
import random
import shutil
import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
try:
with open(_proc_pid_stat, 'r') as f:
l = f.readline().split(' ')
return int(l[13])
except Exception:
return int(100*(time.time()-_load_time[0]))
else:
# os.getpid is not in all platforms available.
# Using time is safe but inaccurate, especially when process
# was suspended or sleeping.
def jiffies(_load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
"""
import time
if not _load_time:
_load_time.append(time.time())
return int(100*(time.time()-_load_time[0]))
The provided code snippet includes necessary dependencies for implementing the `unicode_stdin_stream` function. Write a Python function `def unicode_stdin_stream()` to solve the following problem:
Get a wrapper to read unicode from stdin as UTF-8. This ignores environment variables and default encodings, to reliably read unicode from stdin. :: totreat = unicode_stdin_stream().read()
Here is the function:
def unicode_stdin_stream():
"""Get a wrapper to read unicode from stdin as UTF-8.
This ignores environment variables and default encodings, to reliably read unicode from stdin.
::
totreat = unicode_stdin_stream().read()
"""
stream = sys.stdin
try:
stream_b = stream.buffer
except AttributeError:
return stream
return codecs.getreader("utf-8")(stream_b) | Get a wrapper to read unicode from stdin as UTF-8. This ignores environment variables and default encodings, to reliably read unicode from stdin. :: totreat = unicode_stdin_stream().read() |
172,221 | import codecs
import errno
import os
import random
import shutil
import sys
def link(src, dst):
"""Hard links ``src`` to ``dst``, returning 0 or errno.
Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
supported by the operating system.
"""
if not hasattr(os, "link"):
return ENOLINK
link_errno = 0
try:
os.link(src, dst)
except OSError as e:
link_errno = e.errno
return link_errno
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
# NOTE: Many counters require 2 samples to give accurate results,
# including "% Processor Time" (as by definition, at any instant, a
# thread's CPU usage is either 0 or 100). To read counters like this,
# you should copy this function, but keep the counter open, and call
# CollectQueryData() each time you need to know.
# See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link)
# My older explanation for this was that the "AddCounter" process
# forced the CPU to 100%, but the above makes more sense :)
import win32pdh
if format is None:
format = win32pdh.PDH_FMT_LONG
path = win32pdh.MakeCounterPath( (machine, object, instance, None,
inum, counter))
hq = win32pdh.OpenQuery()
try:
hc = win32pdh.AddCounter(hq, path)
try:
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(hc, format)
return val
finally:
win32pdh.RemoveCounter(hc)
finally:
win32pdh.CloseQuery(hq)
def memusage(processName="python", instance=0):
# from win32pdhutil, part of the win32all package
import win32pdh
return GetPerformanceAttributes("Process", "Virtual Bytes",
processName, instance,
win32pdh.PDH_FMT_LONG, None)
elif sys.platform[:5] == 'linux':
def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'):
"""
Return virtual memory size in bytes of the running python.
"""
try:
with open(_proc_pid_stat, 'r') as f:
l = f.readline().split(' ')
return int(l[22])
except Exception:
return
else:
def memusage():
"""
Return memory usage of running python. [Not implemented]
"""
raise NotImplementedError
The provided code snippet includes necessary dependencies for implementing the `link_or_copy` function. Write a Python function `def link_or_copy(src, dst)` to solve the following problem:
Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place.
Here is the function:
def link_or_copy(src, dst):
"""Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
Attempts to maintain the semantics of ``shutil.copy``.
Because ``os.link`` does not overwrite files, a unique temporary file
will be used if the target already exists, then that file will be moved
into place.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
link_errno = link(src, dst)
if link_errno == errno.EEXIST:
if os.stat(src).st_ino == os.stat(dst).st_ino:
# dst is already a hard link to the correct file, so we don't need
# to do anything else. If we try to link and rename the file
# anyway, we get duplicate files - see http://bugs.python.org/issue21876
return
new_dst = dst + f"-temp-{random.randint(1, 16**4):04X}"
try:
link_or_copy(src, new_dst)
except BaseException:
try:
os.remove(new_dst)
except OSError:
pass
raise
os.rename(new_dst, dst)
elif link_errno != 0:
# Either link isn't supported, or the filesystem doesn't support
# linking, or 'src' and 'dst' are on different filesystems.
shutil.copy(src, dst) | Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. |
172,222 | import codecs
import errno
import os
import random
import shutil
import sys
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
# NOTE: Many counters require 2 samples to give accurate results,
# including "% Processor Time" (as by definition, at any instant, a
# thread's CPU usage is either 0 or 100). To read counters like this,
# you should copy this function, but keep the counter open, and call
# CollectQueryData() each time you need to know.
# See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp (dead link)
# My older explanation for this was that the "AddCounter" process
# forced the CPU to 100%, but the above makes more sense :)
import win32pdh
if format is None:
format = win32pdh.PDH_FMT_LONG
path = win32pdh.MakeCounterPath( (machine, object, instance, None,
inum, counter))
hq = win32pdh.OpenQuery()
try:
hc = win32pdh.AddCounter(hq, path)
try:
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(hc, format)
return val
finally:
win32pdh.RemoveCounter(hc)
finally:
win32pdh.CloseQuery(hq)
def memusage(processName="python", instance=0):
# from win32pdhutil, part of the win32all package
import win32pdh
return GetPerformanceAttributes("Process", "Virtual Bytes",
processName, instance,
win32pdh.PDH_FMT_LONG, None)
elif sys.platform[:5] == 'linux':
def memusage(_proc_pid_stat=f'/proc/{os.getpid()}/stat'):
"""
Return virtual memory size in bytes of the running python.
"""
try:
with open(_proc_pid_stat, 'r') as f:
l = f.readline().split(' ')
return int(l[22])
except Exception:
return
else:
def memusage():
"""
Return memory usage of running python. [Not implemented]
"""
raise NotImplementedError
The provided code snippet includes necessary dependencies for implementing the `ensure_dir_exists` function. Write a Python function `def ensure_dir_exists(path, mode=0o755)` to solve the following problem:
ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. The default permissions are 755, which differ from os.makedirs default of 777.
Here is the function:
def ensure_dir_exists(path, mode=0o755):
"""ensure that a directory exists
If it doesn't exist, try to create it and protect against a race condition
if another process is doing the same.
The default permissions are 755, which differ from os.makedirs default of 777.
"""
if not os.path.exists(path):
try:
os.makedirs(path, mode=mode)
except OSError as e:
if e.errno != errno.EEXIST:
raise
elif not os.path.isdir(path):
raise OSError("%r exists but is not a directory" % path) | ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. The default permissions are 755, which differ from os.makedirs default of 777. |
172,223 | import re
import shutil
import subprocess
import warnings
from io import BytesIO, TextIOWrapper
from nbconvert.utils.version import check_version
from .exceptions import ConversionException
__version = None
The provided code snippet includes necessary dependencies for implementing the `clean_cache` function. Write a Python function `def clean_cache()` to solve the following problem:
Clean the internal cache.
Here is the function:
def clean_cache():
"""Clean the internal cache."""
global __version # noqa
__version = None | Clean the internal cache. |
172,224 | import numpy as np
import math
from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple
def select_step(v1, v2, nv, hour=False, include_last=True,
threshold_factor=3600.):
if v1 > v2:
v1, v2 = v2, v1
dv = (v2 - v1) / nv
if hour:
_select_step = select_step_hour
cycle = 24.
else:
_select_step = select_step_degree
cycle = 360.
# for degree
if dv > 1 / threshold_factor:
step, factor = _select_step(dv)
else:
step, factor = select_step_sub(dv*threshold_factor)
factor = factor * threshold_factor
levs = np.arange(np.floor(v1 * factor / step),
np.ceil(v2 * factor / step) + 0.5,
dtype=int) * step
# n : number of valid levels. If there is a cycle, e.g., [0, 90, 180,
# 270, 360], the grid line needs to be extended from 0 to 360, so
# we need to return the whole array. However, the last level (360)
# needs to be ignored often. In this case, so we return n=4.
n = len(levs)
# we need to check the range of values
# for example, -90 to 90, 0 to 360,
if factor == 1. and levs[-1] >= levs[0] + cycle: # check for cycle
nv = int(cycle / step)
if include_last:
levs = levs[0] + np.arange(0, nv+1, 1) * step
else:
levs = levs[0] + np.arange(0, nv, 1) * step
n = len(levs)
return np.array(levs), n, factor
def select_step24(v1, v2, nv, include_last=True, threshold_factor=3600):
v1, v2 = v1 / 15, v2 / 15
levs, n, factor = select_step(v1, v2, nv, hour=True,
include_last=include_last,
threshold_factor=threshold_factor)
return levs * 15, n, factor | null |
172,225 | import numpy as np
import math
from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple
def select_step(v1, v2, nv, hour=False, include_last=True,
threshold_factor=3600.):
def select_step360(v1, v2, nv, include_last=True, threshold_factor=3600):
return select_step(v1, v2, nv, hour=False,
include_last=include_last,
threshold_factor=threshold_factor) | null |
172,226 | import numpy as np
from matplotlib import ticker as mticker
from matplotlib.transforms import Bbox, Transform
The provided code snippet includes necessary dependencies for implementing the `_find_line_box_crossings` function. Write a Python function `def _find_line_box_crossings(xys, bbox)` to solve the following problem:
Find the points where a polyline crosses a bbox, and the crossing angles. Parameters ---------- xys : (N, 2) array The polyline coordinates. bbox : `.Bbox` The bounding box. Returns ------- list of ((float, float), float) Four separate lists of crossings, for the left, right, bottom, and top sides of the bbox, respectively. For each list, the entries are the ``((x, y), ccw_angle_in_degrees)`` of the crossing, where an angle of 0 means that the polyline is moving to the right at the crossing point. The entries are computed by linearly interpolating at each crossing between the nearest points on either side of the bbox edges.
Here is the function:
def _find_line_box_crossings(xys, bbox):
"""
Find the points where a polyline crosses a bbox, and the crossing angles.
Parameters
----------
xys : (N, 2) array
The polyline coordinates.
bbox : `.Bbox`
The bounding box.
Returns
-------
list of ((float, float), float)
Four separate lists of crossings, for the left, right, bottom, and top
sides of the bbox, respectively. For each list, the entries are the
``((x, y), ccw_angle_in_degrees)`` of the crossing, where an angle of 0
means that the polyline is moving to the right at the crossing point.
The entries are computed by linearly interpolating at each crossing
between the nearest points on either side of the bbox edges.
"""
crossings = []
dxys = xys[1:] - xys[:-1]
for sl in [slice(None), slice(None, None, -1)]:
us, vs = xys.T[sl] # "this" coord, "other" coord
dus, dvs = dxys.T[sl]
umin, vmin = bbox.min[sl]
umax, vmax = bbox.max[sl]
for u0, inside in [(umin, us > umin), (umax, us < umax)]:
crossings.append([])
idxs, = (inside[:-1] ^ inside[1:]).nonzero()
for idx in idxs:
v = vs[idx] + (u0 - us[idx]) * dvs[idx] / dus[idx]
if not vmin <= v <= vmax:
continue
crossing = (u0, v)[sl]
theta = np.degrees(np.arctan2(*dxys[idx][::-1]))
crossings[-1].append((crossing, theta))
return crossings | Find the points where a polyline crosses a bbox, and the crossing angles. Parameters ---------- xys : (N, 2) array The polyline coordinates. bbox : `.Bbox` The bounding box. Returns ------- list of ((float, float), float) Four separate lists of crossings, for the left, right, bottom, and top sides of the bbox, respectively. For each list, the entries are the ``((x, y), ccw_angle_in_degrees)`` of the crossing, where an angle of 0 means that the polyline is moving to the right at the crossing point. The entries are computed by linearly interpolating at each crossing between the nearest points on either side of the bbox edges. |
172,227 | import functools
from itertools import chain
import numpy as np
import matplotlib as mpl
from matplotlib.path import Path
from matplotlib.transforms import Affine2D, IdentityTransform
from .axislines import AxisArtistHelper, GridHelperBase
from .axis_artist import AxisArtist
from .grid_finder import GridFinder
The provided code snippet includes necessary dependencies for implementing the `_value_and_jacobian` function. Write a Python function `def _value_and_jacobian(func, xs, ys, xlims, ylims)` to solve the following problem:
Compute *func* and its derivatives along x and y at positions *xs*, *ys*, while ensuring that finite difference calculations don't try to evaluate values outside of *xlims*, *ylims*.
Here is the function:
def _value_and_jacobian(func, xs, ys, xlims, ylims):
"""
Compute *func* and its derivatives along x and y at positions *xs*, *ys*,
while ensuring that finite difference calculations don't try to evaluate
values outside of *xlims*, *ylims*.
"""
eps = np.finfo(float).eps ** (1/2) # see e.g. scipy.optimize.approx_fprime
val = func(xs, ys)
# Take the finite difference step in the direction where the bound is the
# furthest; the step size is min of epsilon and distance to that bound.
xlo, xhi = sorted(xlims)
dxlo = xs - xlo
dxhi = xhi - xs
xeps = (np.take([-1, 1], dxhi >= dxlo)
* np.minimum(eps, np.maximum(dxlo, dxhi)))
val_dx = func(xs + xeps, ys)
ylo, yhi = sorted(ylims)
dylo = ys - ylo
dyhi = yhi - ys
yeps = (np.take([-1, 1], dyhi >= dylo)
* np.minimum(eps, np.maximum(dylo, dyhi)))
val_dy = func(xs, ys + yeps)
return (val, (val_dx - val) / xeps, (val_dy - val) / yeps) | Compute *func* and its derivatives along x and y at positions *xs*, *ys*, while ensuring that finite difference calculations don't try to evaluate values outside of *xlims*, *ylims*. |
172,228 | from numbers import Number
from matplotlib import _api
from matplotlib.axes import Axes
def _get_axes_aspect(ax):
aspect = ax.get_aspect()
if aspect == "auto":
aspect = 1.
return aspect | null |
172,229 | from numbers import Number
from matplotlib import _api
from matplotlib.axes import Axes
class Fixed(_Base):
"""
Simple fixed size with absolute part = *fixed_size* and relative part = 0.
"""
def __init__(self, fixed_size):
_api.check_isinstance(Number, fixed_size=fixed_size)
self.fixed_size = fixed_size
def get_size(self, renderer):
rel_size = 0.
abs_size = self.fixed_size
return rel_size, abs_size
class Fraction(_Base):
"""
An instance whose size is a *fraction* of the *ref_size*.
>>> s = Fraction(0.3, AxesX(ax))
"""
def __init__(self, fraction, ref_size):
_api.check_isinstance(Number, fraction=fraction)
self._fraction_ref = ref_size
self._fraction = fraction
def get_size(self, renderer):
if self._fraction_ref is None:
return self._fraction, 0.
else:
r, a = self._fraction_ref.get_size(renderer)
rel_size = r*self._fraction
abs_size = a*self._fraction
return rel_size, abs_size
class Number(metaclass=ABCMeta):
def __hash__(self) -> int: ...
The provided code snippet includes necessary dependencies for implementing the `from_any` function. Write a Python function `def from_any(size, fraction_ref=None)` to solve the following problem:
Create a Fixed unit when the first argument is a float, or a Fraction unit if that is a string that ends with %. The second argument is only meaningful when Fraction unit is created. >>> a = Size.from_any(1.2) # => Size.Fixed(1.2) >>> Size.from_any("50%", a) # => Size.Fraction(0.5, a)
Here is the function:
def from_any(size, fraction_ref=None):
"""
Create a Fixed unit when the first argument is a float, or a
Fraction unit if that is a string that ends with %. The second
argument is only meaningful when Fraction unit is created.
>>> a = Size.from_any(1.2) # => Size.Fixed(1.2)
>>> Size.from_any("50%", a) # => Size.Fraction(0.5, a)
"""
if isinstance(size, Number):
return Fixed(size)
elif isinstance(size, str):
if size[-1] == "%":
return Fraction(float(size[:-1]) / 100, fraction_ref)
raise ValueError("Unknown format") | Create a Fixed unit when the first argument is a float, or a Fraction unit if that is a string that ends with %. The second argument is only meaningful when Fraction unit is created. >>> a = Size.from_any(1.2) # => Size.Fixed(1.2) >>> Size.from_any("50%", a) # => Size.Fraction(0.5, a) |
172,230 | import numpy as np
import matplotlib as mpl
from matplotlib import _api
from matplotlib.gridspec import SubplotSpec
import matplotlib.transforms as mtransforms
from . import axes_size as Size
def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):
total_width = fig_w * w
max_height = fig_h * h
# Determine the k factors.
n = len(equal_heights)
eq_rels, eq_abss = equal_heights.T
sm_rels, sm_abss = summed_widths.T
A = np.diag([*eq_rels, 0])
A[:n, -1] = -1
A[-1, :-1] = sm_rels
B = [*(-eq_abss), total_width - sm_abss.sum()]
# A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that
# eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height
# sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width
# (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.)
*karray, height = np.linalg.solve(A, B)
if height > max_height: # Additionally, upper-bound the height.
karray = (max_height - eq_abss) / eq_rels
# Compute the offsets corresponding to these factors.
ox = np.cumsum([0, *(sm_rels * karray + sm_abss)])
ww = (ox[-1] - ox[0]) / fig_w
h0_rel, h0_abs = equal_heights[0]
hh = (karray[0]*h0_rel + h0_abs) / fig_h
pb = mtransforms.Bbox.from_bounds(x, y, w, h)
pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
x0, y0 = pb1.anchored(anchor, pb).p0
return x0, y0, ox, hh | null |
172,231 | import numpy as np
import matplotlib as mpl
from matplotlib import _api
from matplotlib.gridspec import SubplotSpec
import matplotlib.transforms as mtransforms
from . import axes_size as Size
def make_axes_locatable(axes):
divider = AxesDivider(axes)
locator = divider.new_locator(nx=0, ny=0)
axes.set_axes_locator(locator)
return divider
The provided code snippet includes necessary dependencies for implementing the `make_axes_area_auto_adjustable` function. Write a Python function `def make_axes_area_auto_adjustable( ax, use_axes=None, pad=0.1, adjust_dirs=None)` to solve the following problem:
Add auto-adjustable padding around *ax* to take its decorations (title, labels, ticks, ticklabels) into account during layout, using `.Divider.add_auto_adjustable_area`. By default, padding is determined from the decorations of *ax*. Pass *use_axes* to consider the decorations of other Axes instead.
Here is the function:
def make_axes_area_auto_adjustable(
ax, use_axes=None, pad=0.1, adjust_dirs=None):
"""
Add auto-adjustable padding around *ax* to take its decorations (title,
labels, ticks, ticklabels) into account during layout, using
`.Divider.add_auto_adjustable_area`.
By default, padding is determined from the decorations of *ax*.
Pass *use_axes* to consider the decorations of other Axes instead.
"""
if adjust_dirs is None:
adjust_dirs = ["left", "right", "bottom", "top"]
divider = make_axes_locatable(ax)
if use_axes is None:
use_axes = ax
divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad,
adjust_dirs=adjust_dirs) | Add auto-adjustable padding around *ax* to take its decorations (title, labels, ticks, ticklabels) into account during layout, using `.Divider.add_auto_adjustable_area`. By default, padding is determined from the decorations of *ax*. Pass *use_axes* to consider the decorations of other Axes instead. |
172,232 | from matplotlib import _api, cbook
import matplotlib.artist as martist
import matplotlib.transforms as mtransforms
from matplotlib.transforms import Bbox
from .mpl_axes import Axes
host_axes_class_factory = host_subplot_class_factory = \
cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class")
class Axes(maxes.Axes):
class AxisDict(dict):
def __init__(self, axes):
self.axes = axes
super().__init__()
def __getitem__(self, k):
if isinstance(k, tuple):
r = SimpleChainedObjects(
# super() within a list comprehension needs explicit args.
[super(Axes.AxisDict, self).__getitem__(k1) for k1 in k])
return r
elif isinstance(k, slice):
if k.start is None and k.stop is None and k.step is None:
return SimpleChainedObjects(list(self.values()))
else:
raise ValueError("Unsupported slice")
else:
return dict.__getitem__(self, k)
def __call__(self, *v, **kwargs):
return maxes.Axes.axis(self.axes, *v, **kwargs)
def axis(self):
return self._axislines
def clear(self):
# docstring inherited
super().clear()
# Init axis artists.
self._axislines = self.AxisDict(self)
self._axislines.update(
bottom=SimpleAxisArtist(self.xaxis, 1, self.spines["bottom"]),
top=SimpleAxisArtist(self.xaxis, 2, self.spines["top"]),
left=SimpleAxisArtist(self.yaxis, 1, self.spines["left"]),
right=SimpleAxisArtist(self.yaxis, 2, self.spines["right"]))
The provided code snippet includes necessary dependencies for implementing the `host_axes` function. Write a Python function `def host_axes(*args, axes_class=Axes, figure=None, **kwargs)` to solve the following problem:
Create axes that can act as a hosts to parasitic axes. Parameters ---------- figure : `~matplotlib.figure.Figure` Figure to which the axes will be added. Defaults to the current figure `.pyplot.gcf()`. *args, **kwargs Will be passed on to the underlying `~.axes.Axes` object creation.
Here is the function:
def host_axes(*args, axes_class=Axes, figure=None, **kwargs):
"""
Create axes that can act as a hosts to parasitic axes.
Parameters
----------
figure : `~matplotlib.figure.Figure`
Figure to which the axes will be added. Defaults to the current figure
`.pyplot.gcf()`.
*args, **kwargs
Will be passed on to the underlying `~.axes.Axes` object creation.
"""
import matplotlib.pyplot as plt
host_axes_class = host_axes_class_factory(axes_class)
if figure is None:
figure = plt.gcf()
ax = host_axes_class(figure, *args, **kwargs)
figure.add_axes(ax)
return ax | Create axes that can act as a hosts to parasitic axes. Parameters ---------- figure : `~matplotlib.figure.Figure` Figure to which the axes will be added. Defaults to the current figure `.pyplot.gcf()`. *args, **kwargs Will be passed on to the underlying `~.axes.Axes` object creation. |
172,233 | from matplotlib import _api, _docstring
from matplotlib.offsetbox import AnchoredOffsetbox
from matplotlib.patches import Patch, Rectangle
from matplotlib.path import Path
from matplotlib.transforms import Bbox, BboxTransformTo
from matplotlib.transforms import IdentityTransform, TransformedBbox
from . import axes_size as Size
from .parasite_axes import HostAxes
class AnchoredZoomLocator(AnchoredLocatorBase):
def __init__(self, parent_axes, zoom, loc,
borderpad=0.5,
bbox_to_anchor=None,
bbox_transform=None):
self.parent_axes = parent_axes
self.zoom = zoom
if bbox_to_anchor is None:
bbox_to_anchor = parent_axes.bbox
super().__init__(
bbox_to_anchor, None, loc, borderpad=borderpad,
bbox_transform=bbox_transform)
def get_bbox(self, renderer):
bb = self.parent_axes.transData.transform_bbox(self.axes.viewLim)
fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
pad = self.pad * fontsize
return (
Bbox.from_bounds(
0, 0, abs(bb.width * self.zoom), abs(bb.height * self.zoom))
.padded(pad))
def _add_inset_axes(parent_axes, inset_axes):
"""Helper function to add an inset axes and disable navigation in it."""
parent_axes.figure.add_axes(inset_axes)
inset_axes.set_navigate(False)
def inset_axes(parent_axes, width, height, loc='upper right',
bbox_to_anchor=None, bbox_transform=None,
axes_class=None, axes_kwargs=None,
borderpad=0.5):
"""
Create an inset axes with a given width and height.
Both sizes used can be specified either in inches or percentage.
For example,::
inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left')
creates in inset axes in the lower left corner of *parent_axes* which spans
over 30%% in height and 40%% in width of the *parent_axes*. Since the usage
of `.inset_axes` may become slightly tricky when exceeding such standard
cases, it is recommended to read :doc:`the examples
</gallery/axes_grid1/inset_locator_demo>`.
Notes
-----
The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted
differently from that of legend. The value of bbox_to_anchor
(or the return value of its get_points method; the default is
*parent_axes.bbox*) is transformed by the bbox_transform (the default
is Identity transform) and then interpreted as points in the pixel
coordinate (which is dpi dependent).
Thus, following three calls are identical and creates an inset axes
with respect to the *parent_axes*::
axins = inset_axes(parent_axes, "30%%", "40%%")
axins = inset_axes(parent_axes, "30%%", "40%%",
bbox_to_anchor=parent_axes.bbox)
axins = inset_axes(parent_axes, "30%%", "40%%",
bbox_to_anchor=(0, 0, 1, 1),
bbox_transform=parent_axes.transAxes)
Parameters
----------
parent_axes : `matplotlib.axes.Axes`
Axes to place the inset axes.
width, height : float or str
Size of the inset axes to create. If a float is provided, it is
the size in inches, e.g. *width=1.3*. If a string is provided, it is
the size in relative units, e.g. *width='40%%'*. By default, i.e. if
neither *bbox_to_anchor* nor *bbox_transform* are specified, those
are relative to the parent_axes. Otherwise, they are to be understood
relative to the bounding box provided via *bbox_to_anchor*.
loc : str, default: 'upper right'
Location to place the inset axes. Valid locations are
'upper left', 'upper center', 'upper right',
'center left', 'center', 'center right',
'lower left', 'lower center', 'lower right'.
For backward compatibility, numeric values are accepted as well.
See the parameter *loc* of `.Legend` for details.
bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
Bbox that the inset axes will be anchored to. If None,
a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set
to *parent_axes.transAxes* or *parent_axes.figure.transFigure*.
Otherwise, *parent_axes.bbox* is used. If a tuple, can be either
[left, bottom, width, height], or [left, bottom].
If the kwargs *width* and/or *height* are specified in relative units,
the 2-tuple [left, bottom] cannot be used. Note that,
unless *bbox_transform* is set, the units of the bounding box
are interpreted in the pixel coordinate. When using *bbox_to_anchor*
with tuple, it almost always makes sense to also specify
a *bbox_transform*. This might often be the axes transform
*parent_axes.transAxes*.
bbox_transform : `~matplotlib.transforms.Transform`, optional
Transformation for the bbox that contains the inset axes.
If None, a `.transforms.IdentityTransform` is used. The value
of *bbox_to_anchor* (or the return value of its get_points method)
is transformed by the *bbox_transform* and then interpreted
as points in the pixel coordinate (which is dpi dependent).
You may provide *bbox_to_anchor* in some normalized coordinate,
and give an appropriate transform (e.g., *parent_axes.transAxes*).
axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
The type of the newly created inset axes.
axes_kwargs : dict, optional
Keyword arguments to pass to the constructor of the inset axes.
Valid arguments include:
%(Axes:kwdoc)s
borderpad : float, default: 0.5
Padding between inset axes and the bbox_to_anchor.
The units are axes font size, i.e. for a default font size of 10 points
*borderpad = 0.5* is equivalent to a padding of 5 points.
Returns
-------
inset_axes : *axes_class*
Inset axes object created.
"""
if axes_class is None:
axes_class = HostAxes
if axes_kwargs is None:
axes_kwargs = {}
inset_axes = axes_class(parent_axes.figure, parent_axes.get_position(),
**axes_kwargs)
if bbox_transform in [parent_axes.transAxes,
parent_axes.figure.transFigure]:
if bbox_to_anchor is None:
_api.warn_external("Using the axes or figure transform requires a "
"bounding box in the respective coordinates. "
"Using bbox_to_anchor=(0, 0, 1, 1) now.")
bbox_to_anchor = (0, 0, 1, 1)
if bbox_to_anchor is None:
bbox_to_anchor = parent_axes.bbox
if (isinstance(bbox_to_anchor, tuple) and
(isinstance(width, str) or isinstance(height, str))):
if len(bbox_to_anchor) != 4:
raise ValueError("Using relative units for width or height "
"requires to provide a 4-tuple or a "
"`Bbox` instance to `bbox_to_anchor.")
axes_locator = AnchoredSizeLocator(bbox_to_anchor,
width, height,
loc=loc,
bbox_transform=bbox_transform,
borderpad=borderpad)
inset_axes.set_axes_locator(axes_locator)
_add_inset_axes(parent_axes, inset_axes)
return inset_axes
HostAxes = SubplotHost = host_axes_class_factory(Axes)
The provided code snippet includes necessary dependencies for implementing the `zoomed_inset_axes` function. Write a Python function `def zoomed_inset_axes(parent_axes, zoom, loc='upper right', bbox_to_anchor=None, bbox_transform=None, axes_class=None, axes_kwargs=None, borderpad=0.5)` to solve the following problem:
Create an anchored inset axes by scaling a parent axes. For usage, also see :doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`. Parameters ---------- parent_axes : `~matplotlib.axes.Axes` Axes to place the inset axes. zoom : float Scaling factor of the data axes. *zoom* > 1 will enlarge the coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the coordinates (i.e., "zoomed out"). loc : str, default: 'upper right' Location to place the inset axes. Valid locations are 'upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'. For backward compatibility, numeric values are accepted as well. See the parameter *loc* of `.Legend` for details. bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional Bbox that the inset axes will be anchored to. If None, *parent_axes.bbox* is used. If a tuple, can be either [left, bottom, width, height], or [left, bottom]. If the kwargs *width* and/or *height* are specified in relative units, the 2-tuple [left, bottom] cannot be used. Note that the units of the bounding box are determined through the transform in use. When using *bbox_to_anchor* it almost always makes sense to also specify a *bbox_transform*. This might often be the axes transform *parent_axes.transAxes*. bbox_transform : `~matplotlib.transforms.Transform`, optional Transformation for the bbox that contains the inset axes. If None, a `.transforms.IdentityTransform` is used (i.e. pixel coordinates). This is useful when not providing any argument to *bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes sense to also specify a *bbox_transform*. This might often be the axes transform *parent_axes.transAxes*. Inversely, when specifying the axes- or figure-transform here, be aware that not specifying *bbox_to_anchor* will use *parent_axes.bbox*, the units of which are in display (pixel) coordinates. axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes` The type of the newly created inset axes. axes_kwargs : dict, optional Keyword arguments to pass to the constructor of the inset axes. Valid arguments include: %(Axes:kwdoc)s borderpad : float, default: 0.5 Padding between inset axes and the bbox_to_anchor. The units are axes font size, i.e. for a default font size of 10 points *borderpad = 0.5* is equivalent to a padding of 5 points. Returns ------- inset_axes : *axes_class* Inset axes object created.
Here is the function:
def zoomed_inset_axes(parent_axes, zoom, loc='upper right',
bbox_to_anchor=None, bbox_transform=None,
axes_class=None, axes_kwargs=None,
borderpad=0.5):
"""
Create an anchored inset axes by scaling a parent axes. For usage, also see
:doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`.
Parameters
----------
parent_axes : `~matplotlib.axes.Axes`
Axes to place the inset axes.
zoom : float
Scaling factor of the data axes. *zoom* > 1 will enlarge the
coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the
coordinates (i.e., "zoomed out").
loc : str, default: 'upper right'
Location to place the inset axes. Valid locations are
'upper left', 'upper center', 'upper right',
'center left', 'center', 'center right',
'lower left', 'lower center', 'lower right'.
For backward compatibility, numeric values are accepted as well.
See the parameter *loc* of `.Legend` for details.
bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
Bbox that the inset axes will be anchored to. If None,
*parent_axes.bbox* is used. If a tuple, can be either
[left, bottom, width, height], or [left, bottom].
If the kwargs *width* and/or *height* are specified in relative units,
the 2-tuple [left, bottom] cannot be used. Note that
the units of the bounding box are determined through the transform
in use. When using *bbox_to_anchor* it almost always makes sense to
also specify a *bbox_transform*. This might often be the axes transform
*parent_axes.transAxes*.
bbox_transform : `~matplotlib.transforms.Transform`, optional
Transformation for the bbox that contains the inset axes.
If None, a `.transforms.IdentityTransform` is used (i.e. pixel
coordinates). This is useful when not providing any argument to
*bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes
sense to also specify a *bbox_transform*. This might often be the
axes transform *parent_axes.transAxes*. Inversely, when specifying
the axes- or figure-transform here, be aware that not specifying
*bbox_to_anchor* will use *parent_axes.bbox*, the units of which are
in display (pixel) coordinates.
axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
The type of the newly created inset axes.
axes_kwargs : dict, optional
Keyword arguments to pass to the constructor of the inset axes.
Valid arguments include:
%(Axes:kwdoc)s
borderpad : float, default: 0.5
Padding between inset axes and the bbox_to_anchor.
The units are axes font size, i.e. for a default font size of 10 points
*borderpad = 0.5* is equivalent to a padding of 5 points.
Returns
-------
inset_axes : *axes_class*
Inset axes object created.
"""
if axes_class is None:
axes_class = HostAxes
if axes_kwargs is None:
axes_kwargs = {}
inset_axes = axes_class(parent_axes.figure, parent_axes.get_position(),
**axes_kwargs)
axes_locator = AnchoredZoomLocator(parent_axes, zoom=zoom, loc=loc,
bbox_to_anchor=bbox_to_anchor,
bbox_transform=bbox_transform,
borderpad=borderpad)
inset_axes.set_axes_locator(axes_locator)
_add_inset_axes(parent_axes, inset_axes)
return inset_axes | Create an anchored inset axes by scaling a parent axes. For usage, also see :doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`. Parameters ---------- parent_axes : `~matplotlib.axes.Axes` Axes to place the inset axes. zoom : float Scaling factor of the data axes. *zoom* > 1 will enlarge the coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the coordinates (i.e., "zoomed out"). loc : str, default: 'upper right' Location to place the inset axes. Valid locations are 'upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'. For backward compatibility, numeric values are accepted as well. See the parameter *loc* of `.Legend` for details. bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional Bbox that the inset axes will be anchored to. If None, *parent_axes.bbox* is used. If a tuple, can be either [left, bottom, width, height], or [left, bottom]. If the kwargs *width* and/or *height* are specified in relative units, the 2-tuple [left, bottom] cannot be used. Note that the units of the bounding box are determined through the transform in use. When using *bbox_to_anchor* it almost always makes sense to also specify a *bbox_transform*. This might often be the axes transform *parent_axes.transAxes*. bbox_transform : `~matplotlib.transforms.Transform`, optional Transformation for the bbox that contains the inset axes. If None, a `.transforms.IdentityTransform` is used (i.e. pixel coordinates). This is useful when not providing any argument to *bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes sense to also specify a *bbox_transform*. This might often be the axes transform *parent_axes.transAxes*. Inversely, when specifying the axes- or figure-transform here, be aware that not specifying *bbox_to_anchor* will use *parent_axes.bbox*, the units of which are in display (pixel) coordinates. axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes` The type of the newly created inset axes. axes_kwargs : dict, optional Keyword arguments to pass to the constructor of the inset axes. Valid arguments include: %(Axes:kwdoc)s borderpad : float, default: 0.5 Padding between inset axes and the bbox_to_anchor. The units are axes font size, i.e. for a default font size of 10 points *borderpad = 0.5* is equivalent to a padding of 5 points. Returns ------- inset_axes : *axes_class* Inset axes object created. |
172,234 | from matplotlib import _api, _docstring
from matplotlib.offsetbox import AnchoredOffsetbox
from matplotlib.patches import Patch, Rectangle
from matplotlib.path import Path
from matplotlib.transforms import Bbox, BboxTransformTo
from matplotlib.transforms import IdentityTransform, TransformedBbox
from . import axes_size as Size
from .parasite_axes import HostAxes
class BboxPatch(Patch):
def __init__(self, bbox, **kwargs):
"""
Patch showing the shape bounded by a Bbox.
Parameters
----------
bbox : `~matplotlib.transforms.Bbox`
Bbox to use for the extents of this patch.
**kwargs
Patch properties. Valid arguments include:
%(Patch:kwdoc)s
"""
if "transform" in kwargs:
raise ValueError("transform should not be set")
kwargs["transform"] = IdentityTransform()
super().__init__(**kwargs)
self.bbox = bbox
def get_path(self):
# docstring inherited
x0, y0, x1, y1 = self.bbox.extents
return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
class BboxConnector(Patch):
def get_bbox_edge_pos(bbox, loc):
"""
Return the ``(x, y)`` coordinates of corner *loc* of *bbox*; parameters
behave as documented for the `.BboxConnector` constructor.
"""
x0, y0, x1, y1 = bbox.extents
if loc == 1:
return x1, y1
elif loc == 2:
return x0, y1
elif loc == 3:
return x0, y0
elif loc == 4:
return x1, y0
def connect_bbox(bbox1, bbox2, loc1, loc2=None):
"""
Construct a `.Path` connecting corner *loc1* of *bbox1* to corner
*loc2* of *bbox2*, where parameters behave as documented as for the
`.BboxConnector` constructor.
"""
if isinstance(bbox1, Rectangle):
bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform())
if isinstance(bbox2, Rectangle):
bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform())
if loc2 is None:
loc2 = loc1
x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)
x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)
return Path([[x1, y1], [x2, y2]])
def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):
"""
Connect two bboxes with a straight line.
Parameters
----------
bbox1, bbox2 : `~matplotlib.transforms.Bbox`
Bounding boxes to connect.
loc1, loc2 : {1, 2, 3, 4}
Corner of *bbox1* and *bbox2* to draw the line. Valid values are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4
*loc2* is optional and defaults to *loc1*.
**kwargs
Patch properties for the line drawn. Valid arguments include:
%(Patch:kwdoc)s
"""
if "transform" in kwargs:
raise ValueError("transform should not be set")
kwargs["transform"] = IdentityTransform()
if 'fill' in kwargs:
super().__init__(**kwargs)
else:
fill = bool({'fc', 'facecolor', 'color'}.intersection(kwargs))
super().__init__(fill=fill, **kwargs)
self.bbox1 = bbox1
self.bbox2 = bbox2
self.loc1 = loc1
self.loc2 = loc2
def get_path(self):
# docstring inherited
return self.connect_bbox(self.bbox1, self.bbox2,
self.loc1, self.loc2)
class _TransformedBboxWithCallback(TransformedBbox):
"""
Variant of `.TransformBbox` which calls *callback* before returning points.
Used by `.mark_inset` to unstale the parent axes' viewlim as needed.
"""
def __init__(self, *args, callback, **kwargs):
super().__init__(*args, **kwargs)
self._callback = callback
def get_points(self):
self._callback()
return super().get_points()
The provided code snippet includes necessary dependencies for implementing the `mark_inset` function. Write a Python function `def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs)` to solve the following problem:
Draw a box to mark the location of an area represented by an inset axes. This function draws a box in *parent_axes* at the bounding box of *inset_axes*, and shows a connection with the inset axes by drawing lines at the corners, giving a "zoomed in" effect. Parameters ---------- parent_axes : `~matplotlib.axes.Axes` Axes which contains the area of the inset axes. inset_axes : `~matplotlib.axes.Axes` The inset axes. loc1, loc2 : {1, 2, 3, 4} Corners to use for connecting the inset axes and the area in the parent axes. **kwargs Patch properties for the lines and box drawn: %(Patch:kwdoc)s Returns ------- pp : `~matplotlib.patches.Patch` The patch drawn to represent the area of the inset axes. p1, p2 : `~matplotlib.patches.Patch` The patches connecting two corners of the inset axes and its area.
Here is the function:
def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
"""
Draw a box to mark the location of an area represented by an inset axes.
This function draws a box in *parent_axes* at the bounding box of
*inset_axes*, and shows a connection with the inset axes by drawing lines
at the corners, giving a "zoomed in" effect.
Parameters
----------
parent_axes : `~matplotlib.axes.Axes`
Axes which contains the area of the inset axes.
inset_axes : `~matplotlib.axes.Axes`
The inset axes.
loc1, loc2 : {1, 2, 3, 4}
Corners to use for connecting the inset axes and the area in the
parent axes.
**kwargs
Patch properties for the lines and box drawn:
%(Patch:kwdoc)s
Returns
-------
pp : `~matplotlib.patches.Patch`
The patch drawn to represent the area of the inset axes.
p1, p2 : `~matplotlib.patches.Patch`
The patches connecting two corners of the inset axes and its area.
"""
rect = _TransformedBboxWithCallback(
inset_axes.viewLim, parent_axes.transData,
callback=parent_axes._unstale_viewLim)
if 'fill' in kwargs:
pp = BboxPatch(rect, **kwargs)
else:
fill = bool({'fc', 'facecolor', 'color'}.intersection(kwargs))
pp = BboxPatch(rect, fill=fill, **kwargs)
parent_axes.add_patch(pp)
p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
inset_axes.add_patch(p1)
p1.set_clip_on(False)
p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)
inset_axes.add_patch(p2)
p2.set_clip_on(False)
return pp, p1, p2 | Draw a box to mark the location of an area represented by an inset axes. This function draws a box in *parent_axes* at the bounding box of *inset_axes*, and shows a connection with the inset axes by drawing lines at the corners, giving a "zoomed in" effect. Parameters ---------- parent_axes : `~matplotlib.axes.Axes` Axes which contains the area of the inset axes. inset_axes : `~matplotlib.axes.Axes` The inset axes. loc1, loc2 : {1, 2, 3, 4} Corners to use for connecting the inset axes and the area in the parent axes. **kwargs Patch properties for the lines and box drawn: %(Patch:kwdoc)s Returns ------- pp : `~matplotlib.patches.Patch` The patch drawn to represent the area of the inset axes. p1, p2 : `~matplotlib.patches.Patch` The patches connecting two corners of the inset axes and its area. |
172,235 | import numpy as np
from .axes_divider import make_axes_locatable, Size
from .mpl_axes import Axes
def make_axes_locatable(axes):
divider = AxesDivider(axes)
locator = divider.new_locator(nx=0, ny=0)
axes.set_axes_locator(locator)
return divider
The provided code snippet includes necessary dependencies for implementing the `make_rgb_axes` function. Write a Python function `def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs)` to solve the following problem:
Parameters ---------- ax : `~matplotlib.axes.Axes` Axes instance to create the RGB Axes in. pad : float, optional Fraction of the Axes height to pad. axes_class : `matplotlib.axes.Axes` or None, optional Axes class to use for the R, G, and B Axes. If None, use the same class as *ax*. **kwargs : Forwarded to *axes_class* init for the R, G, and B Axes.
Here is the function:
def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs):
"""
Parameters
----------
ax : `~matplotlib.axes.Axes`
Axes instance to create the RGB Axes in.
pad : float, optional
Fraction of the Axes height to pad.
axes_class : `matplotlib.axes.Axes` or None, optional
Axes class to use for the R, G, and B Axes. If None, use
the same class as *ax*.
**kwargs :
Forwarded to *axes_class* init for the R, G, and B Axes.
"""
divider = make_axes_locatable(ax)
pad_size = pad * Size.AxesY(ax)
xsize = ((1-2*pad)/3) * Size.AxesX(ax)
ysize = ((1-2*pad)/3) * Size.AxesY(ax)
divider.set_horizontal([Size.AxesX(ax), pad_size, xsize])
divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize])
ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1))
ax_rgb = []
if axes_class is None:
axes_class = type(ax)
for ny in [4, 2, 0]:
ax1 = axes_class(ax.get_figure(), ax.get_position(original=True),
sharex=ax, sharey=ax, **kwargs)
locator = divider.new_locator(nx=2, ny=ny)
ax1.set_axes_locator(locator)
for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels():
t.set_visible(False)
try:
for axis in ax1.axis.values():
axis.major_ticklabels.set_visible(False)
except AttributeError:
pass
ax_rgb.append(ax1)
fig = ax.get_figure()
for ax1 in ax_rgb:
fig.add_axes(ax1)
return ax_rgb | Parameters ---------- ax : `~matplotlib.axes.Axes` Axes instance to create the RGB Axes in. pad : float, optional Fraction of the Axes height to pad. axes_class : `matplotlib.axes.Axes` or None, optional Axes class to use for the R, G, and B Axes. If None, use the same class as *ax*. **kwargs : Forwarded to *axes_class* init for the R, G, and B Axes. |
172,236 | from numbers import Number
import functools
import numpy as np
from matplotlib import _api, cbook
from matplotlib.gridspec import SubplotSpec
from .axes_divider import Size, SubplotDivider, Divider
from .mpl_axes import Axes
def _tick_only(ax, bottom_on, left_on):
bottom_off = not bottom_on
left_off = not left_on
ax.axis["bottom"].toggle(ticklabels=bottom_off, label=bottom_off)
ax.axis["left"].toggle(ticklabels=left_off, label=left_off) | null |
172,237 | from collections import defaultdict
import functools
import itertools
import math
import textwrap
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _docstring, _preprocess_data
import matplotlib.artist as martist
import matplotlib.axes as maxes
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
import matplotlib.image as mimage
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.container as mcontainer
import matplotlib.transforms as mtransforms
from matplotlib.axes import Axes
from matplotlib.axes._base import _axis_method_wrapper, _process_plot_format
from matplotlib.transforms import Bbox
from matplotlib.tri._triangulation import Triangulation
from . import art3d
from . import proj3d
from . import axis3d
The provided code snippet includes necessary dependencies for implementing the `get_test_data` function. Write a Python function `def get_test_data(delta=0.05)` to solve the following problem:
Return a tuple X, Y, Z with a test data set.
Here is the function:
def get_test_data(delta=0.05):
"""Return a tuple X, Y, Z with a test data set."""
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)
Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /
(2 * np.pi * 0.5 * 1.5))
Z = Z2 - Z1
X = X * 10
Y = Y * 10
Z = Z * 500
return X, Y, Z | Return a tuple X, Y, Z with a test data set. |
172,238 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
The provided code snippet includes necessary dependencies for implementing the `_norm_angle` function. Write a Python function `def _norm_angle(a)` to solve the following problem:
Return the given angle normalized to -180 < *a* <= 180 degrees.
Here is the function:
def _norm_angle(a):
"""Return the given angle normalized to -180 < *a* <= 180 degrees."""
a = (a + 360) % 360
if a > 180:
a = a - 360
return a | Return the given angle normalized to -180 < *a* <= 180 degrees. |
172,239 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
The provided code snippet includes necessary dependencies for implementing the `_norm_text_angle` function. Write a Python function `def _norm_text_angle(a)` to solve the following problem:
Return the given angle normalized to -90 < *a* <= 90 degrees.
Here is the function:
def _norm_text_angle(a):
"""Return the given angle normalized to -90 < *a* <= 90 degrees."""
a = (a + 180) % 180
if a > 90:
a = a - 180
return a | Return the given angle normalized to -90 < *a* <= 90 degrees. |
172,240 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
The provided code snippet includes necessary dependencies for implementing the `get_dir_vector` function. Write a Python function `def get_dir_vector(zdir)` to solve the following problem:
Return a direction vector. Parameters ---------- zdir : {'x', 'y', 'z', None, 3-tuple} The direction. Possible values are: - 'x': equivalent to (1, 0, 0) - 'y': equivalent to (0, 1, 0) - 'z': equivalent to (0, 0, 1) - *None*: equivalent to (0, 0, 0) - an iterable (x, y, z) is converted to a NumPy array, if not already Returns ------- x, y, z : array-like The direction vector.
Here is the function:
def get_dir_vector(zdir):
"""
Return a direction vector.
Parameters
----------
zdir : {'x', 'y', 'z', None, 3-tuple}
The direction. Possible values are:
- 'x': equivalent to (1, 0, 0)
- 'y': equivalent to (0, 1, 0)
- 'z': equivalent to (0, 0, 1)
- *None*: equivalent to (0, 0, 0)
- an iterable (x, y, z) is converted to a NumPy array, if not already
Returns
-------
x, y, z : array-like
The direction vector.
"""
if zdir == 'x':
return np.array((1, 0, 0))
elif zdir == 'y':
return np.array((0, 1, 0))
elif zdir == 'z':
return np.array((0, 0, 1))
elif zdir is None:
return np.array((0, 0, 0))
elif np.iterable(zdir) and len(zdir) == 3:
return np.array(zdir)
else:
raise ValueError("'x', 'y', 'z', None or vector of length 3 expected") | Return a direction vector. Parameters ---------- zdir : {'x', 'y', 'z', None, 3-tuple} The direction. Possible values are: - 'x': equivalent to (1, 0, 0) - 'y': equivalent to (0, 1, 0) - 'z': equivalent to (0, 0, 1) - *None*: equivalent to (0, 0, 0) - an iterable (x, y, z) is converted to a NumPy array, if not already Returns ------- x, y, z : array-like The direction vector. |
172,241 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class Text3D(mtext.Text):
"""
Text object with 3D position and direction.
Parameters
----------
x, y, z : float
The position of the text.
text : str
The text string to display.
zdir : {'x', 'y', 'z', None, 3-tuple}
The direction of the text. See `.get_dir_vector` for a description of
the values.
Other Parameters
----------------
**kwargs
All other parameters are passed on to `~matplotlib.text.Text`.
"""
def __init__(self, x=0, y=0, z=0, text='', zdir='z', **kwargs):
mtext.Text.__init__(self, x, y, text, **kwargs)
self.set_3d_properties(z, zdir)
def get_position_3d(self):
"""Return the (x, y, z) position of the text."""
return self._x, self._y, self._z
def set_position_3d(self, xyz, zdir=None):
"""
Set the (*x*, *y*, *z*) position of the text.
Parameters
----------
xyz : (float, float, float)
The position in 3D space.
zdir : {'x', 'y', 'z', None, 3-tuple}
The direction of the text. If unspecified, the *zdir* will not be
changed. See `.get_dir_vector` for a description of the values.
"""
super().set_position(xyz[:2])
self.set_z(xyz[2])
if zdir is not None:
self._dir_vec = get_dir_vector(zdir)
def set_z(self, z):
"""
Set the *z* position of the text.
Parameters
----------
z : float
"""
self._z = z
self.stale = True
def set_3d_properties(self, z=0, zdir='z'):
"""
Set the *z* position and direction of the text.
Parameters
----------
z : float
The z-position in 3D space.
zdir : {'x', 'y', 'z', 3-tuple}
The direction of the text. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
self._z = z
self._dir_vec = get_dir_vector(zdir)
self.stale = True
def draw(self, renderer):
position3d = np.array((self._x, self._y, self._z))
proj = proj3d.proj_trans_points(
[position3d, position3d + self._dir_vec], self.axes.M)
dx = proj[0][1] - proj[0][0]
dy = proj[1][1] - proj[1][0]
angle = math.degrees(math.atan2(dy, dx))
with cbook._setattr_cm(self, _x=proj[0][0], _y=proj[1][0],
_rotation=_norm_text_angle(angle)):
mtext.Text.draw(self, renderer)
self.stale = False
def get_tightbbox(self, renderer=None):
# Overwriting the 2d Text behavior which is not valid for 3d.
# For now, just return None to exclude from layout calculation.
return None
The provided code snippet includes necessary dependencies for implementing the `text_2d_to_3d` function. Write a Python function `def text_2d_to_3d(obj, z=0, zdir='z')` to solve the following problem:
Convert a `.Text` to a `.Text3D` object. Parameters ---------- z : float The z-position in 3D space. zdir : {'x', 'y', 'z', 3-tuple} The direction of the text. Default: 'z'. See `.get_dir_vector` for a description of the values.
Here is the function:
def text_2d_to_3d(obj, z=0, zdir='z'):
"""
Convert a `.Text` to a `.Text3D` object.
Parameters
----------
z : float
The z-position in 3D space.
zdir : {'x', 'y', 'z', 3-tuple}
The direction of the text. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
obj.__class__ = Text3D
obj.set_3d_properties(z, zdir) | Convert a `.Text` to a `.Text3D` object. Parameters ---------- z : float The z-position in 3D space. zdir : {'x', 'y', 'z', 3-tuple} The direction of the text. Default: 'z'. See `.get_dir_vector` for a description of the values. |
172,242 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class Line3D(lines.Line2D):
"""
3D line object.
"""
def __init__(self, xs, ys, zs, *args, **kwargs):
"""
Parameters
----------
xs : array-like
The x-data to be plotted.
ys : array-like
The y-data to be plotted.
zs : array-like
The z-data to be plotted.
Additional arguments are passed onto :func:`~matplotlib.lines.Line2D`.
"""
super().__init__([], [], *args, **kwargs)
self.set_data_3d(xs, ys, zs)
def set_3d_properties(self, zs=0, zdir='z'):
"""
Set the *z* position and direction of the line.
Parameters
----------
zs : float or array of floats
The location along the *zdir* axis in 3D space to position the
line.
zdir : {'x', 'y', 'z'}
Plane to plot line orthogonal to. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
xs = self.get_xdata()
ys = self.get_ydata()
zs = cbook._to_unmasked_float_array(zs).ravel()
zs = np.broadcast_to(zs, len(xs))
self._verts3d = juggle_axes(xs, ys, zs, zdir)
self.stale = True
def set_data_3d(self, *args):
"""
Set the x, y and z data
Parameters
----------
x : array-like
The x-data to be plotted.
y : array-like
The y-data to be plotted.
z : array-like
The z-data to be plotted.
Notes
-----
Accepts x, y, z arguments or a single array-like (x, y, z)
"""
if len(args) == 1:
args = args[0]
for name, xyz in zip('xyz', args):
if not np.iterable(xyz):
raise RuntimeError(f'{name} must be a sequence')
self._verts3d = args
self.stale = True
def get_data_3d(self):
"""
Get the current data
Returns
-------
verts3d : length-3 tuple or array-like
The current data as a tuple or array-like.
"""
return self._verts3d
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M)
self.set_data(xs, ys)
super().draw(renderer)
self.stale = False
The provided code snippet includes necessary dependencies for implementing the `line_2d_to_3d` function. Write a Python function `def line_2d_to_3d(line, zs=0, zdir='z')` to solve the following problem:
Convert a `.Line2D` to a `.Line3D` object. Parameters ---------- zs : float The location along the *zdir* axis in 3D space to position the line. zdir : {'x', 'y', 'z'} Plane to plot line orthogonal to. Default: 'z'. See `.get_dir_vector` for a description of the values.
Here is the function:
def line_2d_to_3d(line, zs=0, zdir='z'):
"""
Convert a `.Line2D` to a `.Line3D` object.
Parameters
----------
zs : float
The location along the *zdir* axis in 3D space to position the line.
zdir : {'x', 'y', 'z'}
Plane to plot line orthogonal to. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
line.__class__ = Line3D
line.set_3d_properties(zs, zdir) | Convert a `.Line2D` to a `.Line3D` object. Parameters ---------- zs : float The location along the *zdir* axis in 3D space to position the line. zdir : {'x', 'y', 'z'} Plane to plot line orthogonal to. Default: 'z'. See `.get_dir_vector` for a description of the values. |
172,243 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
def _paths_to_3d_segments(paths, zs=0, zdir='z'):
"""Convert paths from a collection object to 3D segments."""
if not np.iterable(zs):
zs = np.broadcast_to(zs, len(paths))
else:
if len(zs) != len(paths):
raise ValueError('Number of z-coordinates does not match paths.')
segs = [_path_to_3d_segment(path, pathz, zdir)
for path, pathz in zip(paths, zs)]
return segs
class Line3DCollection(LineCollection):
"""
A collection of 3D lines.
"""
def set_sort_zpos(self, val):
"""Set the position to use for z-sorting."""
self._sort_zpos = val
self.stale = True
def set_segments(self, segments):
"""
Set 3D segments.
"""
self._segments3d = segments
super().set_segments([])
def do_3d_projection(self):
"""
Project the points according to renderer matrix.
"""
xyslist = [proj3d.proj_trans_points(points, self.axes.M)
for points in self._segments3d]
segments_2d = [np.column_stack([xs, ys]) for xs, ys, zs in xyslist]
LineCollection.set_segments(self, segments_2d)
# FIXME
minz = 1e9
for xs, ys, zs in xyslist:
minz = min(minz, min(zs))
return minz
The provided code snippet includes necessary dependencies for implementing the `line_collection_2d_to_3d` function. Write a Python function `def line_collection_2d_to_3d(col, zs=0, zdir='z')` to solve the following problem:
Convert a `.LineCollection` to a `.Line3DCollection` object.
Here is the function:
def line_collection_2d_to_3d(col, zs=0, zdir='z'):
"""Convert a `.LineCollection` to a `.Line3DCollection` object."""
segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir)
col.__class__ = Line3DCollection
col.set_segments(segments3d) | Convert a `.LineCollection` to a `.Line3DCollection` object. |
172,244 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class Patch3D(Patch):
"""
3D patch object.
"""
def __init__(self, *args, zs=(), zdir='z', **kwargs):
"""
Parameters
----------
verts :
zs : float
The location along the *zdir* axis in 3D space to position the
patch.
zdir : {'x', 'y', 'z'}
Plane to plot patch orthogonal to. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
super().__init__(*args, **kwargs)
self.set_3d_properties(zs, zdir)
def set_3d_properties(self, verts, zs=0, zdir='z'):
"""
Set the *z* position and direction of the patch.
Parameters
----------
verts :
zs : float
The location along the *zdir* axis in 3D space to position the
patch.
zdir : {'x', 'y', 'z'}
Plane to plot patch orthogonal to. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
zs = np.broadcast_to(zs, len(verts))
self._segment3d = [juggle_axes(x, y, z, zdir)
for ((x, y), z) in zip(verts, zs)]
def get_path(self):
return self._path2d
def do_3d_projection(self):
s = self._segment3d
xs, ys, zs = zip(*s)
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
self.axes.M)
self._path2d = mpath.Path(np.column_stack([vxs, vys]))
return min(vzs)
def _get_patch_verts(patch):
"""Return a list of vertices for the path of a patch."""
trans = patch.get_patch_transform()
path = patch.get_path()
polygons = path.to_polygons(trans)
return polygons[0] if len(polygons) else np.array([])
The provided code snippet includes necessary dependencies for implementing the `patch_2d_to_3d` function. Write a Python function `def patch_2d_to_3d(patch, z=0, zdir='z')` to solve the following problem:
Convert a `.Patch` to a `.Patch3D` object.
Here is the function:
def patch_2d_to_3d(patch, z=0, zdir='z'):
"""Convert a `.Patch` to a `.Patch3D` object."""
verts = _get_patch_verts(patch)
patch.__class__ = Patch3D
patch.set_3d_properties(verts, z, zdir) | Convert a `.Patch` to a `.Patch3D` object. |
172,245 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class PathPatch3D(Patch3D):
"""
3D PathPatch object.
"""
def __init__(self, path, *, zs=(), zdir='z', **kwargs):
"""
Parameters
----------
path :
zs : float
The location along the *zdir* axis in 3D space to position the
path patch.
zdir : {'x', 'y', 'z', 3-tuple}
Plane to plot path patch orthogonal to. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
# Not super().__init__!
Patch.__init__(self, **kwargs)
self.set_3d_properties(path, zs, zdir)
def set_3d_properties(self, path, zs=0, zdir='z'):
"""
Set the *z* position and direction of the path patch.
Parameters
----------
path :
zs : float
The location along the *zdir* axis in 3D space to position the
path patch.
zdir : {'x', 'y', 'z', 3-tuple}
Plane to plot path patch orthogonal to. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir)
self._code3d = path.codes
def do_3d_projection(self):
s = self._segment3d
xs, ys, zs = zip(*s)
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
self.axes.M)
self._path2d = mpath.Path(np.column_stack([vxs, vys]), self._code3d)
return min(vzs)
The provided code snippet includes necessary dependencies for implementing the `pathpatch_2d_to_3d` function. Write a Python function `def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z')` to solve the following problem:
Convert a `.PathPatch` to a `.PathPatch3D` object.
Here is the function:
def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'):
"""Convert a `.PathPatch` to a `.PathPatch3D` object."""
path = pathpatch.get_path()
trans = pathpatch.get_patch_transform()
mpath = trans.transform_path(path)
pathpatch.__class__ = PathPatch3D
pathpatch.set_3d_properties(mpath, z, zdir) | Convert a `.PathPatch` to a `.PathPatch3D` object. |
172,246 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class Patch3DCollection(PatchCollection):
"""
A collection of 3D patches.
"""
def __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs):
"""
Create a collection of flat 3D patches with its normal vector
pointed in *zdir* direction, and located at *zs* on the *zdir*
axis. 'zs' can be a scalar or an array-like of the same length as
the number of patches in the collection.
Constructor arguments are the same as for
:class:`~matplotlib.collections.PatchCollection`. In addition,
keywords *zs=0* and *zdir='z'* are available.
Also, the keyword argument *depthshade* is available to indicate
whether to shade the patches in order to give the appearance of depth
(default is *True*). This is typically desired in scatter plots.
"""
self._depthshade = depthshade
super().__init__(*args, **kwargs)
self.set_3d_properties(zs, zdir)
def get_depthshade(self):
return self._depthshade
def set_depthshade(self, depthshade):
"""
Set whether depth shading is performed on collection members.
Parameters
----------
depthshade : bool
Whether to shade the patches in order to give the appearance of
depth.
"""
self._depthshade = depthshade
self.stale = True
def set_sort_zpos(self, val):
"""Set the position to use for z-sorting."""
self._sort_zpos = val
self.stale = True
def set_3d_properties(self, zs, zdir):
"""
Set the *z* positions and direction of the patches.
Parameters
----------
zs : float or array of floats
The location or locations to place the patches in the collection
along the *zdir* axis.
zdir : {'x', 'y', 'z'}
Plane to plot patches orthogonal to.
All patches must have the same direction.
See `.get_dir_vector` for a description of the values.
"""
# Force the collection to initialize the face and edgecolors
# just in case it is a scalarmappable with a colormap.
self.update_scalarmappable()
offsets = self.get_offsets()
if len(offsets) > 0:
xs, ys = offsets.T
else:
xs = []
ys = []
self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
self._z_markers_idx = slice(-1)
self._vzs = None
self.stale = True
def do_3d_projection(self):
xs, ys, zs = self._offsets3d
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
self.axes.M)
self._vzs = vzs
super().set_offsets(np.column_stack([vxs, vys]))
if vzs.size > 0:
return min(vzs)
else:
return np.nan
def _maybe_depth_shade_and_sort_colors(self, color_array):
color_array = (
_zalpha(color_array, self._vzs)
if self._vzs is not None and self._depthshade
else color_array
)
if len(color_array) > 1:
color_array = color_array[self._z_markers_idx]
return mcolors.to_rgba_array(color_array, self._alpha)
def get_facecolor(self):
return self._maybe_depth_shade_and_sort_colors(super().get_facecolor())
def get_edgecolor(self):
# We need this check here to make sure we do not double-apply the depth
# based alpha shading when the edge color is "face" which means the
# edge colour should be identical to the face colour.
if cbook._str_equal(self._edgecolors, 'face'):
return self.get_facecolor()
return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor())
class Path3DCollection(PathCollection):
"""
A collection of 3D paths.
"""
def __init__(self, *args, zs=0, zdir='z', depthshade=True, **kwargs):
"""
Create a collection of flat 3D paths with its normal vector
pointed in *zdir* direction, and located at *zs* on the *zdir*
axis. 'zs' can be a scalar or an array-like of the same length as
the number of paths in the collection.
Constructor arguments are the same as for
:class:`~matplotlib.collections.PathCollection`. In addition,
keywords *zs=0* and *zdir='z'* are available.
Also, the keyword argument *depthshade* is available to indicate
whether to shade the patches in order to give the appearance of depth
(default is *True*). This is typically desired in scatter plots.
"""
self._depthshade = depthshade
self._in_draw = False
super().__init__(*args, **kwargs)
self.set_3d_properties(zs, zdir)
self._offset_zordered = None
def draw(self, renderer):
with self._use_zordered_offset():
with cbook._setattr_cm(self, _in_draw=True):
super().draw(renderer)
def set_sort_zpos(self, val):
"""Set the position to use for z-sorting."""
self._sort_zpos = val
self.stale = True
def set_3d_properties(self, zs, zdir):
"""
Set the *z* positions and direction of the paths.
Parameters
----------
zs : float or array of floats
The location or locations to place the paths in the collection
along the *zdir* axis.
zdir : {'x', 'y', 'z'}
Plane to plot paths orthogonal to.
All paths must have the same direction.
See `.get_dir_vector` for a description of the values.
"""
# Force the collection to initialize the face and edgecolors
# just in case it is a scalarmappable with a colormap.
self.update_scalarmappable()
offsets = self.get_offsets()
if len(offsets) > 0:
xs, ys = offsets.T
else:
xs = []
ys = []
self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
# In the base draw methods we access the attributes directly which
# means we can not resolve the shuffling in the getter methods like
# we do for the edge and face colors.
#
# This means we need to carry around a cache of the unsorted sizes and
# widths (postfixed with 3d) and in `do_3d_projection` set the
# depth-sorted version of that data into the private state used by the
# base collection class in its draw method.
#
# Grab the current sizes and linewidths to preserve them.
self._sizes3d = self._sizes
self._linewidths3d = np.array(self._linewidths)
xs, ys, zs = self._offsets3d
# Sort the points based on z coordinates
# Performance optimization: Create a sorted index array and reorder
# points and point properties according to the index array
self._z_markers_idx = slice(-1)
self._vzs = None
self.stale = True
def set_sizes(self, sizes, dpi=72.0):
super().set_sizes(sizes, dpi)
if not self._in_draw:
self._sizes3d = sizes
def set_linewidth(self, lw):
super().set_linewidth(lw)
if not self._in_draw:
self._linewidths3d = np.array(self._linewidths)
def get_depthshade(self):
return self._depthshade
def set_depthshade(self, depthshade):
"""
Set whether depth shading is performed on collection members.
Parameters
----------
depthshade : bool
Whether to shade the patches in order to give the appearance of
depth.
"""
self._depthshade = depthshade
self.stale = True
def do_3d_projection(self):
xs, ys, zs = self._offsets3d
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs,
self.axes.M)
# Sort the points based on z coordinates
# Performance optimization: Create a sorted index array and reorder
# points and point properties according to the index array
z_markers_idx = self._z_markers_idx = np.argsort(vzs)[::-1]
self._vzs = vzs
# we have to special case the sizes because of code in collections.py
# as the draw method does
# self.set_sizes(self._sizes, self.figure.dpi)
# so we can not rely on doing the sorting on the way out via get_*
if len(self._sizes3d) > 1:
self._sizes = self._sizes3d[z_markers_idx]
if len(self._linewidths3d) > 1:
self._linewidths = self._linewidths3d[z_markers_idx]
PathCollection.set_offsets(self, np.column_stack((vxs, vys)))
# Re-order items
vzs = vzs[z_markers_idx]
vxs = vxs[z_markers_idx]
vys = vys[z_markers_idx]
# Store ordered offset for drawing purpose
self._offset_zordered = np.column_stack((vxs, vys))
return np.min(vzs) if vzs.size else np.nan
def _use_zordered_offset(self):
if self._offset_zordered is None:
# Do nothing
yield
else:
# Swap offset with z-ordered offset
old_offset = self._offsets
super().set_offsets(self._offset_zordered)
try:
yield
finally:
self._offsets = old_offset
def _maybe_depth_shade_and_sort_colors(self, color_array):
color_array = (
_zalpha(color_array, self._vzs)
if self._vzs is not None and self._depthshade
else color_array
)
if len(color_array) > 1:
color_array = color_array[self._z_markers_idx]
return mcolors.to_rgba_array(color_array, self._alpha)
def get_facecolor(self):
return self._maybe_depth_shade_and_sort_colors(super().get_facecolor())
def get_edgecolor(self):
# We need this check here to make sure we do not double-apply the depth
# based alpha shading when the edge color is "face" which means the
# edge colour should be identical to the face colour.
if cbook._str_equal(self._edgecolors, 'face'):
return self.get_facecolor()
return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor())
"antialiased": ["antialiaseds", "aa"],
"edgecolor": ["edgecolors", "ec"],
"facecolor": ["facecolors", "fc"],
"linestyle": ["linestyles", "dashes", "ls"],
"linewidth": ["linewidths", "lw"],
"offset_transform": ["transOffset"],
})
class PathCollection(_CollectionWithSizes):
r"""
A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`.
"""
def __init__(self, paths, sizes=None, **kwargs):
"""
Parameters
----------
paths : list of `.path.Path`
The paths that will make up the `.Collection`.
sizes : array-like
The factor by which to scale each drawn `~.path.Path`. One unit
squared in the Path's data space is scaled to be ``sizes**2``
points when rendered.
**kwargs
Forwarded to `.Collection`.
"""
super().__init__(**kwargs)
self.set_paths(paths)
self.set_sizes(sizes)
self.stale = True
def set_paths(self, paths):
self._paths = paths
self.stale = True
def get_paths(self):
return self._paths
def legend_elements(self, prop="colors", num="auto",
fmt=None, func=lambda x: x, **kwargs):
"""
Create legend handles and labels for a PathCollection.
Each legend handle is a `.Line2D` representing the Path that was drawn,
and each label is a string what each Path represents.
This is useful for obtaining a legend for a `~.Axes.scatter` plot;
e.g.::
scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3])
plt.legend(*scatter.legend_elements())
creates three legend elements, one for each color with the numerical
values passed to *c* as the labels.
Also see the :ref:`automatedlegendcreation` example.
Parameters
----------
prop : {"colors", "sizes"}, default: "colors"
If "colors", the legend handles will show the different colors of
the collection. If "sizes", the legend will show the different
sizes. To set both, use *kwargs* to directly edit the `.Line2D`
properties.
num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
Target number of elements to create.
If None, use all unique elements of the mappable array. If an
integer, target to use *num* elements in the normed range.
If *"auto"*, try to determine which option better suits the nature
of the data.
The number of created elements may slightly deviate from *num* due
to a `~.ticker.Locator` being used to find useful locations.
If a list or array, use exactly those elements for the legend.
Finally, a `~.ticker.Locator` can be provided.
fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
The format or formatter to use for the labels. If a string must be
a valid input for a `.StrMethodFormatter`. If None (the default),
use a `.ScalarFormatter`.
func : function, default: ``lambda x: x``
Function to calculate the labels. Often the size (or color)
argument to `~.Axes.scatter` will have been pre-processed by the
user using a function ``s = f(x)`` to make the markers visible;
e.g. ``size = np.log10(x)``. Providing the inverse of this
function here allows that pre-processing to be inverted, so that
the legend labels have the correct values; e.g. ``func = lambda
x: 10**x``.
**kwargs
Allowed keyword arguments are *color* and *size*. E.g. it may be
useful to set the color of the markers if *prop="sizes"* is used;
similarly to set the size of the markers if *prop="colors"* is
used. Any further parameters are passed onto the `.Line2D`
instance. This may be useful to e.g. specify a different
*markeredgecolor* or *alpha* for the legend handles.
Returns
-------
handles : list of `.Line2D`
Visual representation of each element of the legend.
labels : list of str
The string labels for elements of the legend.
"""
handles = []
labels = []
hasarray = self.get_array() is not None
if fmt is None:
fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
elif isinstance(fmt, str):
fmt = mpl.ticker.StrMethodFormatter(fmt)
fmt.create_dummy_axis()
if prop == "colors":
if not hasarray:
warnings.warn("Collection without array used. Make sure to "
"specify the values to be colormapped via the "
"`c` argument.")
return handles, labels
u = np.unique(self.get_array())
size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
elif prop == "sizes":
u = np.unique(self.get_sizes())
color = kwargs.pop("color", "k")
else:
raise ValueError("Valid values for `prop` are 'colors' or "
f"'sizes'. You supplied '{prop}' instead.")
fu = func(u)
fmt.axis.set_view_interval(fu.min(), fu.max())
fmt.axis.set_data_interval(fu.min(), fu.max())
if num == "auto":
num = 9
if len(u) <= num:
num = None
if num is None:
values = u
label_values = func(values)
else:
if prop == "colors":
arr = self.get_array()
elif prop == "sizes":
arr = self.get_sizes()
if isinstance(num, mpl.ticker.Locator):
loc = num
elif np.iterable(num):
loc = mpl.ticker.FixedLocator(num)
else:
num = int(num)
loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
label_values = loc.tick_values(func(arr).min(), func(arr).max())
cond = ((label_values >= func(arr).min()) &
(label_values <= func(arr).max()))
label_values = label_values[cond]
yarr = np.linspace(arr.min(), arr.max(), 256)
xarr = func(yarr)
ix = np.argsort(xarr)
values = np.interp(label_values, xarr[ix], yarr[ix])
kw = {"markeredgewidth": self.get_linewidths()[0],
"alpha": self.get_alpha(),
**kwargs}
for val, lab in zip(values, label_values):
if prop == "colors":
color = self.cmap(self.norm(val))
elif prop == "sizes":
size = np.sqrt(val)
if np.isclose(size, 0.0):
continue
h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
marker=self.get_paths()[0], **kw)
handles.append(h)
if hasattr(fmt, "set_locs"):
fmt.set_locs(label_values)
l = fmt(lab)
labels.append(l)
return handles, labels
class PatchCollection(Collection):
"""
A generic collection of patches.
PatchCollection draws faster than a large number of equivalent individual
Patches. It also makes it easier to assign a colormap to a heterogeneous
collection of patches.
"""
def __init__(self, patches, match_original=False, **kwargs):
"""
Parameters
----------
patches : list of `.Patch`
A sequence of Patch objects. This list may include
a heterogeneous assortment of different patch types.
match_original : bool, default: False
If True, use the colors and linewidths of the original
patches. If False, new colors may be assigned by
providing the standard collection arguments, facecolor,
edgecolor, linewidths, norm or cmap.
**kwargs
All other parameters are forwarded to `.Collection`.
If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
are None, they default to their `.rcParams` patch setting, in
sequence form.
Notes
-----
The use of `~matplotlib.cm.ScalarMappable` functionality is optional.
If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via
a call to `~.ScalarMappable.set_array`), at draw time a call to scalar
mappable will be made to set the face colors.
"""
if match_original:
def determine_facecolor(patch):
if patch.get_fill():
return patch.get_facecolor()
return [0, 0, 0, 0]
kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
kwargs['linewidths'] = [p.get_linewidth() for p in patches]
kwargs['linestyles'] = [p.get_linestyle() for p in patches]
kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
super().__init__(**kwargs)
self.set_paths(patches)
def set_paths(self, patches):
paths = [p.get_transform().transform_path(p.get_path())
for p in patches]
self._paths = paths
The provided code snippet includes necessary dependencies for implementing the `patch_collection_2d_to_3d` function. Write a Python function `def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True)` to solve the following problem:
Convert a `.PatchCollection` into a `.Patch3DCollection` object (or a `.PathCollection` into a `.Path3DCollection` object). Parameters ---------- zs : float or array of floats The location or locations to place the patches in the collection along the *zdir* axis. Default: 0. zdir : {'x', 'y', 'z'} The axis in which to place the patches. Default: "z". See `.get_dir_vector` for a description of the values. depthshade Whether to shade the patches to give a sense of depth. Default: *True*.
Here is the function:
def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True):
"""
Convert a `.PatchCollection` into a `.Patch3DCollection` object
(or a `.PathCollection` into a `.Path3DCollection` object).
Parameters
----------
zs : float or array of floats
The location or locations to place the patches in the collection along
the *zdir* axis. Default: 0.
zdir : {'x', 'y', 'z'}
The axis in which to place the patches. Default: "z".
See `.get_dir_vector` for a description of the values.
depthshade
Whether to shade the patches to give a sense of depth. Default: *True*.
"""
if isinstance(col, PathCollection):
col.__class__ = Path3DCollection
elif isinstance(col, PatchCollection):
col.__class__ = Patch3DCollection
col._depthshade = depthshade
col._in_draw = False
col.set_3d_properties(zs, zdir) | Convert a `.PatchCollection` into a `.Patch3DCollection` object (or a `.PathCollection` into a `.Path3DCollection` object). Parameters ---------- zs : float or array of floats The location or locations to place the patches in the collection along the *zdir* axis. Default: 0. zdir : {'x', 'y', 'z'} The axis in which to place the patches. Default: "z". See `.get_dir_vector` for a description of the values. depthshade Whether to shade the patches to give a sense of depth. Default: *True*. |
172,247 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
def _paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'):
"""
Convert paths from a collection object to 3D segments with path codes.
"""
zs = np.broadcast_to(zs, len(paths))
segments_codes = [_path_to_3d_segment_with_codes(path, pathz, zdir)
for path, pathz in zip(paths, zs)]
if segments_codes:
segments, codes = zip(*segments_codes)
else:
segments, codes = [], []
return list(segments), list(codes)
class Poly3DCollection(PolyCollection):
"""
A collection of 3D polygons.
.. note::
**Filling of 3D polygons**
There is no simple definition of the enclosed surface of a 3D polygon
unless the polygon is planar.
In practice, Matplotlib fills the 2D projection of the polygon. This
gives a correct filling appearance only for planar polygons. For all
other polygons, you'll find orientations in which the edges of the
polygon intersect in the projection. This will lead to an incorrect
visualization of the 3D area.
If you need filled areas, it is recommended to create them via
`~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_trisurf`, which creates a
triangulation and thus generates consistent surfaces.
"""
def __init__(self, verts, *args, zsort='average', shade=False,
lightsource=None, **kwargs):
"""
Parameters
----------
verts : list of (N, 3) array-like
The sequence of polygons [*verts0*, *verts1*, ...] where each
element *verts_i* defines the vertices of polygon *i* as a 2D
array-like of shape (N, 3).
zsort : {'average', 'min', 'max'}, default: 'average'
The calculation method for the z-order.
See `~.Poly3DCollection.set_zsort` for details.
shade : bool, default: False
Whether to shade *facecolors* and *edgecolors*. When activating
*shade*, *facecolors* and/or *edgecolors* must be provided.
.. versionadded:: 3.7
lightsource : `~matplotlib.colors.LightSource`
The lightsource to use when *shade* is True.
.. versionadded:: 3.7
*args, **kwargs
All other parameters are forwarded to `.PolyCollection`.
Notes
-----
Note that this class does a bit of magic with the _facecolors
and _edgecolors properties.
"""
if shade:
normals = _generate_normals(verts)
facecolors = kwargs.get('facecolors', None)
if facecolors is not None:
kwargs['facecolors'] = _shade_colors(
facecolors, normals, lightsource
)
edgecolors = kwargs.get('edgecolors', None)
if edgecolors is not None:
kwargs['edgecolors'] = _shade_colors(
edgecolors, normals, lightsource
)
if facecolors is None and edgecolors in None:
raise ValueError(
"You must provide facecolors, edgecolors, or both for "
"shade to work.")
super().__init__(verts, *args, **kwargs)
if isinstance(verts, np.ndarray):
if verts.ndim != 3:
raise ValueError('verts must be a list of (N, 3) array-like')
else:
if any(len(np.shape(vert)) != 2 for vert in verts):
raise ValueError('verts must be a list of (N, 3) array-like')
self.set_zsort(zsort)
self._codes3d = None
_zsort_functions = {
'average': np.average,
'min': np.min,
'max': np.max,
}
def set_zsort(self, zsort):
"""
Set the calculation method for the z-order.
Parameters
----------
zsort : {'average', 'min', 'max'}
The function applied on the z-coordinates of the vertices in the
viewer's coordinate system, to determine the z-order.
"""
self._zsortfunc = self._zsort_functions[zsort]
self._sort_zpos = None
self.stale = True
def get_vector(self, segments3d):
"""Optimize points for projection."""
if len(segments3d):
xs, ys, zs = np.row_stack(segments3d).T
else: # row_stack can't stack zero arrays.
xs, ys, zs = [], [], []
ones = np.ones(len(xs))
self._vec = np.array([xs, ys, zs, ones])
indices = [0, *np.cumsum([len(segment) for segment in segments3d])]
self._segslices = [*map(slice, indices[:-1], indices[1:])]
def set_verts(self, verts, closed=True):
"""
Set 3D vertices.
Parameters
----------
verts : list of (N, 3) array-like
The sequence of polygons [*verts0*, *verts1*, ...] where each
element *verts_i* defines the vertices of polygon *i* as a 2D
array-like of shape (N, 3).
closed : bool, default: True
Whether the polygon should be closed by adding a CLOSEPOLY
connection at the end.
"""
self.get_vector(verts)
# 2D verts will be updated at draw time
super().set_verts([], False)
self._closed = closed
def set_verts_and_codes(self, verts, codes):
"""Set 3D vertices with path codes."""
# set vertices with closed=False to prevent PolyCollection from
# setting path codes
self.set_verts(verts, closed=False)
# and set our own codes instead.
self._codes3d = codes
def set_3d_properties(self):
# Force the collection to initialize the face and edgecolors
# just in case it is a scalarmappable with a colormap.
self.update_scalarmappable()
self._sort_zpos = None
self.set_zsort('average')
self._facecolor3d = PolyCollection.get_facecolor(self)
self._edgecolor3d = PolyCollection.get_edgecolor(self)
self._alpha3d = PolyCollection.get_alpha(self)
self.stale = True
def set_sort_zpos(self, val):
"""Set the position to use for z-sorting."""
self._sort_zpos = val
self.stale = True
def do_3d_projection(self):
"""
Perform the 3D projection for this object.
"""
if self._A is not None:
# force update of color mapping because we re-order them
# below. If we do not do this here, the 2D draw will call
# this, but we will never port the color mapped values back
# to the 3D versions.
#
# We hold the 3D versions in a fixed order (the order the user
# passed in) and sort the 2D version by view depth.
self.update_scalarmappable()
if self._face_is_mapped:
self._facecolor3d = self._facecolors
if self._edge_is_mapped:
self._edgecolor3d = self._edgecolors
txs, tys, tzs = proj3d._proj_transform_vec(self._vec, self.axes.M)
xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices]
# This extra fuss is to re-order face / edge colors
cface = self._facecolor3d
cedge = self._edgecolor3d
if len(cface) != len(xyzlist):
cface = cface.repeat(len(xyzlist), axis=0)
if len(cedge) != len(xyzlist):
if len(cedge) == 0:
cedge = cface
else:
cedge = cedge.repeat(len(xyzlist), axis=0)
if xyzlist:
# sort by depth (furthest drawn first)
z_segments_2d = sorted(
((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx)
for idx, ((xs, ys, zs), fc, ec)
in enumerate(zip(xyzlist, cface, cedge))),
key=lambda x: x[0], reverse=True)
_, segments_2d, self._facecolors2d, self._edgecolors2d, idxs = \
zip(*z_segments_2d)
else:
segments_2d = []
self._facecolors2d = np.empty((0, 4))
self._edgecolors2d = np.empty((0, 4))
idxs = []
if self._codes3d is not None:
codes = [self._codes3d[idx] for idx in idxs]
PolyCollection.set_verts_and_codes(self, segments_2d, codes)
else:
PolyCollection.set_verts(self, segments_2d, self._closed)
if len(self._edgecolor3d) != len(cface):
self._edgecolors2d = self._edgecolor3d
# Return zorder value
if self._sort_zpos is not None:
zvec = np.array([[0], [0], [self._sort_zpos], [1]])
ztrans = proj3d._proj_transform_vec(zvec, self.axes.M)
return ztrans[2][0]
elif tzs.size > 0:
# FIXME: Some results still don't look quite right.
# In particular, examine contourf3d_demo2.py
# with az = -54 and elev = -45.
return np.min(tzs)
else:
return np.nan
def set_facecolor(self, colors):
# docstring inherited
super().set_facecolor(colors)
self._facecolor3d = PolyCollection.get_facecolor(self)
def set_edgecolor(self, colors):
# docstring inherited
super().set_edgecolor(colors)
self._edgecolor3d = PolyCollection.get_edgecolor(self)
def set_alpha(self, alpha):
# docstring inherited
artist.Artist.set_alpha(self, alpha)
try:
self._facecolor3d = mcolors.to_rgba_array(
self._facecolor3d, self._alpha)
except (AttributeError, TypeError, IndexError):
pass
try:
self._edgecolors = mcolors.to_rgba_array(
self._edgecolor3d, self._alpha)
except (AttributeError, TypeError, IndexError):
pass
self.stale = True
def get_facecolor(self):
# docstring inherited
# self._facecolors2d is not initialized until do_3d_projection
if not hasattr(self, '_facecolors2d'):
self.axes.M = self.axes.get_proj()
self.do_3d_projection()
return self._facecolors2d
def get_edgecolor(self):
# docstring inherited
# self._edgecolors2d is not initialized until do_3d_projection
if not hasattr(self, '_edgecolors2d'):
self.axes.M = self.axes.get_proj()
self.do_3d_projection()
return self._edgecolors2d
else:
colors = np.asanyarray(color).copy()
return colors
The provided code snippet includes necessary dependencies for implementing the `poly_collection_2d_to_3d` function. Write a Python function `def poly_collection_2d_to_3d(col, zs=0, zdir='z')` to solve the following problem:
Convert a `.PolyCollection` into a `.Poly3DCollection` object. Parameters ---------- zs : float or array of floats The location or locations to place the polygons in the collection along the *zdir* axis. Default: 0. zdir : {'x', 'y', 'z'} The axis in which to place the patches. Default: 'z'. See `.get_dir_vector` for a description of the values.
Here is the function:
def poly_collection_2d_to_3d(col, zs=0, zdir='z'):
"""
Convert a `.PolyCollection` into a `.Poly3DCollection` object.
Parameters
----------
zs : float or array of floats
The location or locations to place the polygons in the collection along
the *zdir* axis. Default: 0.
zdir : {'x', 'y', 'z'}
The axis in which to place the patches. Default: 'z'.
See `.get_dir_vector` for a description of the values.
"""
segments_3d, codes = _paths_to_3d_segments_with_codes(
col.get_paths(), zs, zdir)
col.__class__ = Poly3DCollection
col.set_verts_and_codes(segments_3d, codes)
col.set_3d_properties() | Convert a `.PolyCollection` into a `.Poly3DCollection` object. Parameters ---------- zs : float or array of floats The location or locations to place the polygons in the collection along the *zdir* axis. Default: 0. zdir : {'x', 'y', 'z'} The axis in which to place the patches. Default: 'z'. See `.get_dir_vector` for a description of the values. |
172,248 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class Normalize:
"""
A class which, when called, linearly normalizes data into the
``[0.0, 1.0]`` interval.
"""
def __init__(self, vmin=None, vmax=None, clip=False):
"""
Parameters
----------
vmin, vmax : float or None
If *vmin* and/or *vmax* is not given, they are initialized from the
minimum and maximum value, respectively, of the first input
processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
clip : bool, default: False
If ``True`` values falling outside the range ``[vmin, vmax]``,
are mapped to 0 or 1, whichever is closer, and masked values are
set to 1. If ``False`` masked values remain masked.
Clipping silently defeats the purpose of setting the over, under,
and masked colors in a colormap, so it is likely to lead to
surprises; therefore the default is ``clip=False``.
Notes
-----
Returns 0 if ``vmin == vmax``.
"""
self._vmin = _sanitize_extrema(vmin)
self._vmax = _sanitize_extrema(vmax)
self._clip = clip
self._scale = None
self.callbacks = cbook.CallbackRegistry(signals=["changed"])
def vmin(self):
return self._vmin
def vmin(self, value):
value = _sanitize_extrema(value)
if value != self._vmin:
self._vmin = value
self._changed()
def vmax(self):
return self._vmax
def vmax(self, value):
value = _sanitize_extrema(value)
if value != self._vmax:
self._vmax = value
self._changed()
def clip(self):
return self._clip
def clip(self, value):
if value != self._clip:
self._clip = value
self._changed()
def _changed(self):
"""
Call this whenever the norm is changed to notify all the
callback listeners to the 'changed' signal.
"""
self.callbacks.process('changed')
def process_value(value):
"""
Homogenize the input *value* for easy and efficient normalization.
*value* can be a scalar or sequence.
Returns
-------
result : masked array
Masked array with the same shape as *value*.
is_scalar : bool
Whether *value* is a scalar.
Notes
-----
Float dtypes are preserved; integer types with two bytes or smaller are
converted to np.float32, and larger types are converted to np.float64.
Preserving float32 when possible, and using in-place operations,
greatly improves speed for large arrays.
"""
is_scalar = not np.iterable(value)
if is_scalar:
value = [value]
dtype = np.min_scalar_type(value)
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
# bool_/int8/int16 -> float32; int32/int64 -> float64
dtype = np.promote_types(dtype, np.float32)
# ensure data passed in as an ndarray subclass are interpreted as
# an ndarray. See issue #6622.
mask = np.ma.getmask(value)
data = np.asarray(value)
result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
return result, is_scalar
def __call__(self, value, clip=None):
"""
Normalize *value* data in the ``[vmin, vmax]`` interval into the
``[0.0, 1.0]`` interval and return it.
Parameters
----------
value
Data to normalize.
clip : bool, optional
If ``None``, defaults to ``self.clip`` (which defaults to
``False``).
Notes
-----
If not already initialized, ``self.vmin`` and ``self.vmax`` are
initialized using ``self.autoscale_None(value)``.
"""
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
if self.vmin is None or self.vmax is None:
self.autoscale_None(result)
# Convert at least to float, without losing precision.
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if vmin == vmax:
result.fill(0) # Or should it be all masked? Or 0.5?
elif vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
# ma division is very slow; we can take a shortcut
resdat = result.data
resdat -= vmin
resdat /= (vmax - vmin)
result = np.ma.array(resdat, mask=result.mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until both vmin and vmax are set")
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if np.iterable(value):
val = np.ma.asarray(value)
return vmin + val * (vmax - vmin)
else:
return vmin + value * (vmax - vmin)
def autoscale(self, A):
"""Set *vmin*, *vmax* to min, max of *A*."""
with self.callbacks.blocked():
# Pause callbacks while we are updating so we only get
# a single update signal at the end
self.vmin = self.vmax = None
self.autoscale_None(A)
self._changed()
def autoscale_None(self, A):
"""If vmin or vmax are not set, use the min/max of *A* to set them."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
"""Return whether vmin and vmax are set."""
return self.vmin is not None and self.vmax is not None
The provided code snippet includes necessary dependencies for implementing the `_zalpha` function. Write a Python function `def _zalpha(colors, zs)` to solve the following problem:
Modify the alphas of the color list according to depth.
Here is the function:
def _zalpha(colors, zs):
"""Modify the alphas of the color list according to depth."""
# FIXME: This only works well if the points for *zs* are well-spaced
# in all three dimensions. Otherwise, at certain orientations,
# the min and max zs are very close together.
# Should really normalize against the viewing depth.
if len(colors) == 0 or len(zs) == 0:
return np.zeros((0, 4))
norm = Normalize(min(zs), max(zs))
sats = 1 - norm(zs) * 0.7
rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4))
return np.column_stack([rgba[:, :3], rgba[:, 3] * sats]) | Modify the alphas of the color list according to depth. |
172,249 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
The provided code snippet includes necessary dependencies for implementing the `_generate_normals` function. Write a Python function `def _generate_normals(polygons)` to solve the following problem:
Compute the normals of a list of polygons, one normal per polygon. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This method assumes that the points are in a plane. Otherwise, more than one shade is required, which is not supported. Parameters ---------- polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like A sequence of polygons to compute normals for, which can have varying numbers of vertices. If the polygons all have the same number of vertices and array is passed, then the operation will be vectorized. Returns ------- normals : (..., 3) array A normal vector estimated for the polygon.
Here is the function:
def _generate_normals(polygons):
"""
Compute the normals of a list of polygons, one normal per polygon.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon. This method assumes
that the points are in a plane. Otherwise, more than one shade is required,
which is not supported.
Parameters
----------
polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like
A sequence of polygons to compute normals for, which can have
varying numbers of vertices. If the polygons all have the same
number of vertices and array is passed, then the operation will
be vectorized.
Returns
-------
normals : (..., 3) array
A normal vector estimated for the polygon.
"""
if isinstance(polygons, np.ndarray):
# optimization: polygons all have the same number of points, so can
# vectorize
n = polygons.shape[-2]
i1, i2, i3 = 0, n//3, 2*n//3
v1 = polygons[..., i1, :] - polygons[..., i2, :]
v2 = polygons[..., i2, :] - polygons[..., i3, :]
else:
# The subtraction doesn't vectorize because polygons is jagged.
v1 = np.empty((len(polygons), 3))
v2 = np.empty((len(polygons), 3))
for poly_i, ps in enumerate(polygons):
n = len(ps)
i1, i2, i3 = 0, n//3, 2*n//3
v1[poly_i, :] = ps[i1, :] - ps[i2, :]
v2[poly_i, :] = ps[i2, :] - ps[i3, :]
return np.cross(v1, v2) | Compute the normals of a list of polygons, one normal per polygon. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This method assumes that the points are in a plane. Otherwise, more than one shade is required, which is not supported. Parameters ---------- polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like A sequence of polygons to compute normals for, which can have varying numbers of vertices. If the polygons all have the same number of vertices and array is passed, then the operation will be vectorized. Returns ------- normals : (..., 3) array A normal vector estimated for the polygon. |
172,250 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
class Normalize:
"""
A class which, when called, linearly normalizes data into the
``[0.0, 1.0]`` interval.
"""
def __init__(self, vmin=None, vmax=None, clip=False):
"""
Parameters
----------
vmin, vmax : float or None
If *vmin* and/or *vmax* is not given, they are initialized from the
minimum and maximum value, respectively, of the first input
processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.
clip : bool, default: False
If ``True`` values falling outside the range ``[vmin, vmax]``,
are mapped to 0 or 1, whichever is closer, and masked values are
set to 1. If ``False`` masked values remain masked.
Clipping silently defeats the purpose of setting the over, under,
and masked colors in a colormap, so it is likely to lead to
surprises; therefore the default is ``clip=False``.
Notes
-----
Returns 0 if ``vmin == vmax``.
"""
self._vmin = _sanitize_extrema(vmin)
self._vmax = _sanitize_extrema(vmax)
self._clip = clip
self._scale = None
self.callbacks = cbook.CallbackRegistry(signals=["changed"])
def vmin(self):
return self._vmin
def vmin(self, value):
value = _sanitize_extrema(value)
if value != self._vmin:
self._vmin = value
self._changed()
def vmax(self):
return self._vmax
def vmax(self, value):
value = _sanitize_extrema(value)
if value != self._vmax:
self._vmax = value
self._changed()
def clip(self):
return self._clip
def clip(self, value):
if value != self._clip:
self._clip = value
self._changed()
def _changed(self):
"""
Call this whenever the norm is changed to notify all the
callback listeners to the 'changed' signal.
"""
self.callbacks.process('changed')
def process_value(value):
"""
Homogenize the input *value* for easy and efficient normalization.
*value* can be a scalar or sequence.
Returns
-------
result : masked array
Masked array with the same shape as *value*.
is_scalar : bool
Whether *value* is a scalar.
Notes
-----
Float dtypes are preserved; integer types with two bytes or smaller are
converted to np.float32, and larger types are converted to np.float64.
Preserving float32 when possible, and using in-place operations,
greatly improves speed for large arrays.
"""
is_scalar = not np.iterable(value)
if is_scalar:
value = [value]
dtype = np.min_scalar_type(value)
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
# bool_/int8/int16 -> float32; int32/int64 -> float64
dtype = np.promote_types(dtype, np.float32)
# ensure data passed in as an ndarray subclass are interpreted as
# an ndarray. See issue #6622.
mask = np.ma.getmask(value)
data = np.asarray(value)
result = np.ma.array(data, mask=mask, dtype=dtype, copy=True)
return result, is_scalar
def __call__(self, value, clip=None):
"""
Normalize *value* data in the ``[vmin, vmax]`` interval into the
``[0.0, 1.0]`` interval and return it.
Parameters
----------
value
Data to normalize.
clip : bool, optional
If ``None``, defaults to ``self.clip`` (which defaults to
``False``).
Notes
-----
If not already initialized, ``self.vmin`` and ``self.vmax`` are
initialized using ``self.autoscale_None(value)``.
"""
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
if self.vmin is None or self.vmax is None:
self.autoscale_None(result)
# Convert at least to float, without losing precision.
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if vmin == vmax:
result.fill(0) # Or should it be all masked? Or 0.5?
elif vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(np.clip(result.filled(vmax), vmin, vmax),
mask=mask)
# ma division is very slow; we can take a shortcut
resdat = result.data
resdat -= vmin
resdat /= (vmax - vmin)
result = np.ma.array(resdat, mask=result.mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until both vmin and vmax are set")
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if np.iterable(value):
val = np.ma.asarray(value)
return vmin + val * (vmax - vmin)
else:
return vmin + value * (vmax - vmin)
def autoscale(self, A):
"""Set *vmin*, *vmax* to min, max of *A*."""
with self.callbacks.blocked():
# Pause callbacks while we are updating so we only get
# a single update signal at the end
self.vmin = self.vmax = None
self.autoscale_None(A)
self._changed()
def autoscale_None(self, A):
"""If vmin or vmax are not set, use the min/max of *A* to set them."""
A = np.asanyarray(A)
if self.vmin is None and A.size:
self.vmin = A.min()
if self.vmax is None and A.size:
self.vmax = A.max()
def scaled(self):
"""Return whether vmin and vmax are set."""
return self.vmin is not None and self.vmax is not None
The provided code snippet includes necessary dependencies for implementing the `_shade_colors` function. Write a Python function `def _shade_colors(color, normals, lightsource=None)` to solve the following problem:
Shade *color* using normal vectors given by *normals*, assuming a *lightsource* (using default position if not given). *color* can also be an array of the same length as *normals*.
Here is the function:
def _shade_colors(color, normals, lightsource=None):
"""
Shade *color* using normal vectors given by *normals*,
assuming a *lightsource* (using default position if not given).
*color* can also be an array of the same length as *normals*.
"""
if lightsource is None:
# chosen for backwards-compatibility
lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712)
with np.errstate(invalid="ignore"):
shade = ((normals / np.linalg.norm(normals, axis=1, keepdims=True))
@ lightsource.direction)
mask = ~np.isnan(shade)
if mask.any():
# convert dot product to allowed shading fractions
in_norm = mcolors.Normalize(-1, 1)
out_norm = mcolors.Normalize(0.3, 1).inverse
def norm(x):
return out_norm(in_norm(x))
shade[~mask] = 0
color = mcolors.to_rgba_array(color)
# shape of color should be (M, 4) (where M is number of faces)
# shape of shade should be (M,)
# colors should have final shape of (M, 4)
alpha = color[:, 3]
colors = norm(shade)[:, np.newaxis] * color
colors[:, 3] = alpha
else:
colors = np.asanyarray(color).copy()
return colors | Shade *color* using normal vectors given by *normals*, assuming a *lightsource* (using default position if not given). *color* can also be an array of the same length as *normals*. |
172,251 | import numpy as np
import numpy.linalg as linalg
The provided code snippet includes necessary dependencies for implementing the `_line2d_seg_dist` function. Write a Python function `def _line2d_seg_dist(p, s0, s1)` to solve the following problem:
Return the distance(s) from point(s) *p* to segment(s) (*s0*, *s1*). Parameters ---------- p : (ndim,) or (N, ndim) array-like The points from which the distances are computed. s0, s1 : (ndim,) or (N, ndim) array-like The xy(z...) coordinates of the segment endpoints.
Here is the function:
def _line2d_seg_dist(p, s0, s1):
"""
Return the distance(s) from point(s) *p* to segment(s) (*s0*, *s1*).
Parameters
----------
p : (ndim,) or (N, ndim) array-like
The points from which the distances are computed.
s0, s1 : (ndim,) or (N, ndim) array-like
The xy(z...) coordinates of the segment endpoints.
"""
s0 = np.asarray(s0)
s01 = s1 - s0 # shape (ndim,) or (N, ndim)
s0p = p - s0 # shape (ndim,) or (N, ndim)
l2 = s01 @ s01 # squared segment length
# Avoid div. by zero for degenerate segments (for them, s01 = (0, 0, ...)
# so the value of l2 doesn't matter; this just replaces 0/0 by 0/1).
l2 = np.where(l2, l2, 1)
# Project onto segment, without going past segment ends.
p1 = s0 + np.multiply.outer(np.clip(s0p @ s01 / l2, 0, 1), s01)
return ((p - p1) ** 2).sum(axis=-1) ** (1/2) | Return the distance(s) from point(s) *p* to segment(s) (*s0*, *s1*). Parameters ---------- p : (ndim,) or (N, ndim) array-like The points from which the distances are computed. s0, s1 : (ndim,) or (N, ndim) array-like The xy(z...) coordinates of the segment endpoints. |
172,252 | import numpy as np
import numpy.linalg as linalg
The provided code snippet includes necessary dependencies for implementing the `world_transformation` function. Write a Python function `def world_transformation(xmin, xmax, ymin, ymax, zmin, zmax, pb_aspect=None)` to solve the following problem:
Produce a matrix that scales homogeneous coords in the specified ranges to [0, 1], or [0, pb_aspect[i]] if the plotbox aspect ratio is specified.
Here is the function:
def world_transformation(xmin, xmax,
ymin, ymax,
zmin, zmax, pb_aspect=None):
"""
Produce a matrix that scales homogeneous coords in the specified ranges
to [0, 1], or [0, pb_aspect[i]] if the plotbox aspect ratio is specified.
"""
dx = xmax - xmin
dy = ymax - ymin
dz = zmax - zmin
if pb_aspect is not None:
ax, ay, az = pb_aspect
dx /= ax
dy /= ay
dz /= az
return np.array([[1/dx, 0, 0, -xmin/dx],
[0, 1/dy, 0, -ymin/dy],
[0, 0, 1/dz, -zmin/dz],
[0, 0, 0, 1]]) | Produce a matrix that scales homogeneous coords in the specified ranges to [0, 1], or [0, pb_aspect[i]] if the plotbox aspect ratio is specified. |
172,253 | import numpy as np
import numpy.linalg as linalg
def _view_axes(E, R, V, roll):
"""
Get the unit viewing axes in data coordinates.
Parameters
----------
E : 3-element numpy array
The coordinates of the eye/camera.
R : 3-element numpy array
The coordinates of the center of the view box.
V : 3-element numpy array
Unit vector in the direction of the vertical axis.
roll : float
The roll angle in radians.
Returns
-------
u : 3-element numpy array
Unit vector pointing towards the right of the screen.
v : 3-element numpy array
Unit vector pointing towards the top of the screen.
w : 3-element numpy array
Unit vector pointing out of the screen.
"""
w = (E - R)
w = w/np.linalg.norm(w)
u = np.cross(V, w)
u = u/np.linalg.norm(u)
v = np.cross(w, u) # Will be a unit vector
# Save some computation for the default roll=0
if roll != 0:
# A positive rotation of the camera is a negative rotation of the world
Rroll = rotation_about_vector(w, -roll)
u = np.dot(Rroll, u)
v = np.dot(Rroll, v)
return u, v, w
def _view_transformation_uvw(u, v, w, E):
"""
Return the view transformation matrix.
Parameters
----------
u : 3-element numpy array
Unit vector pointing towards the right of the screen.
v : 3-element numpy array
Unit vector pointing towards the top of the screen.
w : 3-element numpy array
Unit vector pointing out of the screen.
E : 3-element numpy array
The coordinates of the eye/camera.
"""
Mr = np.eye(4)
Mt = np.eye(4)
Mr[:3, :3] = [u, v, w]
Mt[:3, -1] = -E
M = np.dot(Mr, Mt)
return M
The provided code snippet includes necessary dependencies for implementing the `view_transformation` function. Write a Python function `def view_transformation(E, R, V, roll)` to solve the following problem:
Return the view transformation matrix. Parameters ---------- E : 3-element numpy array The coordinates of the eye/camera. R : 3-element numpy array The coordinates of the center of the view box. V : 3-element numpy array Unit vector in the direction of the vertical axis. roll : float The roll angle in radians.
Here is the function:
def view_transformation(E, R, V, roll):
"""
Return the view transformation matrix.
Parameters
----------
E : 3-element numpy array
The coordinates of the eye/camera.
R : 3-element numpy array
The coordinates of the center of the view box.
V : 3-element numpy array
Unit vector in the direction of the vertical axis.
roll : float
The roll angle in radians.
"""
u, v, w = _view_axes(E, R, V, roll)
M = _view_transformation_uvw(u, v, w, E)
return M | Return the view transformation matrix. Parameters ---------- E : 3-element numpy array The coordinates of the eye/camera. R : 3-element numpy array The coordinates of the center of the view box. V : 3-element numpy array Unit vector in the direction of the vertical axis. roll : float The roll angle in radians. |
172,254 | import numpy as np
import numpy.linalg as linalg
def persp_transformation(zfront, zback, focal_length):
e = focal_length
a = 1 # aspect ratio
b = (zfront+zback)/(zfront-zback)
c = -2*(zfront*zback)/(zfront-zback)
proj_matrix = np.array([[e, 0, 0, 0],
[0, e/a, 0, 0],
[0, 0, b, c],
[0, 0, -1, 0]])
return proj_matrix | null |
172,255 | import numpy as np
import numpy.linalg as linalg
def ortho_transformation(zfront, zback):
# note: w component in the resulting vector will be (zback-zfront), not 1
a = -(zfront + zback)
b = -(zfront - zback)
proj_matrix = np.array([[2, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, -2, 0],
[0, 0, a, b]])
return proj_matrix | null |
172,256 | import numpy as np
import numpy.linalg as linalg
def _vec_pad_ones(xs, ys, zs):
return np.array([xs, ys, zs, np.ones_like(xs)])
The provided code snippet includes necessary dependencies for implementing the `inv_transform` function. Write a Python function `def inv_transform(xs, ys, zs, M)` to solve the following problem:
Transform the points by the inverse of the projection matrix *M*.
Here is the function:
def inv_transform(xs, ys, zs, M):
"""
Transform the points by the inverse of the projection matrix *M*.
"""
iM = linalg.inv(M)
vec = _vec_pad_ones(xs, ys, zs)
vecr = np.dot(iM, vec)
try:
vecr = vecr / vecr[3]
except OverflowError:
pass
return vecr[0], vecr[1], vecr[2] | Transform the points by the inverse of the projection matrix *M*. |
172,257 | import numpy as np
import numpy.linalg as linalg
def _proj_transform_vec_clip(vec, M):
vecw = np.dot(M, vec)
w = vecw[3]
# clip here.
txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w
tis = (0 <= vecw[0]) & (vecw[0] <= 1) & (0 <= vecw[1]) & (vecw[1] <= 1)
if np.any(tis):
tis = vecw[1] < 1
return txs, tys, tzs, tis
def _vec_pad_ones(xs, ys, zs):
return np.array([xs, ys, zs, np.ones_like(xs)])
The provided code snippet includes necessary dependencies for implementing the `proj_transform_clip` function. Write a Python function `def proj_transform_clip(xs, ys, zs, M)` to solve the following problem:
Transform the points by the projection matrix and return the clipping result returns txs, tys, tzs, tis
Here is the function:
def proj_transform_clip(xs, ys, zs, M):
"""
Transform the points by the projection matrix
and return the clipping result
returns txs, tys, tzs, tis
"""
vec = _vec_pad_ones(xs, ys, zs)
return _proj_transform_vec_clip(vec, M) | Transform the points by the projection matrix and return the clipping result returns txs, tys, tzs, tis |
172,258 | import numpy as np
import numpy.linalg as linalg
def proj_trans_points(points, M):
xs, ys, zs = zip(*points)
return proj_transform(xs, ys, zs, M)
def proj_points(points, M):
return np.column_stack(proj_trans_points(points, M)) | null |
172,259 | import numpy as np
import numpy.linalg as linalg
def rot_x(V, alpha):
cosa, sina = np.cos(alpha), np.sin(alpha)
M1 = np.array([[1, 0, 0, 0],
[0, cosa, -sina, 0],
[0, sina, cosa, 0],
[0, 0, 0, 1]])
return np.dot(M1, V) | null |
172,260 | import inspect
import numpy as np
import matplotlib as mpl
from matplotlib import (
_api, artist, lines as mlines, axis as maxis, patches as mpatches,
transforms as mtransforms, colors as mcolors)
from . import art3d, proj3d
def _move_from_center(coord, centers, deltas, axmask=(True, True, True)):
"""
For each coordinate where *axmask* is True, move *coord* away from
*centers* by *deltas*.
"""
coord = np.asarray(coord)
return coord + axmask * np.copysign(1, coord - centers) * deltas
The provided code snippet includes necessary dependencies for implementing the `move_from_center` function. Write a Python function `def move_from_center(coord, centers, deltas, axmask=(True, True, True))` to solve the following problem:
For each coordinate where *axmask* is True, move *coord* away from *centers* by *deltas*.
Here is the function:
def move_from_center(coord, centers, deltas, axmask=(True, True, True)):
"""
For each coordinate where *axmask* is True, move *coord* away from
*centers* by *deltas*.
"""
return _move_from_center(coord, centers, deltas, axmask=axmask) | For each coordinate where *axmask* is True, move *coord* away from *centers* by *deltas*. |
172,261 | import inspect
import numpy as np
import matplotlib as mpl
from matplotlib import (
_api, artist, lines as mlines, axis as maxis, patches as mpatches,
transforms as mtransforms, colors as mcolors)
from . import art3d, proj3d
def _tick_update_position(tick, tickxs, tickys, labelpos):
"""Update tick line and label position and style."""
tick.label1.set_position(labelpos)
tick.label2.set_position(labelpos)
tick.tick1line.set_visible(True)
tick.tick2line.set_visible(False)
tick.tick1line.set_linestyle('-')
tick.tick1line.set_marker('')
tick.tick1line.set_data(tickxs, tickys)
tick.gridline.set_data([0], [0])
The provided code snippet includes necessary dependencies for implementing the `tick_update_position` function. Write a Python function `def tick_update_position(tick, tickxs, tickys, labelpos)` to solve the following problem:
Update tick line and label position and style.
Here is the function:
def tick_update_position(tick, tickxs, tickys, labelpos):
"""Update tick line and label position and style."""
_tick_update_position(tick, tickxs, tickys, labelpos) | Update tick line and label position and style. |
172,262 | import os
import re
import time
from os.path import basename
from multiprocessing import util
import distutils
The provided code snippet includes necessary dependencies for implementing the `concurrency_safe_rename` function. Write a Python function `def concurrency_safe_rename(src, dst)` to solve the following problem:
Renames ``src`` into ``dst`` overwriting ``dst`` if it exists. On Windows os.replace can yield permission errors if executed by two different processes.
Here is the function:
def concurrency_safe_rename(src, dst):
"""Renames ``src`` into ``dst`` overwriting ``dst`` if it exists.
On Windows os.replace can yield permission errors if executed by two
different processes.
"""
max_sleep_time = 1
total_sleep_time = 0
sleep_time = 0.001
while total_sleep_time < max_sleep_time:
try:
replace(src, dst)
break
except Exception as exc:
if getattr(exc, 'winerror', None) in access_denied_errors:
time.sleep(sleep_time)
total_sleep_time += sleep_time
sleep_time *= 2
else:
raise
else:
raise | Renames ``src`` into ``dst`` overwriting ``dst`` if it exists. On Windows os.replace can yield permission errors if executed by two different processes. |
172,263 | import pickle
import os
import warnings
import io
from pathlib import Path
from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR
from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile
from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,
BZ2CompressorWrapper, LZMACompressorWrapper,
XZCompressorWrapper, LZ4CompressorWrapper)
from .numpy_pickle_utils import Unpickler, Pickler
from .numpy_pickle_utils import _read_fileobject, _write_fileobject
from .numpy_pickle_utils import _read_bytes, BUFFER_SIZE
from .numpy_pickle_utils import _ensure_native_byte_order
from .numpy_pickle_compat import load_compatibility
from .numpy_pickle_compat import NDArrayWrapper
from .numpy_pickle_compat import ZNDArrayWrapper
from .backports import make_memmap
class NumpyPickler(Pickler):
"""A pickler to persist big data efficiently.
The main features of this object are:
* persistence of numpy arrays in a single file.
* optional compression with a special care on avoiding memory copies.
Attributes
----------
fp: file
File object handle used for serializing the input object.
protocol: int, optional
Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL.
"""
dispatch = Pickler.dispatch.copy()
def __init__(self, fp, protocol=None):
self.file_handle = fp
self.buffered = isinstance(self.file_handle, BinaryZlibFile)
# By default we want a pickle protocol that only changes with
# the major python version and not the minor one
if protocol is None:
protocol = pickle.DEFAULT_PROTOCOL
Pickler.__init__(self, self.file_handle, protocol=protocol)
# delayed import of numpy, to avoid tight coupling
try:
import numpy as np
except ImportError:
np = None
self.np = np
def _create_array_wrapper(self, array):
"""Create and returns a numpy array wrapper from a numpy array."""
order = 'F' if (array.flags.f_contiguous and
not array.flags.c_contiguous) else 'C'
allow_mmap = not self.buffered and not array.dtype.hasobject
kwargs = {}
try:
self.file_handle.tell()
except io.UnsupportedOperation:
kwargs = {'numpy_array_alignment_bytes': None}
wrapper = NumpyArrayWrapper(type(array),
array.shape, order, array.dtype,
allow_mmap=allow_mmap,
**kwargs)
return wrapper
def save(self, obj):
"""Subclass the Pickler `save` method.
This is a total abuse of the Pickler class in order to use the numpy
persistence function `save` instead of the default pickle
implementation. The numpy array is replaced by a custom wrapper in the
pickle persistence stack and the serialized array is written right
after in the file. Warning: the file produced does not follow the
pickle format. As such it can not be read with `pickle.load`.
"""
if self.np is not None and type(obj) in (self.np.ndarray,
self.np.matrix,
self.np.memmap):
if type(obj) is self.np.memmap:
# Pickling doesn't work with memmapped arrays
obj = self.np.asanyarray(obj)
# The array wrapper is pickled instead of the real array.
wrapper = self._create_array_wrapper(obj)
Pickler.save(self, wrapper)
# A framer was introduced with pickle protocol 4 and we want to
# ensure the wrapper object is written before the numpy array
# buffer in the pickle file.
# See https://www.python.org/dev/peps/pep-3154/#framing to get
# more information on the framer behavior.
if self.proto >= 4:
self.framer.commit_frame(force=True)
# And then array bytes are written right after the wrapper.
wrapper.write_array(obj, self)
return
return Pickler.save(self, obj)
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self: _P) -> _P: ...
def __exit__(
self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]
) -> Optional[bool]: ...
def cwd(cls: Type[_P]) -> _P: ...
def stat(self) -> os.stat_result: ...
def chmod(self, mode: int) -> None: ...
def exists(self) -> bool: ...
def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def group(self) -> str: ...
def is_dir(self) -> bool: ...
def is_file(self) -> bool: ...
if sys.version_info >= (3, 7):
def is_mount(self) -> bool: ...
def is_symlink(self) -> bool: ...
def is_socket(self) -> bool: ...
def is_fifo(self) -> bool: ...
def is_block_device(self) -> bool: ...
def is_char_device(self) -> bool: ...
def iterdir(self: _P) -> Generator[_P, None, None]: ...
def lchmod(self, mode: int) -> None: ...
def lstat(self) -> os.stat_result: ...
def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ...
# Adapted from builtins.open
# Text mode: always returns a TextIOWrapper
def open(
self,
mode: OpenTextMode = ...,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> TextIOWrapper: ...
# Unbuffered binary mode: returns a FileIO
def open(
self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ...
) -> FileIO: ...
# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter
def open(
self,
mode: OpenBinaryModeUpdating,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedRandom: ...
def open(
self,
mode: OpenBinaryModeWriting,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedWriter: ...
def open(
self,
mode: OpenBinaryModeReading,
buffering: Literal[-1, 1] = ...,
encoding: None = ...,
errors: None = ...,
newline: None = ...,
) -> BufferedReader: ...
# Buffering cannot be determined: fall back to BinaryIO
def open(
self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ...
) -> BinaryIO: ...
# Fallback if mode is not specified
def open(
self,
mode: str,
buffering: int = ...,
encoding: Optional[str] = ...,
errors: Optional[str] = ...,
newline: Optional[str] = ...,
) -> IO[Any]: ...
def owner(self) -> str: ...
if sys.version_info >= (3, 9):
def readlink(self: _P) -> _P: ...
if sys.version_info >= (3, 8):
def rename(self: _P, target: Union[str, PurePath]) -> _P: ...
def replace(self: _P, target: Union[str, PurePath]) -> _P: ...
else:
def rename(self, target: Union[str, PurePath]) -> None: ...
def replace(self, target: Union[str, PurePath]) -> None: ...
def resolve(self: _P, strict: bool = ...) -> _P: ...
def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ...
def rmdir(self) -> None: ...
def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ...
def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ...
if sys.version_info >= (3, 8):
def unlink(self, missing_ok: bool = ...) -> None: ...
else:
def unlink(self) -> None: ...
def home(cls: Type[_P]) -> _P: ...
def absolute(self: _P) -> _P: ...
def expanduser(self: _P) -> _P: ...
def read_bytes(self) -> bytes: ...
def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ...
def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ...
def write_bytes(self, data: bytes) -> int: ...
def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ...
if sys.version_info >= (3, 8):
def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ...
try:
import lz4
from lz4.frame import LZ4FrameFile
except ImportError:
lz4 = None
LZ4_NOT_INSTALLED_ERROR = ('LZ4 is not installed. Install it with pip: '
'https://python-lz4.readthedocs.io/')
_COMPRESSORS = {}
def _write_fileobject(filename, compress=("zlib", 3)):
"""Return the right compressor file object in write mode."""
compressmethod = compress[0]
compresslevel = compress[1]
if compressmethod in _COMPRESSORS.keys():
file_instance = _COMPRESSORS[compressmethod].compressor_file(
filename, compresslevel=compresslevel)
return _buffered_write_file(file_instance)
else:
file_instance = _COMPRESSORS['zlib'].compressor_file(
filename, compresslevel=compresslevel)
return _buffered_write_file(file_instance)
The provided code snippet includes necessary dependencies for implementing the `dump` function. Write a Python function `def dump(value, filename, compress=0, protocol=None, cache_size=None)` to solve the following problem:
Persist an arbitrary Python object into one file. Read more in the :ref:`User Guide <persistence>`. Parameters ----------- value: any Python object The object to store to disk. filename: str, pathlib.Path, or file object. The file object or path of the file in which it is to be stored. The compression method corresponding to one of the supported filename extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used automatically. compress: int from 0 to 9 or bool or 2-tuple, optional Optional compression level for the data. 0 or False is no compression. Higher value means more compression, but also slower read and write times. Using a value of 3 is often a good compromise. See the notes for more details. If compress is True, the compression level used is 3. If compress is a 2-tuple, the first element must correspond to a string between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma' 'xz'), the second element must be an integer from 0 to 9, corresponding to the compression level. protocol: int, optional Pickle protocol, see pickle.dump documentation for more details. cache_size: positive int, optional This option is deprecated in 0.10 and has no effect. Returns ------- filenames: list of strings The list of file names in which the data is stored. If compress is false, each array is stored in a different file. See Also -------- joblib.load : corresponding loader Notes ----- Memmapping on load cannot be used for compressed files. Thus using compression can significantly slow down loading. In addition, compressed files take extra extra memory during dump and load.
Here is the function:
def dump(value, filename, compress=0, protocol=None, cache_size=None):
"""Persist an arbitrary Python object into one file.
Read more in the :ref:`User Guide <persistence>`.
Parameters
-----------
value: any Python object
The object to store to disk.
filename: str, pathlib.Path, or file object.
The file object or path of the file in which it is to be stored.
The compression method corresponding to one of the supported filename
extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used
automatically.
compress: int from 0 to 9 or bool or 2-tuple, optional
Optional compression level for the data. 0 or False is no compression.
Higher value means more compression, but also slower read and
write times. Using a value of 3 is often a good compromise.
See the notes for more details.
If compress is True, the compression level used is 3.
If compress is a 2-tuple, the first element must correspond to a string
between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma'
'xz'), the second element must be an integer from 0 to 9, corresponding
to the compression level.
protocol: int, optional
Pickle protocol, see pickle.dump documentation for more details.
cache_size: positive int, optional
This option is deprecated in 0.10 and has no effect.
Returns
-------
filenames: list of strings
The list of file names in which the data is stored. If
compress is false, each array is stored in a different file.
See Also
--------
joblib.load : corresponding loader
Notes
-----
Memmapping on load cannot be used for compressed files. Thus
using compression can significantly slow down loading. In
addition, compressed files take extra extra memory during
dump and load.
"""
if Path is not None and isinstance(filename, Path):
filename = str(filename)
is_filename = isinstance(filename, str)
is_fileobj = hasattr(filename, "write")
compress_method = 'zlib' # zlib is the default compression method.
if compress is True:
# By default, if compress is enabled, we want the default compress
# level of the compressor.
compress_level = None
elif isinstance(compress, tuple):
# a 2-tuple was set in compress
if len(compress) != 2:
raise ValueError(
'Compress argument tuple should contain exactly 2 elements: '
'(compress method, compress level), you passed {}'
.format(compress))
compress_method, compress_level = compress
elif isinstance(compress, str):
compress_method = compress
compress_level = None # Use default compress level
compress = (compress_method, compress_level)
else:
compress_level = compress
if compress_method == 'lz4' and lz4 is None:
raise ValueError(LZ4_NOT_INSTALLED_ERROR)
if (compress_level is not None and
compress_level is not False and
compress_level not in range(10)):
# Raising an error if a non valid compress level is given.
raise ValueError(
'Non valid compress level given: "{}". Possible values are '
'{}.'.format(compress_level, list(range(10))))
if compress_method not in _COMPRESSORS:
# Raising an error if an unsupported compression method is given.
raise ValueError(
'Non valid compression method given: "{}". Possible values are '
'{}.'.format(compress_method, _COMPRESSORS))
if not is_filename and not is_fileobj:
# People keep inverting arguments, and the resulting error is
# incomprehensible
raise ValueError(
'Second argument should be a filename or a file-like object, '
'%s (type %s) was given.'
% (filename, type(filename))
)
if is_filename and not isinstance(compress, tuple):
# In case no explicit compression was requested using both compression
# method and level in a tuple and the filename has an explicit
# extension, we select the corresponding compressor.
# unset the variable to be sure no compression level is set afterwards.
compress_method = None
for name, compressor in _COMPRESSORS.items():
if filename.endswith(compressor.extension):
compress_method = name
if compress_method in _COMPRESSORS and compress_level == 0:
# we choose the default compress_level in case it was not given
# as an argument (using compress).
compress_level = None
if cache_size is not None:
# Cache size is deprecated starting from version 0.10
warnings.warn("Please do not set 'cache_size' in joblib.dump, "
"this parameter has no effect and will be removed. "
"You used 'cache_size={}'".format(cache_size),
DeprecationWarning, stacklevel=2)
if compress_level != 0:
with _write_fileobject(filename, compress=(compress_method,
compress_level)) as f:
NumpyPickler(f, protocol=protocol).dump(value)
elif is_filename:
with open(filename, 'wb') as f:
NumpyPickler(f, protocol=protocol).dump(value)
else:
NumpyPickler(filename, protocol=protocol).dump(value)
# If the target container is a file object, nothing is returned.
if is_fileobj:
return
# For compatibility, the list of created filenames (e.g with one element
# after 0.10.0) is returned by default.
return [filename] | Persist an arbitrary Python object into one file. Read more in the :ref:`User Guide <persistence>`. Parameters ----------- value: any Python object The object to store to disk. filename: str, pathlib.Path, or file object. The file object or path of the file in which it is to be stored. The compression method corresponding to one of the supported filename extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used automatically. compress: int from 0 to 9 or bool or 2-tuple, optional Optional compression level for the data. 0 or False is no compression. Higher value means more compression, but also slower read and write times. Using a value of 3 is often a good compromise. See the notes for more details. If compress is True, the compression level used is 3. If compress is a 2-tuple, the first element must correspond to a string between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma' 'xz'), the second element must be an integer from 0 to 9, corresponding to the compression level. protocol: int, optional Pickle protocol, see pickle.dump documentation for more details. cache_size: positive int, optional This option is deprecated in 0.10 and has no effect. Returns ------- filenames: list of strings The list of file names in which the data is stored. If compress is false, each array is stored in a different file. See Also -------- joblib.load : corresponding loader Notes ----- Memmapping on load cannot be used for compressed files. Thus using compression can significantly slow down loading. In addition, compressed files take extra extra memory during dump and load. |
172,264 | import pickle
import os
import warnings
import io
from pathlib import Path
from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR
from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile
from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,
BZ2CompressorWrapper, LZMACompressorWrapper,
XZCompressorWrapper, LZ4CompressorWrapper)
from .numpy_pickle_utils import Unpickler, Pickler
from .numpy_pickle_utils import _read_fileobject, _write_fileobject
from .numpy_pickle_utils import _read_bytes, BUFFER_SIZE
from .numpy_pickle_utils import _ensure_native_byte_order
from .numpy_pickle_compat import load_compatibility
from .numpy_pickle_compat import NDArrayWrapper
from .numpy_pickle_compat import ZNDArrayWrapper
from .backports import make_memmap
def load(filename, mmap_mode=None):
"""Reconstruct a Python object from a file persisted with joblib.dump.
Read more in the :ref:`User Guide <persistence>`.
WARNING: joblib.load relies on the pickle module and can therefore
execute arbitrary Python code. It should therefore never be used
to load files from untrusted sources.
Parameters
-----------
filename: str, pathlib.Path, or file object.
The file object or path of the file from which to load the object
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
If not None, the arrays are memory-mapped from the disk. This
mode has no effect for compressed files. Note that in this
case the reconstructed object might no longer match exactly
the originally pickled object.
Returns
-------
result: any Python object
The object stored in the file.
See Also
--------
joblib.dump : function to save an object
Notes
-----
This function can load numpy array files saved separately during the
dump. If the mmap_mode argument is given, it is passed to np.load and
arrays are loaded as memmaps. As a consequence, the reconstructed
object might not match the original pickled object. Note that if the
file was saved with compression, the arrays cannot be memmapped.
"""
if Path is not None and isinstance(filename, Path):
filename = str(filename)
if hasattr(filename, "read"):
fobj = filename
filename = getattr(fobj, 'name', '')
with _read_fileobject(fobj, filename, mmap_mode) as fobj:
obj = _unpickle(fobj)
else:
with open(filename, 'rb') as f:
with _read_fileobject(f, filename, mmap_mode) as fobj:
if isinstance(fobj, str):
# if the returned file object is a string, this means we
# try to load a pickle file generated with an version of
# Joblib so we load it with joblib compatibility function.
return load_compatibility(fobj)
obj = _unpickle(fobj, filename, mmap_mode)
return obj
JOBLIB_MMAPS = set()
def add_maybe_unlink_finalizer(memmap):
util.debug(
"[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid {})"
"".format(type(memmap), id(memmap), os.path.basename(memmap.filename),
os.getpid()))
weakref.finalize(memmap, _log_and_unlink, memmap.filename)
def load_temporary_memmap(filename, mmap_mode, unlink_on_gc_collect):
from ._memmapping_reducer import JOBLIB_MMAPS, add_maybe_unlink_finalizer
obj = load(filename, mmap_mode)
JOBLIB_MMAPS.add(obj.filename)
if unlink_on_gc_collect:
add_maybe_unlink_finalizer(obj)
return obj | null |
172,265 | import ast
import operator as op
def eval_(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand))
else:
raise TypeError(node)
The provided code snippet includes necessary dependencies for implementing the `eval_expr` function. Write a Python function `def eval_expr(expr)` to solve the following problem:
>>> eval_expr('2*6') 12 >>> eval_expr('2**6') 64 >>> eval_expr('1 + 2*3**(4) / (6 + -7)') -161.0
Here is the function:
def eval_expr(expr):
"""
>>> eval_expr('2*6')
12
>>> eval_expr('2**6')
64
>>> eval_expr('1 + 2*3**(4) / (6 + -7)')
-161.0
"""
try:
return eval_(ast.parse(expr, mode="eval").body)
except (TypeError, SyntaxError, KeyError) as e:
raise ValueError(
f"{expr!r} is not a valid or supported arithmetic expression."
) from e | >>> eval_expr('2*6') 12 >>> eval_expr('2**6') 64 >>> eval_expr('1 + 2*3**(4) / (6 + -7)') -161.0 |
172,266 | from mmap import mmap
import errno
import os
import stat
import threading
import atexit
import tempfile
import time
import warnings
import weakref
from uuid import uuid4
from multiprocessing import util
from pickle import whichmodule, loads, dumps, HIGHEST_PROTOCOL, PicklingError
from .numpy_pickle import dump, load, load_temporary_memmap
from .backports import make_memmap
from .disk import delete_folder
from .externals.loky.backend import resource_tracker
import os
os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE")
The provided code snippet includes necessary dependencies for implementing the `unlink_file` function. Write a Python function `def unlink_file(filename)` to solve the following problem:
Wrapper around os.unlink with a retry mechanism. The retry mechanism has been implemented primarily to overcome a race condition happening during the finalizer of a np.memmap: when a process holding the last reference to a mmap-backed np.memmap/np.array is about to delete this array (and close the reference), it sends a maybe_unlink request to the resource_tracker. This request can be processed faster than it takes for the last reference of the memmap to be closed, yielding (on Windows) a PermissionError in the resource_tracker loop.
Here is the function:
def unlink_file(filename):
"""Wrapper around os.unlink with a retry mechanism.
The retry mechanism has been implemented primarily to overcome a race
condition happening during the finalizer of a np.memmap: when a process
holding the last reference to a mmap-backed np.memmap/np.array is about to
delete this array (and close the reference), it sends a maybe_unlink
request to the resource_tracker. This request can be processed faster than
it takes for the last reference of the memmap to be closed, yielding (on
Windows) a PermissionError in the resource_tracker loop.
"""
NUM_RETRIES = 10
for retry_no in range(1, NUM_RETRIES + 1):
try:
os.unlink(filename)
break
except PermissionError:
util.debug(
'[ResourceTracker] tried to unlink {}, got '
'PermissionError'.format(filename)
)
if retry_no == NUM_RETRIES:
raise
else:
time.sleep(.2)
except FileNotFoundError:
# In case of a race condition when deleting the temporary folder,
# avoid noisy FileNotFoundError exception in the resource tracker.
pass | Wrapper around os.unlink with a retry mechanism. The retry mechanism has been implemented primarily to overcome a race condition happening during the finalizer of a np.memmap: when a process holding the last reference to a mmap-backed np.memmap/np.array is about to delete this array (and close the reference), it sends a maybe_unlink request to the resource_tracker. This request can be processed faster than it takes for the last reference of the memmap to be closed, yielding (on Windows) a PermissionError in the resource_tracker loop. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.