index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
28,726 | microdot.microdot | post | Decorator that is used to register a function as a ``POST`` request
handler for a given URL.
:param url_pattern: The URL pattern that will be compared against
incoming requests.
This decorator can be used as an alias to the``route`` decorator with
``methods=['POST']``.
Example::
@app.post('/users')
def create_user(request):
# ...
| def post(self, url_pattern):
"""Decorator that is used to register a function as a ``POST`` request
handler for a given URL.
:param url_pattern: The URL pattern that will be compared against
incoming requests.
This decorator can be used as an alias to the``route`` decorator with
``methods=['POST']``.
Example::
@app.post('/users')
def create_user(request):
# ...
"""
return self.route(url_pattern, methods=['POST'])
| (self, url_pattern) |
28,727 | microdot.microdot | put | Decorator that is used to register a function as a ``PUT`` request
handler for a given URL.
:param url_pattern: The URL pattern that will be compared against
incoming requests.
This decorator can be used as an alias to the ``route`` decorator with
``methods=['PUT']``.
Example::
@app.put('/users/<int:id>')
def edit_user(request, id):
# ...
| def put(self, url_pattern):
"""Decorator that is used to register a function as a ``PUT`` request
handler for a given URL.
:param url_pattern: The URL pattern that will be compared against
incoming requests.
This decorator can be used as an alias to the ``route`` decorator with
``methods=['PUT']``.
Example::
@app.put('/users/<int:id>')
def edit_user(request, id):
# ...
"""
return self.route(url_pattern, methods=['PUT'])
| (self, url_pattern) |
28,728 | microdot.microdot | route | Decorator that is used to register a function as a request handler
for a given URL.
:param url_pattern: The URL pattern that will be compared against
incoming requests.
:param methods: The list of HTTP methods to be handled by the
decorated function. If omitted, only ``GET`` requests
are handled.
The URL pattern can be a static path (for example, ``/users`` or
``/api/invoices/search``) or a path with dynamic components enclosed
in ``<`` and ``>`` (for example, ``/users/<id>`` or
``/invoices/<number>/products``). Dynamic path components can also
include a type prefix, separated from the name with a colon (for
example, ``/users/<int:id>``). The type can be ``string`` (the
default), ``int``, ``path`` or ``re:[regular-expression]``.
The first argument of the decorated function must be
the request object. Any path arguments that are specified in the URL
pattern are passed as keyword arguments. The return value of the
function must be a :class:`Response` instance, or the arguments to
be passed to this class.
Example::
@app.route('/')
def index(request):
return 'Hello, world!'
| def route(self, url_pattern, methods=None):
"""Decorator that is used to register a function as a request handler
for a given URL.
:param url_pattern: The URL pattern that will be compared against
incoming requests.
:param methods: The list of HTTP methods to be handled by the
decorated function. If omitted, only ``GET`` requests
are handled.
The URL pattern can be a static path (for example, ``/users`` or
``/api/invoices/search``) or a path with dynamic components enclosed
in ``<`` and ``>`` (for example, ``/users/<id>`` or
``/invoices/<number>/products``). Dynamic path components can also
include a type prefix, separated from the name with a colon (for
example, ``/users/<int:id>``). The type can be ``string`` (the
default), ``int``, ``path`` or ``re:[regular-expression]``.
The first argument of the decorated function must be
the request object. Any path arguments that are specified in the URL
pattern are passed as keyword arguments. The return value of the
function must be a :class:`Response` instance, or the arguments to
be passed to this class.
Example::
@app.route('/')
def index(request):
return 'Hello, world!'
"""
def decorated(f):
self.url_map.append(
([m.upper() for m in (methods or ['GET'])],
URLPattern(url_pattern), f))
return f
return decorated
| (self, url_pattern, methods=None) |
28,729 | microdot.asgi | run | Normally you would not start the server by invoking this method.
Instead, start your chosen ASGI web server and pass the ``Microdot``
instance as the ASGI application.
| def run(self, host='0.0.0.0', port=5000, debug=False,
**options): # pragma: no cover
"""Normally you would not start the server by invoking this method.
Instead, start your chosen ASGI web server and pass the ``Microdot``
instance as the ASGI application.
"""
self.embedded_server = True
super().run(host=host, port=port, debug=debug, **options)
| (self, host='0.0.0.0', port=5000, debug=False, **options) |
28,730 | microdot.asgi | shutdown | null | def shutdown(self):
if self.embedded_server: # pragma: no cover
super().shutdown()
else:
pid = os.getpgrp() if hasattr(os, 'getpgrp') else os.getpid()
os.kill(pid, signal.SIGTERM)
| (self) |
28,731 | microdot.microdot | start_server | Start the Microdot web server as a coroutine. This coroutine does
not normally return, as the server enters an endless listening loop.
The :func:`shutdown` function provides a method for terminating the
server gracefully.
:param host: The hostname or IP address of the network interface that
will be listening for requests. A value of ``'0.0.0.0'``
(the default) indicates that the server should listen for
requests on all the available interfaces, and a value of
``127.0.0.1`` indicates that the server should listen
for requests only on the internal networking interface of
the host.
:param port: The port number to listen for requests. The default is
port 5000.
:param debug: If ``True``, the server logs debugging information. The
default is ``False``.
:param ssl: An ``SSLContext`` instance or ``None`` if the server should
not use TLS. The default is ``None``.
This method is a coroutine.
Example::
import asyncio
from microdot_asyncio import Microdot
app = Microdot()
@app.route('/')
async def index(request):
return 'Hello, world!'
async def main():
await app.start_server(debug=True)
asyncio.run(main())
| @staticmethod
def abort(status_code, reason=None):
"""Abort the current request and return an error response with the
given status code.
:param status_code: The numeric status code of the response.
:param reason: The reason for the response, which is included in the
response body.
Example::
from microdot import abort
@app.route('/users/<int:id>')
def get_user(id):
user = get_user_by_id(id)
if user is None:
abort(404)
return user.to_dict()
"""
raise HTTPException(status_code, reason)
| (self, host='0.0.0.0', port=5000, debug=False, ssl=None) |
28,734 | azure_databricks_api.__rest_client | AzureDatabricksRESTClient |
API List:
Instance Profiles
Profiles Add
Profiles List
Profiles Remove
| class AzureDatabricksRESTClient(object):
"""
API List:
Instance Profiles
Profiles Add
Profiles List
Profiles Remove
"""
def __init__(self, region, token):
self._region = region
self._token = token
self._host = 'https://{region}.azuredatabricks.net'.format(region=self._region)
self.api_version = '2.0'
parameters = {'host': self._host, 'api_version': self.api_version, 'token': self._token}
self.clusters = ClusterAPI(**parameters)
self.groups = GroupsAPI(**parameters)
self.tokens = TokensAPI(**parameters)
self.workspace = WorkspaceAPI(**parameters)
self.dbfs = DbfsAPI(**parameters)
self.libraries = LibrariesAPI(**parameters)
| (region, token) |
28,735 | azure_databricks_api.__rest_client | __init__ | null | def __init__(self, region, token):
self._region = region
self._token = token
self._host = 'https://{region}.azuredatabricks.net'.format(region=self._region)
self.api_version = '2.0'
parameters = {'host': self._host, 'api_version': self.api_version, 'token': self._token}
self.clusters = ClusterAPI(**parameters)
self.groups = GroupsAPI(**parameters)
self.tokens = TokensAPI(**parameters)
self.workspace = WorkspaceAPI(**parameters)
self.dbfs = DbfsAPI(**parameters)
self.libraries = LibrariesAPI(**parameters)
| (self, region, token) |
28,763 | heapdict | heapdict | null | class heapdict(MutableMapping):
__marker = object()
def __init__(self, *args, **kw):
self.heap = []
self.d = {}
self.update(*args, **kw)
@doc(dict.clear)
def clear(self):
del self.heap[:]
self.d.clear()
@doc(dict.__setitem__)
def __setitem__(self, key, value):
if key in self.d:
self.pop(key)
wrapper = [value, key, len(self)]
self.d[key] = wrapper
self.heap.append(wrapper)
self._decrease_key(len(self.heap)-1)
def _min_heapify(self, i):
n = len(self.heap)
h = self.heap
while True:
# calculate the offset of the left child
l = (i << 1) + 1
# calculate the offset of the right child
r = (i + 1) << 1
if l < n and h[l][0] < h[i][0]:
low = l
else:
low = i
if r < n and h[r][0] < h[low][0]:
low = r
if low == i:
break
self._swap(i, low)
i = low
def _decrease_key(self, i):
while i:
# calculate the offset of the parent
parent = (i - 1) >> 1
if self.heap[parent][0] < self.heap[i][0]:
break
self._swap(i, parent)
i = parent
def _swap(self, i, j):
h = self.heap
h[i], h[j] = h[j], h[i]
h[i][2] = i
h[j][2] = j
@doc(dict.__delitem__)
def __delitem__(self, key):
wrapper = self.d[key]
while wrapper[2]:
# calculate the offset of the parent
parentpos = (wrapper[2] - 1) >> 1
parent = self.heap[parentpos]
self._swap(wrapper[2], parent[2])
self.popitem()
@doc(dict.__getitem__)
def __getitem__(self, key):
return self.d[key][0]
@doc(dict.__iter__)
def __iter__(self):
return iter(self.d)
def popitem(self):
"""D.popitem() -> (k, v), remove and return the (key, value) pair with lowest\nvalue; but raise KeyError if D is empty."""
wrapper = self.heap[0]
if len(self.heap) == 1:
self.heap.pop()
else:
self.heap[0] = self.heap.pop()
self.heap[0][2] = 0
self._min_heapify(0)
del self.d[wrapper[1]]
return wrapper[1], wrapper[0]
@doc(dict.__len__)
def __len__(self):
return len(self.d)
def peekitem(self):
"""D.peekitem() -> (k, v), return the (key, value) pair with lowest value;\n but raise KeyError if D is empty."""
return (self.heap[0][1], self.heap[0][0])
| (*args, **kw) |
28,765 | heapdict | __delitem__ | Delete self[key]. | @doc(dict.__delitem__)
def __delitem__(self, key):
wrapper = self.d[key]
while wrapper[2]:
# calculate the offset of the parent
parentpos = (wrapper[2] - 1) >> 1
parent = self.heap[parentpos]
self._swap(wrapper[2], parent[2])
self.popitem()
| (self, key) |
28,767 | heapdict | __getitem__ | x.__getitem__(y) <==> x[y] | @doc(dict.__getitem__)
def __getitem__(self, key):
return self.d[key][0]
| (self, key) |
28,768 | heapdict | __init__ | null | def __init__(self, *args, **kw):
self.heap = []
self.d = {}
self.update(*args, **kw)
| (self, *args, **kw) |
28,769 | heapdict | __iter__ | Implement iter(self). | @doc(dict.__iter__)
def __iter__(self):
return iter(self.d)
| (self) |
28,770 | heapdict | __len__ | Return len(self). | @doc(dict.__len__)
def __len__(self):
return len(self.d)
| (self) |
28,771 | heapdict | __setitem__ | Set self[key] to value. | @doc(dict.__setitem__)
def __setitem__(self, key, value):
if key in self.d:
self.pop(key)
wrapper = [value, key, len(self)]
self.d[key] = wrapper
self.heap.append(wrapper)
self._decrease_key(len(self.heap)-1)
| (self, key, value) |
28,772 | heapdict | _decrease_key | null | def _decrease_key(self, i):
while i:
# calculate the offset of the parent
parent = (i - 1) >> 1
if self.heap[parent][0] < self.heap[i][0]:
break
self._swap(i, parent)
i = parent
| (self, i) |
28,773 | heapdict | _min_heapify | null | def _min_heapify(self, i):
n = len(self.heap)
h = self.heap
while True:
# calculate the offset of the left child
l = (i << 1) + 1
# calculate the offset of the right child
r = (i + 1) << 1
if l < n and h[l][0] < h[i][0]:
low = l
else:
low = i
if r < n and h[r][0] < h[low][0]:
low = r
if low == i:
break
self._swap(i, low)
i = low
| (self, i) |
28,774 | heapdict | _swap | null | def _swap(self, i, j):
h = self.heap
h[i], h[j] = h[j], h[i]
h[i][2] = i
h[j][2] = j
| (self, i, j) |
28,775 | heapdict | clear | D.clear() -> None. Remove all items from D. | @doc(dict.clear)
def clear(self):
del self.heap[:]
self.d.clear()
| (self) |
28,779 | heapdict | peekitem | D.peekitem() -> (k, v), return the (key, value) pair with lowest value;
but raise KeyError if D is empty. | def peekitem(self):
"""D.peekitem() -> (k, v), return the (key, value) pair with lowest value;\n but raise KeyError if D is empty."""
return (self.heap[0][1], self.heap[0][0])
| (self) |
28,781 | heapdict | popitem | D.popitem() -> (k, v), remove and return the (key, value) pair with lowest
value; but raise KeyError if D is empty. | def popitem(self):
"""D.popitem() -> (k, v), remove and return the (key, value) pair with lowest\nvalue; but raise KeyError if D is empty."""
wrapper = self.heap[0]
if len(self.heap) == 1:
self.heap.pop()
else:
self.heap[0] = self.heap.pop()
self.heap[0][2] = 0
self._min_heapify(0)
del self.d[wrapper[1]]
return wrapper[1], wrapper[0]
| (self) |
28,785 | ipytextual.driver | Driver | A headless driver that may be run remotely. | class Driver(_Driver):
"""A headless driver that may be run remotely."""
def __init__(
self, app: App, *, debug: bool = False, size: tuple[int, int] | None = None
):
if size is None:
if SIZE[0] is not None:
width = SIZE[0]
height = SIZE[1]
size = width, height
super().__init__(app, debug=debug, size=size)
self.exit_event = Event()
self._process_input_task = asyncio.create_task(self.process_input())
self._stdout_queue = asyncio.Queue()
self._stdin_queue = asyncio.Queue()
def write(self, data: str) -> None:
"""Write data to the output device.
Args:
data: Raw data.
"""
data_bytes = data.encode("utf-8")
self._stdout_queue.put_nowait(b"D%s%s" % (len(data_bytes).to_bytes(4, "big"), data_bytes))
def write_meta(self, data: dict[str, object]) -> None:
"""Write meta to the controlling process (i.e. textual-web)
Args:
data: Meta dict.
"""
meta_bytes = json.dumps(data).encode("utf-8", errors="ignore")
self._stdout_queue.put_nowait(b"M%s%s" % (len(meta_bytes).to_bytes(4, "big"), meta_bytes))
def flush(self) -> None:
pass
def _enable_mouse_support(self) -> None:
"""Enable reporting of mouse events."""
write = self.write
write("\x1b[?1000h") # SET_VT200_MOUSE
write("\x1b[?1003h") # SET_ANY_EVENT_MOUSE
write("\x1b[?1015h") # SET_VT200_HIGHLIGHT_MOUSE
write("\x1b[?1006h") # SET_SGR_EXT_MODE_MOUSE
def _enable_bracketed_paste(self) -> None:
"""Enable bracketed paste mode."""
self.write("\x1b[?2004h")
def _disable_bracketed_paste(self) -> None:
"""Disable bracketed paste mode."""
self.write("\x1b[?2004l")
def _disable_mouse_support(self) -> None:
"""Disable reporting of mouse events."""
write = self.write
write("\x1b[?1000l") #
write("\x1b[?1003l") #
write("\x1b[?1015l")
write("\x1b[?1006l")
def _request_terminal_sync_mode_support(self) -> None:
"""Writes an escape sequence to query the terminal support for the sync protocol."""
self.write("\033[?2026$p")
def start_application_mode(self) -> None:
"""Start application mode."""
loop = asyncio.get_running_loop()
def do_exit() -> None:
"""Callback to force exit."""
asyncio.run_coroutine_threadsafe(
self._app._post_message(messages.ExitApp()), loop=loop
)
if not WINDOWS:
for _signal in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(_signal, do_exit)
self._stdout_queue.put_nowait(b"__GANGLION__\n")
self.write("\x1b[?1049h") # Alt screen
self._enable_mouse_support()
self.write("\x1b[?25l") # Hide cursor
self.write("\033[?1003h\n")
size = Size(80, 24) if self._size is None else Size(*self._size)
event = events.Resize(size, size)
asyncio.run_coroutine_threadsafe(
self._app._post_message(event),
loop=loop,
)
self._request_terminal_sync_mode_support()
self._enable_bracketed_paste()
self.flush()
def disable_input(self) -> None:
"""Disable further input."""
def stop_application_mode(self) -> None:
"""Stop application mode, restore state."""
self.exit_event.set()
self.write_meta({"type": "exit"})
async def process_input(self) -> None:
"""Wait for input and dispatch events."""
data = await self._stdin_queue.get()
def more_data():
return not self._stdin_queue.empty()
parser = XTermParser(more_data, debug=self._debug)
utf8_decoder = getincrementaldecoder("utf-8")().decode
decode = utf8_decoder
# The server sends us a stream of bytes, which contains the equivalent of stdin, plus
# in band data packets.
byte_stream = ByteStream()
try:
while True:
data = await self._stdin_queue.get()
for packet_type, payload in byte_stream.feed(data):
if packet_type == "D":
# Treat as stdin
for event in parser.feed(decode(payload)):
self.process_event(event)
else:
# Process meta information separately
self._on_meta(packet_type, payload)
except _ExitInput:
pass
except Exception:
from traceback import format_exc
log(format_exc())
finally:
self._process_input_task.cancel()
def _on_meta(self, packet_type: str, payload: bytes) -> None:
"""Private method to dispatch meta.
Args:
packet_type: Packet type (currently always "M")
payload: Meta payload (JSON encoded as bytes).
"""
payload_map = json.loads(payload)
_type = payload_map.get("type")
if isinstance(payload_map, dict):
self.on_meta(_type, payload_map)
def on_meta(self, packet_type: str, payload: dict) -> None:
"""Process meta information.
Args:
packet_type: The type of the packet.
payload: meta dict.
"""
if packet_type == "resize":
self._size = (payload["width"], payload["height"])
size = Size(*self._size)
self._app.post_message(events.Resize(size, size))
elif packet_type == "quit":
self._app.post_message(messages.ExitApp())
elif packet_type == "exit":
raise _ExitInput()
| (app: 'App', *, debug: 'bool' = False, size: 'tuple[int, int] | None' = None) |
28,786 | ipytextual.driver | __init__ | null | def __init__(
self, app: App, *, debug: bool = False, size: tuple[int, int] | None = None
):
if size is None:
if SIZE[0] is not None:
width = SIZE[0]
height = SIZE[1]
size = width, height
super().__init__(app, debug=debug, size=size)
self.exit_event = Event()
self._process_input_task = asyncio.create_task(self.process_input())
self._stdout_queue = asyncio.Queue()
self._stdin_queue = asyncio.Queue()
| (self, app: textual.app.App, *, debug: bool = False, size: Optional[tuple[int, int]] = None) |
28,787 | ipytextual.driver | _disable_bracketed_paste | Disable bracketed paste mode. | def _disable_bracketed_paste(self) -> None:
"""Disable bracketed paste mode."""
self.write("\x1b[?2004l")
| (self) -> NoneType |
28,788 | ipytextual.driver | _disable_mouse_support | Disable reporting of mouse events. | def _disable_mouse_support(self) -> None:
"""Disable reporting of mouse events."""
write = self.write
write("\x1b[?1000l") #
write("\x1b[?1003l") #
write("\x1b[?1015l")
write("\x1b[?1006l")
| (self) -> NoneType |
28,789 | ipytextual.driver | _enable_bracketed_paste | Enable bracketed paste mode. | def _enable_bracketed_paste(self) -> None:
"""Enable bracketed paste mode."""
self.write("\x1b[?2004h")
| (self) -> NoneType |
28,790 | ipytextual.driver | _enable_mouse_support | Enable reporting of mouse events. | def _enable_mouse_support(self) -> None:
"""Enable reporting of mouse events."""
write = self.write
write("\x1b[?1000h") # SET_VT200_MOUSE
write("\x1b[?1003h") # SET_ANY_EVENT_MOUSE
write("\x1b[?1015h") # SET_VT200_HIGHLIGHT_MOUSE
write("\x1b[?1006h") # SET_SGR_EXT_MODE_MOUSE
| (self) -> NoneType |
28,791 | ipytextual.driver | _on_meta | Private method to dispatch meta.
Args:
packet_type: Packet type (currently always "M")
payload: Meta payload (JSON encoded as bytes).
| def _on_meta(self, packet_type: str, payload: bytes) -> None:
"""Private method to dispatch meta.
Args:
packet_type: Packet type (currently always "M")
payload: Meta payload (JSON encoded as bytes).
"""
payload_map = json.loads(payload)
_type = payload_map.get("type")
if isinstance(payload_map, dict):
self.on_meta(_type, payload_map)
| (self, packet_type: str, payload: bytes) -> NoneType |
28,792 | ipytextual.driver | _request_terminal_sync_mode_support | Writes an escape sequence to query the terminal support for the sync protocol. | def _request_terminal_sync_mode_support(self) -> None:
"""Writes an escape sequence to query the terminal support for the sync protocol."""
self.write("\033[?2026$p")
| (self) -> NoneType |
28,793 | textual.driver | close | Perform any final cleanup. | def close(self) -> None:
"""Perform any final cleanup."""
| (self) -> NoneType |
28,794 | ipytextual.driver | disable_input | Disable further input. | def disable_input(self) -> None:
"""Disable further input."""
| (self) -> NoneType |
28,795 | ipytextual.driver | flush | null | def flush(self) -> None:
pass
| (self) -> NoneType |
28,796 | textual.driver | no_automatic_restart | A context manager used to tell the driver to not auto-restart.
For drivers that support the application being suspended by the
operating system, this context manager is used to mark a body of
code as one that will manage its own stop and start.
| null | (self) -> Iterator[NoneType] |
28,797 | ipytextual.driver | on_meta | Process meta information.
Args:
packet_type: The type of the packet.
payload: meta dict.
| def on_meta(self, packet_type: str, payload: dict) -> None:
"""Process meta information.
Args:
packet_type: The type of the packet.
payload: meta dict.
"""
if packet_type == "resize":
self._size = (payload["width"], payload["height"])
size = Size(*self._size)
self._app.post_message(events.Resize(size, size))
elif packet_type == "quit":
self._app.post_message(messages.ExitApp())
elif packet_type == "exit":
raise _ExitInput()
| (self, packet_type: str, payload: dict) -> NoneType |
28,798 | textual.driver | process_event | Perform additional processing on an event, prior to sending.
Args:
event: An event to send.
| def process_event(self, event: events.Event) -> None:
"""Perform additional processing on an event, prior to sending.
Args:
event: An event to send.
"""
# NOTE: This runs in a thread.
# Avoid calling methods on the app.
event.set_sender(self._app)
if self.cursor_origin is None:
offset_x = 0
offset_y = 0
else:
offset_x, offset_y = self.cursor_origin
if isinstance(event, events.MouseEvent):
event.x -= offset_x
event.y -= offset_y
event.screen_x -= offset_x
event.screen_y -= offset_y
if isinstance(event, events.MouseDown):
if event.button:
self._down_buttons.append(event.button)
elif isinstance(event, events.MouseUp):
if event.button and event.button in self._down_buttons:
self._down_buttons.remove(event.button)
elif isinstance(event, events.MouseMove):
if (
self._down_buttons
and not event.button
and self._last_move_event is not None
):
# Deduplicate self._down_buttons while preserving order.
buttons = list(dict.fromkeys(self._down_buttons).keys())
self._down_buttons.clear()
move_event = self._last_move_event
for button in buttons:
self.send_event(
MouseUp(
x=move_event.x,
y=move_event.y,
delta_x=0,
delta_y=0,
button=button,
shift=event.shift,
meta=event.meta,
ctrl=event.ctrl,
screen_x=move_event.screen_x,
screen_y=move_event.screen_y,
style=event.style,
)
)
self._last_move_event = event
self.send_event(event)
| (self, event: textual.events.Event) -> NoneType |
28,799 | ipytextual.driver | process_input | Wait for input and dispatch events. | def stop_application_mode(self) -> None:
"""Stop application mode, restore state."""
self.exit_event.set()
self.write_meta({"type": "exit"})
| (self) -> NoneType |
28,800 | textual.driver | resume_application_mode | Resume application mode.
Used to resume application mode after it has been previously
suspended.
| def resume_application_mode(self) -> None:
"""Resume application mode.
Used to resume application mode after it has been previously
suspended.
"""
self.start_application_mode()
| (self) -> NoneType |
28,801 | textual.driver | send_event | Send an event to the target app.
Args:
event: An event.
| def send_event(self, event: events.Event) -> None:
"""Send an event to the target app.
Args:
event: An event.
"""
asyncio.run_coroutine_threadsafe(
self._app._post_message(event), loop=self._loop
)
| (self, event: textual.events.Event) -> NoneType |
28,802 | ipytextual.driver | start_application_mode | Start application mode. | def start_application_mode(self) -> None:
"""Start application mode."""
loop = asyncio.get_running_loop()
def do_exit() -> None:
"""Callback to force exit."""
asyncio.run_coroutine_threadsafe(
self._app._post_message(messages.ExitApp()), loop=loop
)
if not WINDOWS:
for _signal in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(_signal, do_exit)
self._stdout_queue.put_nowait(b"__GANGLION__\n")
self.write("\x1b[?1049h") # Alt screen
self._enable_mouse_support()
self.write("\x1b[?25l") # Hide cursor
self.write("\033[?1003h\n")
size = Size(80, 24) if self._size is None else Size(*self._size)
event = events.Resize(size, size)
asyncio.run_coroutine_threadsafe(
self._app._post_message(event),
loop=loop,
)
self._request_terminal_sync_mode_support()
self._enable_bracketed_paste()
self.flush()
| (self) -> NoneType |
28,803 | ipytextual.driver | stop_application_mode | Stop application mode, restore state. | def stop_application_mode(self) -> None:
"""Stop application mode, restore state."""
self.exit_event.set()
self.write_meta({"type": "exit"})
| (self) -> NoneType |
28,804 | textual.driver | suspend_application_mode | Suspend application mode.
Used to suspend application mode and allow uninhibited access to the
terminal.
| def suspend_application_mode(self) -> None:
"""Suspend application mode.
Used to suspend application mode and allow uninhibited access to the
terminal.
"""
self.stop_application_mode()
self.close()
| (self) -> NoneType |
28,805 | ipytextual.driver | write | Write data to the output device.
Args:
data: Raw data.
| def write(self, data: str) -> None:
"""Write data to the output device.
Args:
data: Raw data.
"""
data_bytes = data.encode("utf-8")
self._stdout_queue.put_nowait(b"D%s%s" % (len(data_bytes).to_bytes(4, "big"), data_bytes))
| (self, data: str) -> NoneType |
28,806 | ipytextual.driver | write_meta | Write meta to the controlling process (i.e. textual-web)
Args:
data: Meta dict.
| def write_meta(self, data: dict[str, object]) -> None:
"""Write meta to the controlling process (i.e. textual-web)
Args:
data: Meta dict.
"""
meta_bytes = json.dumps(data).encode("utf-8", errors="ignore")
self._stdout_queue.put_nowait(b"M%s%s" % (len(meta_bytes).to_bytes(4, "big"), meta_bytes))
| (self, data: dict[str, object]) -> NoneType |
28,807 | ipytextual.widget | Widget | null | class Widget(AnyWidget):
_esm = bundler_output_dir / "index.js"
_data_from_textual = Bytes().tag(sync=True)
_data_to_textual = Unicode().tag(sync=True)
_cols = Int(80).tag(sync=True)
_rows = Int(24).tag(sync=True)
_ready = Bool().tag(sync=True)
def __init__(self, app, cols: int | None = None, rows: int | None = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._app = app
if cols is not None:
self._cols = cols
SIZE[0] = cols
if rows is not None:
self._rows = rows
SIZE[1] = rows
self._data_from_textual_queue = asyncio.Queue()
self._data_to_textual_queue = asyncio.Queue()
self._ready_event = asyncio.Event()
self._tasks = [
asyncio.create_task(self._run()),
asyncio.create_task(self._send_data()),
asyncio.create_task(self._recv_data()),
]
self.observe(self._observe_cols, names=["_cols"])
self.observe(self._observe_rows, names=["_rows"])
self.observe(self._observe_ready, names=["_ready"])
self.observe(self._observe_data_to_textual, names=["_data_to_textual"])
def _observe_data_to_textual(self, change):
data = bytes(change["new"], "utf8")
self._data_to_textual_queue.put_nowait(data)
async def _send_data(self):
await self._ready_event.wait()
while True:
data = await self._data_from_textual_queue.get()
self._data_from_textual = data
async def _recv_data(self):
while True:
data = await self._data_to_textual_queue.get()
packet_type = b"D"
packet = b"%s%s%s" % (packet_type, len(data).to_bytes(4, "big"), data)
self._app._driver._stdin_queue.put_nowait(packet)
def _observe_ready(self, change):
self._ready_event.set()
def _observe_cols(self, change):
SIZE[0] = change["new"]
def _observe_rows(self, change):
SIZE[1] = change["new"]
async def _run(self):
self._tasks.append(asyncio.create_task(self._app.run_async()))
while True:
if self._app._driver is not None:
break
await asyncio.sleep(0)
for _ in range(10):
line = []
while True:
data = await self._app._driver._stdout_queue.get()
line.append(data)
if data[-1] == 10: # "\n"
break
line = b"".join(line)
if not line:
break
if line == b"__GANGLION__\n":
ready = True
break
if ready:
META = 77 # b"M"
DATA = 68 # b"D"
while True:
data = await self._app._driver._stdout_queue.get()
type_bytes = data[0]
size_bytes = data[1:5]
size = int.from_bytes(size_bytes, "big")
data = data[5:5 + size]
if type_bytes == DATA:
self._data_from_textual_queue.put_nowait(data)
elif type_bytes == META:
meta_data = json.loads(data)
#if meta_data.get("type") == "exit":
# await self.send_meta({"type": "exit"})
#else:
# await on_meta(json.loads(data))
| (app, cols: 'int | None' = None, rows: 'int | None' = None, *args, **kwargs) |
28,812 | ipytextual.widget | __init__ | null | def __init__(self, app, cols: int | None = None, rows: int | None = None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._app = app
if cols is not None:
self._cols = cols
SIZE[0] = cols
if rows is not None:
self._rows = rows
SIZE[1] = rows
self._data_from_textual_queue = asyncio.Queue()
self._data_to_textual_queue = asyncio.Queue()
self._ready_event = asyncio.Event()
self._tasks = [
asyncio.create_task(self._run()),
asyncio.create_task(self._send_data()),
asyncio.create_task(self._recv_data()),
]
self.observe(self._observe_cols, names=["_cols"])
self.observe(self._observe_rows, names=["_rows"])
self.observe(self._observe_ready, names=["_ready"])
self.observe(self._observe_data_to_textual, names=["_data_to_textual"])
| (self, app, cols: Optional[int] = None, rows: Optional[int] = None, *args, **kwargs) |
28,828 | ipytextual.widget | _observe_cols | null | def _observe_cols(self, change):
SIZE[0] = change["new"]
| (self, change) |
28,829 | ipytextual.widget | _observe_data_to_textual | null | def _observe_data_to_textual(self, change):
data = bytes(change["new"], "utf8")
self._data_to_textual_queue.put_nowait(data)
| (self, change) |
28,830 | ipytextual.widget | _observe_ready | null | def _observe_ready(self, change):
self._ready_event.set()
| (self, change) |
28,831 | ipytextual.widget | _observe_rows | null | def _observe_rows(self, change):
SIZE[1] = change["new"]
| (self, change) |
28,836 | anywidget.widget | _repr_mimebundle_ | null | def _repr_mimebundle_(self, **kwargs: dict) -> tuple[dict, dict] | None:
plaintext = repr(self)
if len(plaintext) > 110:
plaintext = plaintext[:110] + "…"
if self._view_name is None:
return None
return repr_mimebundle(model_id=self.model_id, repr_text=plaintext)
| (self, **kwargs: dict) -> tuple[dict, dict] | None |
28,877 | netsuitesdk.connection | NetSuiteConnection | null | class NetSuiteConnection:
def __init__(self, account, consumer_key, consumer_secret, token_key, token_secret,
caching=True, caching_timeout=2592000, caching_path=None,
search_body_fields_only=True, page_size: int = 100):
ns_client = NetSuiteClient(account=account, caching=caching, caching_timeout=caching_timeout,
caching_path=caching_path, search_body_fields_only=search_body_fields_only,
page_size=page_size)
ns_client.connect_tba(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
token_key=token_key,
token_secret=token_secret
)
self.client = ns_client
self.accounts = Accounts(ns_client)
self.billing_accounts = BillingAccount(ns_client)
self.classifications = Classifications(ns_client)
self.departments = Departments(ns_client)
self.currencies = Currencies(ns_client)
self.locations = Locations(ns_client)
self.vendor_bills = VendorBills(ns_client)
self.vendor_credits = VendorCredits(ns_client)
self.vendors = Vendors(ns_client)
self.subsidiaries = Subsidiaries(ns_client)
self.journal_entries = JournalEntries(ns_client)
self.adv_inter_company_journal_entries = AdvInterCompanyJournalEntries(ns_client)
self.employees = Employees(ns_client)
self.expense_reports = ExpenseReports(ns_client)
self.folders = Folders(ns_client)
self.files = Files(ns_client)
self.expense_categories = ExpenseCategory(ns_client)
self.custom_lists = CustomLists(ns_client)
self.custom_segments = CustomSegments(ns_client)
self.custom_records = CustomRecords(ns_client)
self.custom_record_types = CustomRecordTypes(ns_client)
self.customers = Customers(ns_client)
self.projects = Projects(ns_client)
self.vendor_payments = VendorPayments(ns_client)
self.invoices = Invoices(ns_client)
self.terms = Terms(ns_client)
self.tax_items = TaxItems(ns_client)
self.tax_groups = TaxGroups(ns_client)
self.credit_memos = CreditMemos(ns_client)
self.price_level = PriceLevel(ns_client)
self.usages = Usage(ns_client)
self.items = Items(ns_client)
| (account, consumer_key, consumer_secret, token_key, token_secret, caching=True, caching_timeout=2592000, caching_path=None, search_body_fields_only=True, page_size: int = 100) |
28,878 | netsuitesdk.connection | __init__ | null | def __init__(self, account, consumer_key, consumer_secret, token_key, token_secret,
caching=True, caching_timeout=2592000, caching_path=None,
search_body_fields_only=True, page_size: int = 100):
ns_client = NetSuiteClient(account=account, caching=caching, caching_timeout=caching_timeout,
caching_path=caching_path, search_body_fields_only=search_body_fields_only,
page_size=page_size)
ns_client.connect_tba(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
token_key=token_key,
token_secret=token_secret
)
self.client = ns_client
self.accounts = Accounts(ns_client)
self.billing_accounts = BillingAccount(ns_client)
self.classifications = Classifications(ns_client)
self.departments = Departments(ns_client)
self.currencies = Currencies(ns_client)
self.locations = Locations(ns_client)
self.vendor_bills = VendorBills(ns_client)
self.vendor_credits = VendorCredits(ns_client)
self.vendors = Vendors(ns_client)
self.subsidiaries = Subsidiaries(ns_client)
self.journal_entries = JournalEntries(ns_client)
self.adv_inter_company_journal_entries = AdvInterCompanyJournalEntries(ns_client)
self.employees = Employees(ns_client)
self.expense_reports = ExpenseReports(ns_client)
self.folders = Folders(ns_client)
self.files = Files(ns_client)
self.expense_categories = ExpenseCategory(ns_client)
self.custom_lists = CustomLists(ns_client)
self.custom_segments = CustomSegments(ns_client)
self.custom_records = CustomRecords(ns_client)
self.custom_record_types = CustomRecordTypes(ns_client)
self.customers = Customers(ns_client)
self.projects = Projects(ns_client)
self.vendor_payments = VendorPayments(ns_client)
self.invoices = Invoices(ns_client)
self.terms = Terms(ns_client)
self.tax_items = TaxItems(ns_client)
self.tax_groups = TaxGroups(ns_client)
self.credit_memos = CreditMemos(ns_client)
self.price_level = PriceLevel(ns_client)
self.usages = Usage(ns_client)
self.items = Items(ns_client)
| (self, account, consumer_key, consumer_secret, token_key, token_secret, caching=True, caching_timeout=2592000, caching_path=None, search_body_fields_only=True, page_size: int = 100) |
28,879 | netsuitesdk.internal.exceptions | NetSuiteError | Exception raised for errors during login or other requests (like
get, getAll) to NetSuite. | class NetSuiteError(Exception):
"""Exception raised for errors during login or other requests (like
get, getAll) to NetSuite."""
def __init__(self, message, code=None):
"""
:param str message: Text describing the error
:param str code: Netsuite code specifying the exact error
Possible values are listed in
"""
self.message = message
self.code = code
def __str__(self):
if self.code is None:
return self.message
return 'code: {}, message: {}'.format(self.code, self.message)
| (message, code=None) |
28,880 | netsuitesdk.internal.exceptions | __init__ |
:param str message: Text describing the error
:param str code: Netsuite code specifying the exact error
Possible values are listed in
| def __init__(self, message, code=None):
"""
:param str message: Text describing the error
:param str code: Netsuite code specifying the exact error
Possible values are listed in
"""
self.message = message
self.code = code
| (self, message, code=None) |
28,881 | netsuitesdk.internal.exceptions | __str__ | null | def __str__(self):
if self.code is None:
return self.message
return 'code: {}, message: {}'.format(self.code, self.message)
| (self) |
28,882 | netsuitesdk.internal.exceptions | NetSuiteLoginError | Exception raised for errors during login to NetSuite | class NetSuiteLoginError(NetSuiteError):
"""Exception raised for errors during login to NetSuite"""
pass
| (message, code=None) |
28,885 | netsuitesdk.internal.exceptions | NetSuiteRateLimitError | Exception raised for errors during rate limit requests like get, search, .. | class NetSuiteRateLimitError(NetSuiteError):
"""Exception raised for errors during rate limit requests like get, search, .."""
pass
| (message, code=None) |
28,888 | netsuitesdk.internal.exceptions | NetSuiteRequestError | Exception raised for errors during requests like get, search, .. | class NetSuiteRequestError(NetSuiteError):
"""Exception raised for errors during requests like get, search, .."""
pass
| (message, code=None) |
28,891 | netsuitesdk.internal.exceptions | NetSuiteTypeError | Exception raised when requested an invalid netsuite type | class NetSuiteTypeError(NetSuiteError):
"""Exception raised when requested an invalid netsuite type"""
pass
| (message, code=None) |
28,898 | jupyter_highlight_selected_word | _jupyter_nbextension_paths | null | def _jupyter_nbextension_paths():
# src & dest are os paths, and so must use os.path.sep to work correctly on
# Windows.
# In contrast, require is a requirejs path, and thus must use `/` as the
# path separator.
return [dict(
section='notebook',
# src is relative to current module
src=os.path.join('static', 'highlight_selected_word'),
# dest directory is in the `nbextensions/` namespace
dest='highlight_selected_word',
# require is also in the `nbextensions/` namespace
# must use / as path.sep
require='highlight_selected_word/main',
)]
| () |
28,900 | yampex.plot | Plotter |
I provide a Matplotlib C{Figure} with one or more time-vector and
XY subplots of Numpy vectors.
Construct an instance of me with the total number of subplots (to
be intelligently apportioned into one or more rows and columns)
or, with two constructor arguments, the number of columns followed
by the number of rows.
With the I{filePath} keyword, you can specify the file path of a
PNG file for me to create or overwrite with each call to L{show}.
You can set the I{width} and I{height} of the Figure with
constructor keywords, and (read-only) access them via my
properties of the same names. Or set my I{figSize} attribute (in a
subclass or with that constructor keyword) to a 2-sequence with
figure width and height. The default width and height is just shy
of the entire monitor size.
The dimensions are in inches, converted to pixels at 100 DPI,
unless they are both integers and either of them exceeds 75 (which
would equate to a huge 7,500 pixels). In that case, they are
considered to specify the pixel dimensions directly.
Use the "Agg" backend by supplying the constructor keyword
I{useAgg}. This works better for plotting to an image file, and is
selected automatically if you supply a I{filePath} to the
constructor. Be aware that, once selected, that backend will be
used for all instances of me. If you're using the "Agg" backend,
you should specify it the first time an instance is constructed.
Setting the I{verbose} keyword C{True} puts out a bit of info
about annotator positioning. Not for regular use.
Any other keywords you supply to the constructor are supplied to
the underlying Matplotlib plotting call for all
subplots.
Keep the API for L{OptsBase} handy, and maybe a copy of the
U{source<http://edsuom.com/yampex/yampex.plot.py>}, to see all the
plotting options you can set.
@ivar dims: A dict (actually, a subclass of L{Dims}) of sub-dicts
of the dimensions of various text objects, keyed first by
subplot index then the object name.
@ivar Nsp: The number of subplots defined thus far defined with
calls to my instance.
| class Plotter(OptsBase):
"""
I provide a Matplotlib C{Figure} with one or more time-vector and
XY subplots of Numpy vectors.
Construct an instance of me with the total number of subplots (to
be intelligently apportioned into one or more rows and columns)
or, with two constructor arguments, the number of columns followed
by the number of rows.
With the I{filePath} keyword, you can specify the file path of a
PNG file for me to create or overwrite with each call to L{show}.
You can set the I{width} and I{height} of the Figure with
constructor keywords, and (read-only) access them via my
properties of the same names. Or set my I{figSize} attribute (in a
subclass or with that constructor keyword) to a 2-sequence with
figure width and height. The default width and height is just shy
of the entire monitor size.
The dimensions are in inches, converted to pixels at 100 DPI,
unless they are both integers and either of them exceeds 75 (which
would equate to a huge 7,500 pixels). In that case, they are
considered to specify the pixel dimensions directly.
Use the "Agg" backend by supplying the constructor keyword
I{useAgg}. This works better for plotting to an image file, and is
selected automatically if you supply a I{filePath} to the
constructor. Be aware that, once selected, that backend will be
used for all instances of me. If you're using the "Agg" backend,
you should specify it the first time an instance is constructed.
Setting the I{verbose} keyword C{True} puts out a bit of info
about annotator positioning. Not for regular use.
Any other keywords you supply to the constructor are supplied to
the underlying Matplotlib plotting call for all
subplots.
Keep the API for L{OptsBase} handy, and maybe a copy of the
U{source<http://edsuom.com/yampex/yampex.plot.py>}, to see all the
plotting options you can set.
@ivar dims: A dict (actually, a subclass of L{Dims}) of sub-dicts
of the dimensions of various text objects, keyed first by
subplot index then the object name.
@ivar Nsp: The number of subplots defined thus far defined with
calls to my instance.
"""
ph = PlotterHolder()
fc = None
DPI = 100 # Don't change this, for reference only
_settings = {'title', 'xlabel', 'ylabel'}
figSize = None
# Flag to indicate if using Agg rendererer (for generating PNG files)
usingAgg = False
# Show warnings? (Not for regular use.)
verbose = False
@classmethod
def setupClass(cls, useAgg=False):
"""
Called by each instance of me during instantiation. Sets a
class-wide Matplotlib pyplot import the first time it's
called.
If any instance of me is using the Agg renderer, all instances
will.
"""
mpl = importlib.import_module("matplotlib")
if useAgg and not cls.usingAgg:
mpl.use('Agg')
cls.usingAgg = True
else:
try:
raise Exception(
"Neither GTK3Agg nor PyQt5Agg actually work consistently")
mpl.use('GTK3Agg')
except:
try:
mpl.use('tkagg')
except:
print("WARNING: Neither GTK3Agg nor tkagg available!")
if not getattr(cls, 'plt', None):
cls.plt = importlib.import_module("matplotlib.pyplot")
@classmethod
def showAll(cls):
"""
Calls L{show} for the figures generated by all instances of me.
"""
OK = cls.ph.doForAll('show', noShow=True)
if OK: cls.plt.show()
cls.ph.doForAll('clear')
# They should all have removed themselves now, but what the
# heck, clear it anyways
cls.ph.removeAll()
def __init__(self, *args, **kw):
"""
Constructor possibilities (not including keywords, except I{Nc}):
C{Plotter(Nc, Nr)}: Specify I{Nc} columns and I{Nr} rows.
C{Plotter(N)}: Specify up to I{N} subplots in optimal
arrangement of columns and rows.
C{Plotter(N, Nc=x)}: Specify up to I{N} columns subplots with
I{x} columns.
C{Plotter(Nc, Nr, V)}: Specify I{Nc} columns and I{Nr} rows,
with container object I{V}.
C{Plotter(Nc, Nr, V)}: Specify up to I{N} subplots in optimal
arrangement of columns and rows, with container object I{V}.
C{Plotter(N, V, Nc=x)}: Specify up to I{N} columns subplots
with I{x} columns, with container object I{V}.
@keyword filePath: Specify the path of a PNG file to be
created instead of a plot window being opened. (Implies
I{useAgg}.)
@keyword useAgg: Set C{True} to use the "Agg" backend, which
works better for creating image files. If you're going to
specify it for multiple plot images, do so the first time
an instance of me is constructed.
@keyword figSize: Set to a 2-sequence with figure width and
height if not using the default, which is just shy of your
entire monitor size. Dimensions are in inches, converted
to pixels at 100 DPI, unless both are integers and either
exceeds 75. Then they are considered to specify the pixel
dimensions directly.
@keyword width: Specify the figure width part of I{figSize}.
@keyword height: Specify the figure height part of I{figSize}.
@keyword h2: A single index, or a sequence or set containing
one or more indices, of any rows (starting with 0 for the
top row) that have twice the normal height. If an invalid
index is included, an exception will be raised.
@keyword w2: A single index, or a sequence or set containing
one or more indices, of any columns (starting with 0 for
the left column) that have twice the normal width. If an
invalid index is included, an exception will be raised.
"""
args, kw, N, self.Nc, self.Nr = self.parseArgs(*args, **kw)
self.V = args[0] if args else None
self.opts = Opts()
self.filePath = kw.pop('filePath', None)
if 'verbose' in kw: self.verbose = kw.pop('verbose')
useAgg = bool(self.filePath) or kw.pop('useAgg', False)
self.setupClass(useAgg=useAgg)
figSize = kw.pop('figSize', self.figSize)
if figSize is None:
if useAgg or screeninfo is None:
figSize = [10.0, 7.0]
else:
si = screeninfo.screeninfo.get_monitors()[0]
figSize = [
float(x)/self.DPI for x in (si.width-80, si.height-80)]
width = kw.pop('width', None)
if width: figSize[0] = width
height = kw.pop('height', None)
if height: figSize[1] = height
figSize = self._maybePixels(figSize)
self.fig = self.plt.figure(figsize=figSize)
self.figSize = figSize
self.sp = Subplotter(
self, N, self.Nc, self.Nr, kw.pop('h2', []), kw.pop('w2', []))
# The ID is an integer, not a reference to anything
self.ID = self.ph.add(self)
self.kw = kw
self.dims = Dims()
self.xlabels = {}
self.annotators = {}
self.adj = Adjuster(self)
self.reset()
@staticmethod
def parseArgs(*args, **kw):
"""
Parse the supplied I{args} and I{kw} for a constructor call.
Returns a 5-tuple with a revised args list and kw dict, the
number of subplots, the number of columns, and the number of
rows.
"""
N = args[0]
args = list(args[1:])
Nc = kw.pop('Nc', None)
if args and isinstance(args[0], int):
# Nc, Nr specified
if Nc:
raise ValueError(
"You can't specify Nc as both a second arg and keyword")
Nc = N
Nr = args.pop(0)
N = Nc*Nr
else:
# N specified
Nc = Nc if Nc else 3 if N > 6 else 2 if N > 3 else 1
Nr = int(np.ceil(float(N)/Nc))
return args, kw, N, Nc, Nr
def reset(self):
"""
Clears everything out to start fresh.
"""
self.dims.clear()
self.xlabels.clear()
self.annotators.clear()
self._figTitle = None
self.tbmTitle = None
self._isSubplot = False
self._universal_xlabel = False
self._plotter = None
self.Nsp = 0
def __del__(self):
"""
Safely ensures that I am removed from the class-wide I{ph}
instance of L{PlotterHolder}.
"""
# Only an integer is passed to the call
self.ph.remove(self.ID)
# No new references were created, nothing retained
def _maybePixels(self, figSize):
"""
Considers the supplied I{figSize} to be in pixels if both its
elements are integers and at least one of them exceeds 75. In
that case, scales it down by DPI.
Returns the figSize in inches.
"""
bigDim = False
newFigSize = []
for dim in figSize:
if not isinstance(dim, int):
# Not both integers, use original
return figSize
if dim > 75: bigDim = True
# Convert from (presumed) pixels to Matplotlib's stupid inches
newFigSize.append(float(dim)/self.DPI)
# Use the converted dims unless neither was > 75
return newFigSize if bigDim else figSize
@property
def width(self):
"""
Figure width (inches).
"""
return self.fig.get_figwidth()
@property
def height(self):
"""
Figure height (inches).
"""
return self.fig.get_figheight()
def __getattr__(self, name):
"""
You can access plotting methods and a given subplot's plotting
options as attributes.
If you request a plotting method, you'll get an instance of me
with my I{_plotter} method set to I{name} first.
"""
if name in PLOTTER_NAMES:
self._plotter = name
return self
if name in self.opts:
return self.opts[name]
raise AttributeError(sub(
"No plotting option or attribute '{}'", name))
def __enter__(self):
"""
Upon an outer context entry, sets up the first subplot with
cleared axes, preserves a copy of my global options, and
returns a reference to myself as a subplotting tool.
"""
# TODO: Allow my instance to be context-called again
#self.reset()
self.sp.setup()
self._isSubplot = True
self.opts.newLocal()
return self
def __exit__(self, *args):
"""
Upon completion of context, turns minor ticks and grid on if
enabled for this subplot's axis, restores global (all
subplots) options.
If the Agg rendererer is not being used (for generating PNG
files), also sets a hook to adjust the subplot spacings and
annotation positions upon window resizing.
The args are just placeholders for the three args that
C{contextmanager} supplies at the end of context: I{exc_type},
I{exc_val}, I{exc_tb}. (None are useful here.)
@see: L{_doPlots}.
"""
# Do the last (and perhaps only) call's plotting
self._doPlots()
self._isSubplot = False
self.opts.goGlobal()
if not self.usingAgg:
self.fig.canvas.mpl_connect('resize_event', self.subplots_adjust)
def start(self):
"""
An alternative to the context-manager way of using me. Just call
this method and a reference to myself as a subplotting tool
will be returned.
Call L{done} when finished, which is the same thing as exiting
my subplotting context.
"""
if self._isSubplot:
raise Exception("You are already in a subplotting context!")
return self.__enter__()
def done(self):
"""
Call this after a call to L{start} when done plotting. This is the
alternative to the context-manager way of using me.
B{Note}: If you don't call this to close out a plotting
session with the alternative method, the last subplot will not
get drawn!
@see: L{start}, which gets called to start the
alternative-method plotting session.
"""
if not self._isSubplot:
raise Exception("You are not in a subplotting context!")
self.__exit__()
def subplots_adjust(self, *args):
"""
Adjusts spacings.
"""
dimThing = args[0] if args else self.fig.get_window_extent()
fWidth, fHeight = [getattr(dimThing, x) for x in ('width', 'height')]
self.adj.updateFigSize(fWidth, fHeight)
if self._figTitle:
kw = {
'm': 10,
'fontsize': self.fontsize('title', 14),
'alpha': 1.0,
'fDims': (fWidth, fHeight),
}
ax = self.fig.get_axes()[0]
if self.tbmTitle: self.tbmTitle.remove()
self.tbmTitle = TextBoxMaker(self.fig, **kw)("N", self._figTitle)
titleObj = self.tbmTitle.tList[0]
else: self.tbmTitle = titleObj = None
kw = self.adj(self._universal_xlabel, titleObj)
try:
self.fig.subplots_adjust(**kw)
except ValueError as e:
if self.verbose:
print((sub(
"WARNING: ValueError '{}' doing subplots_adjust({})",
e.message, ", ".join(
[sub("{}={}", x, kw[x]) for x in kw]))))
self.updateAnnotations()
def updateAnnotations(self, annotator=None):
"""
Updates the positions of all annotations in an already-drawn plot.
When L{PlotHelper} calls this, it will supply the annotator
for its subplot.
"""
plt = self.plt
updated = False
if annotator is None:
for annotator in self.annotators.values():
if annotator.update():
updated = True
elif annotator.update(): updated = True
if updated:
# This raises a warning with newer matplotlib
#plt.pause(0.0001)
plt.draw()
def _doPlots(self):
"""
This gets called by L{__call__} at the beginning of each call to
my subplot-context instance, and by L{__exit__} when subplot
context ends, to do all the plotting for the previous subplot.
Adds minor ticks and a grid, depending on the subplot-specific
options. Then calls L{Opts.newLocal} on my I{opts} to create a
new set of local options.
"""
ax = self.sp.ax
if ax: ax.helper.doPlots()
# Setting calls now use new local options
self.opts.newLocal()
def show(self, windowTitle=None, fh=None, filePath=None, noShow=False):
"""
Call this to show the figure with suplots after the last call to
my instance.
If I have a non-C{None} I{fc} attribute (which must reference
an instance of Qt's C{FigureCanvas}, then the FigureCanvas is
drawn instead of PyPlot doing a window show.
You can supply an open file-like object for PNG data to be
written to (instead of a Matplotlib Figure being displayed)
with the I{fh} keyword. (It's up to you to close the file
object.)
Or, with the I{filePath} keyword, you can specify the file
path of a PNG file for me to create or overwrite. (That
overrides any I{filePath} you set in the constructor.)
"""
try:
self.fig.tight_layout()
except ValueError as e:
if self.verbose:
proto = "WARNING: ValueError '{}' doing tight_layout "+\
"on {:.5g} x {:.5g} figure"
print((sub(proto, e.message, self.width, self.height)))
self.subplots_adjust()
# Calling plt.draw massively slows things down when generating
# plot images on Rpi. And without it, the (un-annotated) plot
# still updates!
if False and self.annotators:
# This is not actually run, see above comment
self.plt.draw()
for annotator in list(self.annotators.values()):
if self.verbose: annotator.setVerbose()
annotator.update()
if fh is None:
if not filePath:
filePath = self.filePath
if filePath:
fh = open(filePath, 'wb+')
if fh is None:
self.plt.draw()
if windowTitle: self.fig.canvas.set_window_title(windowTitle)
if self.fc is not None: self.fc.draw()
elif not noShow: self.plt.show()
else:
self.fig.savefig(fh, format='png')
self.plt.close()
if filePath is not None:
# Only close a file handle I opened myself
fh.close()
if not noShow: self.clear()
def clear(self):
"""
Clears my figure with all annotators and artist
dimensions. Removes my ID from the class-wide
L{PlotterHolder}.
"""
try:
# This causes stupid errors with tkagg, so just wrap it in
# try-except for now
self.fig.clear()
except: pass
self.annotators.clear()
self.dims.clear()
self.ph.remove(self.ID)
def xBounds(self, *args, **kw):
"""
See L{Subplotter.xBounds}.
"""
self.sp.xBounds(*args, **kw)
def yBounds(self, *args, **kw):
"""
See L{Subplotter.yBounds}.
"""
self.sp.yBounds(*args, **kw)
def fontsize(self, name, default=None):
return self.opts['fontsizes'].get(name, default)
def doKeywords(self, kVector, kw):
"""
Applies line style/marker/color settings as keywords for this
vector, except for options already set with keywords.
Then applies plot keywords set via the set_plotKeyword call
and then, with higher priority, those set via the constructor,
if they don't conflict with explicitly set keywords to this
call which takes highest priority.
Returns the new kw dict.
"""
kw = self.opts.kwModified(kVector, kw)
for thisDict in (self.kw, self.plotKeywords):
for name in thisDict:
if name not in kw:
kw[name] = thisDict[name]
return kw
def doSettings(self, k):
"""
Does C{set_XXX} calls on the C{Axes} object for the subplot at
index I{k}.
"""
def bbAdd(textObj):
dims = self.adj.tsc.dims(textObj)
self.dims.setDims(k, name, dims)
for name in self._settings:
value = self.opts[name]
if not value: continue
fontsize = self.fontsize(name, None)
kw = {'size':fontsize} if fontsize else {}
bbAdd(self.sp.set_(name, value, **kw))
if name == 'xlabel':
self.xlabels[k] = value
continue
settings = self.opts['settings']
for name in settings:
bbAdd(self.sp.set_(name, settings[name]))
def __call__(self, *args, **kw):
"""
In the next (perhaps first) subplot, or one whose index is
specified with keyword I{k}, plots the second supplied vector
(and any further ones) versus the first.
If you supply a container object that houses vectors and
provides access to them as items as the first argument, you
can supply vector names instead of the vectors themselves. The
container object must evaluate C{b in a} as C{True} if it
contains a vector with I{b}, and must return the vector with
C{a[b]}.
Many options can be set via the methods in L{OptsBase},
including a title, a list of plot markers and linestyles, and
a list of legend entries for the plots with those keywords.
Set I{useLabels} to C{True} to have annotation labels pointing
to each plot line instead of a legend, with text taken from
the legend list.
You can override my default plotter by specifying the name of
another one with the I{plotter} keyword, e.g.,
C{plotter="step"}. But the usual way to do that is to call the
corresponding method of my instance, e.g., C{sp.step(X, Y)}.
Any other keywords you supply to this call are supplied to the
underlying Matplotlib plotting call. (B{NOTE:} This is a
change from previous versions of Yampex where keywords to this
method were used to C{set_X} the axes, e.g., C{ylabel="foo"}
results in a C{set_ylabel("foo")} command to the C{axes}
object, for this subplot only. Use the new L{OptsBase.set}
command instead.)
Returns a L{SpecialAx} wrapper object for the C{Axes} object
created for the plot.
If you want to do everything with the next subplot on your
own, bit by bit, and only want a reference to its C{Axes}
object (still with special treatment via L{SpecialAx}) just
call this with no args.
For low-level Matplotlib operations, you can access the
underlying C{Axes} object via the returned L{SpecialAx}
object's I{ax} attribute. But none of its special features
will apply to what you do that way.
@keyword k: Set this to the integer index of the subplot you
want the supplied vectors plotted in if not in sequence.
@see: L{_doPlots}.
"""
# Do plotting for the previous call (if any)
self._doPlots()
if 'plotter' not in kw:
plotter = self._plotter
self._plotter = None
if plotter: kw.setdefault('plotter', plotter)
k = kw.pop('k', None)
ax = self.sp[k]
ax.helper.addCall(args, kw)
self.Nsp += 1
return ax
| (*args, **kw) |
28,901 | yampex.plot | __call__ |
In the next (perhaps first) subplot, or one whose index is
specified with keyword I{k}, plots the second supplied vector
(and any further ones) versus the first.
If you supply a container object that houses vectors and
provides access to them as items as the first argument, you
can supply vector names instead of the vectors themselves. The
container object must evaluate C{b in a} as C{True} if it
contains a vector with I{b}, and must return the vector with
C{a[b]}.
Many options can be set via the methods in L{OptsBase},
including a title, a list of plot markers and linestyles, and
a list of legend entries for the plots with those keywords.
Set I{useLabels} to C{True} to have annotation labels pointing
to each plot line instead of a legend, with text taken from
the legend list.
You can override my default plotter by specifying the name of
another one with the I{plotter} keyword, e.g.,
C{plotter="step"}. But the usual way to do that is to call the
corresponding method of my instance, e.g., C{sp.step(X, Y)}.
Any other keywords you supply to this call are supplied to the
underlying Matplotlib plotting call. (B{NOTE:} This is a
change from previous versions of Yampex where keywords to this
method were used to C{set_X} the axes, e.g., C{ylabel="foo"}
results in a C{set_ylabel("foo")} command to the C{axes}
object, for this subplot only. Use the new L{OptsBase.set}
command instead.)
Returns a L{SpecialAx} wrapper object for the C{Axes} object
created for the plot.
If you want to do everything with the next subplot on your
own, bit by bit, and only want a reference to its C{Axes}
object (still with special treatment via L{SpecialAx}) just
call this with no args.
For low-level Matplotlib operations, you can access the
underlying C{Axes} object via the returned L{SpecialAx}
object's I{ax} attribute. But none of its special features
will apply to what you do that way.
@keyword k: Set this to the integer index of the subplot you
want the supplied vectors plotted in if not in sequence.
@see: L{_doPlots}.
| def __call__(self, *args, **kw):
"""
In the next (perhaps first) subplot, or one whose index is
specified with keyword I{k}, plots the second supplied vector
(and any further ones) versus the first.
If you supply a container object that houses vectors and
provides access to them as items as the first argument, you
can supply vector names instead of the vectors themselves. The
container object must evaluate C{b in a} as C{True} if it
contains a vector with I{b}, and must return the vector with
C{a[b]}.
Many options can be set via the methods in L{OptsBase},
including a title, a list of plot markers and linestyles, and
a list of legend entries for the plots with those keywords.
Set I{useLabels} to C{True} to have annotation labels pointing
to each plot line instead of a legend, with text taken from
the legend list.
You can override my default plotter by specifying the name of
another one with the I{plotter} keyword, e.g.,
C{plotter="step"}. But the usual way to do that is to call the
corresponding method of my instance, e.g., C{sp.step(X, Y)}.
Any other keywords you supply to this call are supplied to the
underlying Matplotlib plotting call. (B{NOTE:} This is a
change from previous versions of Yampex where keywords to this
method were used to C{set_X} the axes, e.g., C{ylabel="foo"}
results in a C{set_ylabel("foo")} command to the C{axes}
object, for this subplot only. Use the new L{OptsBase.set}
command instead.)
Returns a L{SpecialAx} wrapper object for the C{Axes} object
created for the plot.
If you want to do everything with the next subplot on your
own, bit by bit, and only want a reference to its C{Axes}
object (still with special treatment via L{SpecialAx}) just
call this with no args.
For low-level Matplotlib operations, you can access the
underlying C{Axes} object via the returned L{SpecialAx}
object's I{ax} attribute. But none of its special features
will apply to what you do that way.
@keyword k: Set this to the integer index of the subplot you
want the supplied vectors plotted in if not in sequence.
@see: L{_doPlots}.
"""
# Do plotting for the previous call (if any)
self._doPlots()
if 'plotter' not in kw:
plotter = self._plotter
self._plotter = None
if plotter: kw.setdefault('plotter', plotter)
k = kw.pop('k', None)
ax = self.sp[k]
ax.helper.addCall(args, kw)
self.Nsp += 1
return ax
| (self, *args, **kw) |
28,902 | yampex.plot | __del__ |
Safely ensures that I am removed from the class-wide I{ph}
instance of L{PlotterHolder}.
| def __del__(self):
"""
Safely ensures that I am removed from the class-wide I{ph}
instance of L{PlotterHolder}.
"""
# Only an integer is passed to the call
self.ph.remove(self.ID)
# No new references were created, nothing retained
| (self) |
28,903 | yampex.plot | __enter__ |
Upon an outer context entry, sets up the first subplot with
cleared axes, preserves a copy of my global options, and
returns a reference to myself as a subplotting tool.
| def __enter__(self):
"""
Upon an outer context entry, sets up the first subplot with
cleared axes, preserves a copy of my global options, and
returns a reference to myself as a subplotting tool.
"""
# TODO: Allow my instance to be context-called again
#self.reset()
self.sp.setup()
self._isSubplot = True
self.opts.newLocal()
return self
| (self) |
28,904 | yampex.plot | __exit__ |
Upon completion of context, turns minor ticks and grid on if
enabled for this subplot's axis, restores global (all
subplots) options.
If the Agg rendererer is not being used (for generating PNG
files), also sets a hook to adjust the subplot spacings and
annotation positions upon window resizing.
The args are just placeholders for the three args that
C{contextmanager} supplies at the end of context: I{exc_type},
I{exc_val}, I{exc_tb}. (None are useful here.)
@see: L{_doPlots}.
| def __exit__(self, *args):
"""
Upon completion of context, turns minor ticks and grid on if
enabled for this subplot's axis, restores global (all
subplots) options.
If the Agg rendererer is not being used (for generating PNG
files), also sets a hook to adjust the subplot spacings and
annotation positions upon window resizing.
The args are just placeholders for the three args that
C{contextmanager} supplies at the end of context: I{exc_type},
I{exc_val}, I{exc_tb}. (None are useful here.)
@see: L{_doPlots}.
"""
# Do the last (and perhaps only) call's plotting
self._doPlots()
self._isSubplot = False
self.opts.goGlobal()
if not self.usingAgg:
self.fig.canvas.mpl_connect('resize_event', self.subplots_adjust)
| (self, *args) |
28,905 | yampex.plot | __getattr__ |
You can access plotting methods and a given subplot's plotting
options as attributes.
If you request a plotting method, you'll get an instance of me
with my I{_plotter} method set to I{name} first.
| def __getattr__(self, name):
"""
You can access plotting methods and a given subplot's plotting
options as attributes.
If you request a plotting method, you'll get an instance of me
with my I{_plotter} method set to I{name} first.
"""
if name in PLOTTER_NAMES:
self._plotter = name
return self
if name in self.opts:
return self.opts[name]
raise AttributeError(sub(
"No plotting option or attribute '{}'", name))
| (self, name) |
28,906 | yampex.plot | __init__ |
Constructor possibilities (not including keywords, except I{Nc}):
C{Plotter(Nc, Nr)}: Specify I{Nc} columns and I{Nr} rows.
C{Plotter(N)}: Specify up to I{N} subplots in optimal
arrangement of columns and rows.
C{Plotter(N, Nc=x)}: Specify up to I{N} columns subplots with
I{x} columns.
C{Plotter(Nc, Nr, V)}: Specify I{Nc} columns and I{Nr} rows,
with container object I{V}.
C{Plotter(Nc, Nr, V)}: Specify up to I{N} subplots in optimal
arrangement of columns and rows, with container object I{V}.
C{Plotter(N, V, Nc=x)}: Specify up to I{N} columns subplots
with I{x} columns, with container object I{V}.
@keyword filePath: Specify the path of a PNG file to be
created instead of a plot window being opened. (Implies
I{useAgg}.)
@keyword useAgg: Set C{True} to use the "Agg" backend, which
works better for creating image files. If you're going to
specify it for multiple plot images, do so the first time
an instance of me is constructed.
@keyword figSize: Set to a 2-sequence with figure width and
height if not using the default, which is just shy of your
entire monitor size. Dimensions are in inches, converted
to pixels at 100 DPI, unless both are integers and either
exceeds 75. Then they are considered to specify the pixel
dimensions directly.
@keyword width: Specify the figure width part of I{figSize}.
@keyword height: Specify the figure height part of I{figSize}.
@keyword h2: A single index, or a sequence or set containing
one or more indices, of any rows (starting with 0 for the
top row) that have twice the normal height. If an invalid
index is included, an exception will be raised.
@keyword w2: A single index, or a sequence or set containing
one or more indices, of any columns (starting with 0 for
the left column) that have twice the normal width. If an
invalid index is included, an exception will be raised.
| def __init__(self, *args, **kw):
"""
Constructor possibilities (not including keywords, except I{Nc}):
C{Plotter(Nc, Nr)}: Specify I{Nc} columns and I{Nr} rows.
C{Plotter(N)}: Specify up to I{N} subplots in optimal
arrangement of columns and rows.
C{Plotter(N, Nc=x)}: Specify up to I{N} columns subplots with
I{x} columns.
C{Plotter(Nc, Nr, V)}: Specify I{Nc} columns and I{Nr} rows,
with container object I{V}.
C{Plotter(Nc, Nr, V)}: Specify up to I{N} subplots in optimal
arrangement of columns and rows, with container object I{V}.
C{Plotter(N, V, Nc=x)}: Specify up to I{N} columns subplots
with I{x} columns, with container object I{V}.
@keyword filePath: Specify the path of a PNG file to be
created instead of a plot window being opened. (Implies
I{useAgg}.)
@keyword useAgg: Set C{True} to use the "Agg" backend, which
works better for creating image files. If you're going to
specify it for multiple plot images, do so the first time
an instance of me is constructed.
@keyword figSize: Set to a 2-sequence with figure width and
height if not using the default, which is just shy of your
entire monitor size. Dimensions are in inches, converted
to pixels at 100 DPI, unless both are integers and either
exceeds 75. Then they are considered to specify the pixel
dimensions directly.
@keyword width: Specify the figure width part of I{figSize}.
@keyword height: Specify the figure height part of I{figSize}.
@keyword h2: A single index, or a sequence or set containing
one or more indices, of any rows (starting with 0 for the
top row) that have twice the normal height. If an invalid
index is included, an exception will be raised.
@keyword w2: A single index, or a sequence or set containing
one or more indices, of any columns (starting with 0 for
the left column) that have twice the normal width. If an
invalid index is included, an exception will be raised.
"""
args, kw, N, self.Nc, self.Nr = self.parseArgs(*args, **kw)
self.V = args[0] if args else None
self.opts = Opts()
self.filePath = kw.pop('filePath', None)
if 'verbose' in kw: self.verbose = kw.pop('verbose')
useAgg = bool(self.filePath) or kw.pop('useAgg', False)
self.setupClass(useAgg=useAgg)
figSize = kw.pop('figSize', self.figSize)
if figSize is None:
if useAgg or screeninfo is None:
figSize = [10.0, 7.0]
else:
si = screeninfo.screeninfo.get_monitors()[0]
figSize = [
float(x)/self.DPI for x in (si.width-80, si.height-80)]
width = kw.pop('width', None)
if width: figSize[0] = width
height = kw.pop('height', None)
if height: figSize[1] = height
figSize = self._maybePixels(figSize)
self.fig = self.plt.figure(figsize=figSize)
self.figSize = figSize
self.sp = Subplotter(
self, N, self.Nc, self.Nr, kw.pop('h2', []), kw.pop('w2', []))
# The ID is an integer, not a reference to anything
self.ID = self.ph.add(self)
self.kw = kw
self.dims = Dims()
self.xlabels = {}
self.annotators = {}
self.adj = Adjuster(self)
self.reset()
| (self, *args, **kw) |
28,907 | yampex.plot | _doPlots |
This gets called by L{__call__} at the beginning of each call to
my subplot-context instance, and by L{__exit__} when subplot
context ends, to do all the plotting for the previous subplot.
Adds minor ticks and a grid, depending on the subplot-specific
options. Then calls L{Opts.newLocal} on my I{opts} to create a
new set of local options.
| def _doPlots(self):
"""
This gets called by L{__call__} at the beginning of each call to
my subplot-context instance, and by L{__exit__} when subplot
context ends, to do all the plotting for the previous subplot.
Adds minor ticks and a grid, depending on the subplot-specific
options. Then calls L{Opts.newLocal} on my I{opts} to create a
new set of local options.
"""
ax = self.sp.ax
if ax: ax.helper.doPlots()
# Setting calls now use new local options
self.opts.newLocal()
| (self) |
28,908 | yampex.plot | _maybePixels |
Considers the supplied I{figSize} to be in pixels if both its
elements are integers and at least one of them exceeds 75. In
that case, scales it down by DPI.
Returns the figSize in inches.
| def _maybePixels(self, figSize):
"""
Considers the supplied I{figSize} to be in pixels if both its
elements are integers and at least one of them exceeds 75. In
that case, scales it down by DPI.
Returns the figSize in inches.
"""
bigDim = False
newFigSize = []
for dim in figSize:
if not isinstance(dim, int):
# Not both integers, use original
return figSize
if dim > 75: bigDim = True
# Convert from (presumed) pixels to Matplotlib's stupid inches
newFigSize.append(float(dim)/self.DPI)
# Use the converted dims unless neither was > 75
return newFigSize if bigDim else figSize
| (self, figSize) |
28,909 | yampex.options | add_annotation |
Adds the text supplied after index I{k} at an annotation of the
plotted vector.
If there is more than one vector being plotted within the same
subplot, you can have the annotation refer to a vector other
than the first one by setting the keyword I{kVector} to its
non-zero index.
The annotation points to the point at index I{k} of the
plotted vector, unless I{k} is a float. In that case, it
points to the point where the vector is closest to that float
value.
You may include a text prototype with format-substitution args
following it, or just supply the final text string with no
further arguments. If you supply just an integer or float
value with no further arguments, it will be formatted
reasonably.
You can set the annotation to the first y-axis value that
crosses a float value of I{k} by setting I{y} C{True}.
@see: L{clear_annotations}.
| def add_annotation(self, k, proto, *args, **kw):
"""
Adds the text supplied after index I{k} at an annotation of the
plotted vector.
If there is more than one vector being plotted within the same
subplot, you can have the annotation refer to a vector other
than the first one by setting the keyword I{kVector} to its
non-zero index.
The annotation points to the point at index I{k} of the
plotted vector, unless I{k} is a float. In that case, it
points to the point where the vector is closest to that float
value.
You may include a text prototype with format-substitution args
following it, or just supply the final text string with no
further arguments. If you supply just an integer or float
value with no further arguments, it will be formatted
reasonably.
You can set the annotation to the first y-axis value that
crosses a float value of I{k} by setting I{y} C{True}.
@see: L{clear_annotations}.
"""
kVector = None
if args:
if "{" not in proto:
# Called with kVector as a third argument, per API of
# commit 15c49b and earlier
text = proto
kVector = args[0]
else: text = sub(proto, *args)
elif isinstance(proto, int):
text = sub("{:+d}", proto)
elif isinstance(proto, float):
text = sub("{:+.4g}", proto)
else: text = proto
if kVector is None:
kVector = kw.get('kVector', 0)
y = kw.get('y', False)
self.opts['annotations'].append((k, text, kVector, y))
| (self, k, proto, *args, **kw) |
28,910 | yampex.options | add_axvline |
Adds a vertical dashed line at the data point with integer index
I{k}. You can use negative indices, e.g., -1 for the last data
point.
To place the dashed line at (or at least near) an x value, use
a float for I{k}.
| def add_axvline(self, k):
"""
Adds a vertical dashed line at the data point with integer index
I{k}. You can use negative indices, e.g., -1 for the last data
point.
To place the dashed line at (or at least near) an x value, use
a float for I{k}.
"""
self.opts['axvlines'].append(k)
| (self, k) |
28,911 | yampex.options | add_color |
Appends the supplied line style character to the list of colors
being used.
The first and possibly only color in the list applies to the
first vector plotted within a given subplot. If there are
additional vectors being plotted within a given subplot (three
or more arguments supplied when calling the L{Plotter} object,
more than the number of colors that have been added to the
list, then the colors rotate back to the first one in the
list.
If you never call this and don't set your own list with a call
to L{set_colors}, a default color list is used.
If no color code or C{None} is supplied, reverts to the
default color scheme.
| def add_color(self, x=None):
"""
Appends the supplied line style character to the list of colors
being used.
The first and possibly only color in the list applies to the
first vector plotted within a given subplot. If there are
additional vectors being plotted within a given subplot (three
or more arguments supplied when calling the L{Plotter} object,
more than the number of colors that have been added to the
list, then the colors rotate back to the first one in the
list.
If you never call this and don't set your own list with a call
to L{set_colors}, a default color list is used.
If no color code or C{None} is supplied, reverts to the
default color scheme.
"""
if x is None:
self.opts['colors'] = []
return
self.opts['colors'].append(x)
| (self, x=None) |
28,912 | yampex.options | add_legend |
Adds the supplied format-substituted text to the list of legend
entries.
You may include a text I{proto}type with format-substitution
I{args}, or just supply the final text string with no further
arguments.
@see: L{clear_legend}, L{set_legend}.
| def add_legend(self, proto, *args):
"""
Adds the supplied format-substituted text to the list of legend
entries.
You may include a text I{proto}type with format-substitution
I{args}, or just supply the final text string with no further
arguments.
@see: L{clear_legend}, L{set_legend}.
"""
text = sub(proto, *args)
self.opts['legend'].append(text)
| (self, proto, *args) |
28,913 | yampex.options | add_line |
Appends the supplied line style string(s) to my list of line
styles being used.
The first and possibly only line style in the list applies to
the first vector plotted within a given subplot. If there is
an additional vector being plotted within a given subplot
(three or more arguments supplied when calling the L{Plotter}
object, and more than one line style has been added to the
list, then the second line style in the list is used for that
second vector plot line. Otherwise, the first (only) line
style in the list is used for the second plot line as well.
If no line style character or C{None} is supplied, clears the
list of line styles.
@keyword width: A I{width} for the line(s). If you want
separate line widths for different lines, call this
repeatedly with each seperate line style and width. (You
can make the width a second argument of a 2-arg call,
after a single line style string.)
| def add_line(self, *args, **kw):
"""
Appends the supplied line style string(s) to my list of line
styles being used.
The first and possibly only line style in the list applies to
the first vector plotted within a given subplot. If there is
an additional vector being plotted within a given subplot
(three or more arguments supplied when calling the L{Plotter}
object, and more than one line style has been added to the
list, then the second line style in the list is used for that
second vector plot line. Otherwise, the first (only) line
style in the list is used for the second plot line as well.
If no line style character or C{None} is supplied, clears the
list of line styles.
@keyword width: A I{width} for the line(s). If you want
separate line widths for different lines, call this
repeatedly with each seperate line style and width. (You
can make the width a second argument of a 2-arg call,
after a single line style string.)
"""
if not args or args[0] is None:
self.opts['linestyles'] = []
return
if len(args) == 2 and not isinstance(args[1], str):
width = args[1]
args = [args[0]]
else: width = kw.get('width', None)
for x in args:
self.opts['linestyles'].append((x, width))
| (self, *args, **kw) |
28,914 | yampex.options | add_lines |
Alias for L{add_line}.
| def add_lines(self, *args, **kw):
"""
Alias for L{add_line}.
"""
return self.add_line(*args, **kw)
| (self, *args, **kw) |
28,915 | yampex.options | add_marker |
Appends the supplied marker style character to the list of markers
being used.
The first and possibly only marker in the list applies to the
first vector plotted within a given subplot. If there is an
additional vector being plotted within a given subplot (three
or more arguments supplied when calling the L{Plotter} object,
and more than one marker has been added to the list, then the
second marker in the list is used for that second vector plot
line. Otherwise, the first (only) marker in the list is used
for the second plot line as well.
You can specify a I{size} for the marker as well.
| def add_marker(self, x, size=None):
"""
Appends the supplied marker style character to the list of markers
being used.
The first and possibly only marker in the list applies to the
first vector plotted within a given subplot. If there is an
additional vector being plotted within a given subplot (three
or more arguments supplied when calling the L{Plotter} object,
and more than one marker has been added to the list, then the
second marker in the list is used for that second vector plot
line. Otherwise, the first (only) marker in the list is used
for the second plot line as well.
You can specify a I{size} for the marker as well.
"""
self.opts['markers'].append((x, size))
| (self, x, size=None) |
28,916 | yampex.options | add_plotKeyword |
Add a keyword to the underlying Matplotlib plotting call.
@see: L{clear_plotKeywords}.
| def add_plotKeyword(self, name, value):
"""
Add a keyword to the underlying Matplotlib plotting call.
@see: L{clear_plotKeywords}.
"""
self.opts['plotKeywords'][name] = value
| (self, name, value) |
28,917 | yampex.options | add_textBox |
Adds a text box to the specified I{location} of the subplot.
Here are the locations (you can use the integer instead of the
abbreviation if you want), along with their text alignments:
1. "NE": right, top.
2. "E": right, middle.
3. "SE": right, bottom.
4. "S": middle, bottom.
5. "SW": left, bottom.
6. "W": left, middle.
7. "NW": left, top.
8. "N": middle, top.
9. "M": middle of plot.
If there's already a text box at the specified location, a
line will be added to it.
You may include a text I{proto}type with format-substitution
I{args}, or just supply the final text string with no further
arguments.
@see: L{clear_textBoxes}.
| def add_textBox(self, location, proto, *args):
"""
Adds a text box to the specified I{location} of the subplot.
Here are the locations (you can use the integer instead of the
abbreviation if you want), along with their text alignments:
1. "NE": right, top.
2. "E": right, middle.
3. "SE": right, bottom.
4. "S": middle, bottom.
5. "SW": left, bottom.
6. "W": left, middle.
7. "NW": left, top.
8. "N": middle, top.
9. "M": middle of plot.
If there's already a text box at the specified location, a
line will be added to it.
You may include a text I{proto}type with format-substitution
I{args}, or just supply the final text string with no further
arguments.
@see: L{clear_textBoxes}.
"""
text = sub(proto, *args)
prevText = self.opts['textBoxes'].get(location, None)
if prevText:
text = prevText + "\n" + text
self.opts['textBoxes'][location] = text.strip()
| (self, location, proto, *args) |
28,918 | yampex.plot | clear |
Clears my figure with all annotators and artist
dimensions. Removes my ID from the class-wide
L{PlotterHolder}.
| def clear(self):
"""
Clears my figure with all annotators and artist
dimensions. Removes my ID from the class-wide
L{PlotterHolder}.
"""
try:
# This causes stupid errors with tkagg, so just wrap it in
# try-except for now
self.fig.clear()
except: pass
self.annotators.clear()
self.dims.clear()
self.ph.remove(self.ID)
| (self) |
28,919 | yampex.options | clear_annotations |
Clears the list of annotations.
| def clear_annotations(self):
"""
Clears the list of annotations.
"""
self.opts['annotations'] = []
| (self) |
28,920 | yampex.options | clear_legend |
Clears the list of legend entries.
| def clear_legend(self):
"""
Clears the list of legend entries.
"""
self.opts['legend'] = []
| (self) |
28,921 | yampex.options | clear_plotKeywords |
Clears all keywords for this subplot.
| def clear_plotKeywords(self):
"""
Clears all keywords for this subplot.
"""
self.opts['plotKeywords'].clear()
| (self) |
28,922 | yampex.options | clear_textBoxes |
Clears the dict of text boxes.
| def clear_textBoxes(self):
"""
Clears the dict of text boxes.
"""
self.opts['textBoxes'].clear()
| (self) |
28,923 | yampex.plot | doKeywords |
Applies line style/marker/color settings as keywords for this
vector, except for options already set with keywords.
Then applies plot keywords set via the set_plotKeyword call
and then, with higher priority, those set via the constructor,
if they don't conflict with explicitly set keywords to this
call which takes highest priority.
Returns the new kw dict.
| def doKeywords(self, kVector, kw):
"""
Applies line style/marker/color settings as keywords for this
vector, except for options already set with keywords.
Then applies plot keywords set via the set_plotKeyword call
and then, with higher priority, those set via the constructor,
if they don't conflict with explicitly set keywords to this
call which takes highest priority.
Returns the new kw dict.
"""
kw = self.opts.kwModified(kVector, kw)
for thisDict in (self.kw, self.plotKeywords):
for name in thisDict:
if name not in kw:
kw[name] = thisDict[name]
return kw
| (self, kVector, kw) |
28,924 | yampex.plot | doSettings |
Does C{set_XXX} calls on the C{Axes} object for the subplot at
index I{k}.
| def doSettings(self, k):
"""
Does C{set_XXX} calls on the C{Axes} object for the subplot at
index I{k}.
"""
def bbAdd(textObj):
dims = self.adj.tsc.dims(textObj)
self.dims.setDims(k, name, dims)
for name in self._settings:
value = self.opts[name]
if not value: continue
fontsize = self.fontsize(name, None)
kw = {'size':fontsize} if fontsize else {}
bbAdd(self.sp.set_(name, value, **kw))
if name == 'xlabel':
self.xlabels[k] = value
continue
settings = self.opts['settings']
for name in settings:
bbAdd(self.sp.set_(name, settings[name]))
| (self, k) |
28,925 | yampex.plot | done |
Call this after a call to L{start} when done plotting. This is the
alternative to the context-manager way of using me.
B{Note}: If you don't call this to close out a plotting
session with the alternative method, the last subplot will not
get drawn!
@see: L{start}, which gets called to start the
alternative-method plotting session.
| def done(self):
"""
Call this after a call to L{start} when done plotting. This is the
alternative to the context-manager way of using me.
B{Note}: If you don't call this to close out a plotting
session with the alternative method, the last subplot will not
get drawn!
@see: L{start}, which gets called to start the
alternative-method plotting session.
"""
if not self._isSubplot:
raise Exception("You are not in a subplotting context!")
self.__exit__()
| (self) |
28,926 | yampex.plot | fontsize | null | def fontsize(self, name, default=None):
return self.opts['fontsizes'].get(name, default)
| (self, name, default=None) |
28,927 | yampex.plot | parseArgs |
Parse the supplied I{args} and I{kw} for a constructor call.
Returns a 5-tuple with a revised args list and kw dict, the
number of subplots, the number of columns, and the number of
rows.
| @staticmethod
def parseArgs(*args, **kw):
"""
Parse the supplied I{args} and I{kw} for a constructor call.
Returns a 5-tuple with a revised args list and kw dict, the
number of subplots, the number of columns, and the number of
rows.
"""
N = args[0]
args = list(args[1:])
Nc = kw.pop('Nc', None)
if args and isinstance(args[0], int):
# Nc, Nr specified
if Nc:
raise ValueError(
"You can't specify Nc as both a second arg and keyword")
Nc = N
Nr = args.pop(0)
N = Nc*Nr
else:
# N specified
Nc = Nc if Nc else 3 if N > 6 else 2 if N > 3 else 1
Nr = int(np.ceil(float(N)/Nc))
return args, kw, N, Nc, Nr
| (*args, **kw) |
28,928 | yampex.options | plot |
Specifies a non-logarithmic regular plot, unless called with the
name of a different plot type.
| def plot(self, call="plot"):
"""
Specifies a non-logarithmic regular plot, unless called with the
name of a different plot type.
"""
if call not in PLOTTER_NAMES:
raise ValueError(sub("Unrecognized plot type '{}'", call))
self.opts['call'] = call
| (self, call='plot') |
28,929 | yampex.options | plot_bar |
Specifies a bar plot, unless called with C{False}.
| def plot_bar(self, yes=True):
"""
Specifies a bar plot, unless called with C{False}.
"""
self.opts['call'] = "bar" if yes else "plot"
| (self, yes=True) |
28,930 | yampex.options | plot_error |
Specifies an error bar plot, unless called with C{False}.
| def plot_error(self, yes=True):
"""
Specifies an error bar plot, unless called with C{False}.
"""
self.opts['call'] = "error" if yes else "plot"
| (self, yes=True) |
28,931 | yampex.options | plot_loglog |
Makes both axes logarithmic, unless called with C{False}.
| def plot_loglog(self, yes=True):
"""
Makes both axes logarithmic, unless called with C{False}.
"""
self.opts['call'] = "loglog" if yes else "plot"
| (self, yes=True) |
28,932 | yampex.options | plot_semilogx |
Makes x-axis logarithmic, unless called with C{False}.
| def plot_semilogx(self, yes=True):
"""
Makes x-axis logarithmic, unless called with C{False}.
"""
self.opts['call'] = "semilogx" if yes else "plot"
| (self, yes=True) |
28,933 | yampex.options | plot_semilogy |
Makes y-axis logarithmic, unless called with C{False}.
| def plot_semilogy(self, yes=True):
"""
Makes y-axis logarithmic, unless called with C{False}.
"""
self.opts['call'] = "semilogy" if yes else "plot"
| (self, yes=True) |
28,934 | yampex.options | plot_stem |
Specifies a stem plot, unless called with C{False}.
| def plot_stem(self, yes=True):
"""
Specifies a stem plot, unless called with C{False}.
"""
self.opts['call'] = "stem" if yes else "plot"
| (self, yes=True) |
28,935 | yampex.options | plot_step |
Specifies a step plot, unless called with C{False}.
| def plot_step(self, yes=True):
"""
Specifies a step plot, unless called with C{False}.
"""
self.opts['call'] = "step" if yes else "plot"
| (self, yes=True) |
28,936 | yampex.options | prevOpts |
Lets you use my previous local options (or the current ones, if
there are no previous ones) inside a context call.
| def add_annotation(self, k, proto, *args, **kw):
"""
Adds the text supplied after index I{k} at an annotation of the
plotted vector.
If there is more than one vector being plotted within the same
subplot, you can have the annotation refer to a vector other
than the first one by setting the keyword I{kVector} to its
non-zero index.
The annotation points to the point at index I{k} of the
plotted vector, unless I{k} is a float. In that case, it
points to the point where the vector is closest to that float
value.
You may include a text prototype with format-substitution args
following it, or just supply the final text string with no
further arguments. If you supply just an integer or float
value with no further arguments, it will be formatted
reasonably.
You can set the annotation to the first y-axis value that
crosses a float value of I{k} by setting I{y} C{True}.
@see: L{clear_annotations}.
"""
kVector = None
if args:
if "{" not in proto:
# Called with kVector as a third argument, per API of
# commit 15c49b and earlier
text = proto
kVector = args[0]
else: text = sub(proto, *args)
elif isinstance(proto, int):
text = sub("{:+d}", proto)
elif isinstance(proto, float):
text = sub("{:+.4g}", proto)
else: text = proto
if kVector is None:
kVector = kw.get('kVector', 0)
y = kw.get('y', False)
self.opts['annotations'].append((k, text, kVector, y))
| (self) |
28,937 | yampex.plot | reset |
Clears everything out to start fresh.
| def reset(self):
"""
Clears everything out to start fresh.
"""
self.dims.clear()
self.xlabels.clear()
self.annotators.clear()
self._figTitle = None
self.tbmTitle = None
self._isSubplot = False
self._universal_xlabel = False
self._plotter = None
self.Nsp = 0
| (self) |
28,938 | yampex.options | set |
Before this subplot is drawn, do a C{set_name=value} command to the
axes. You can call this method as many times as you like with
a different attribute I{name} and I{value}.
Use this method in place of calling the Plotter instance with
keywords. Now, such keywords are sent directly to the
underlying Matplotlib plotting call.
| def set(self, name, value):
"""
Before this subplot is drawn, do a C{set_name=value} command to the
axes. You can call this method as many times as you like with
a different attribute I{name} and I{value}.
Use this method in place of calling the Plotter instance with
keywords. Now, such keywords are sent directly to the
underlying Matplotlib plotting call.
"""
self.opts['settings'][name] = value
| (self, name, value) |
28,939 | yampex.options | set_axisExact |
Forces the limits of the named axis ("x" or "y") to exactly the
data range, unless called with C{False}.
| def set_axisExact(self, axisName, yes=True):
"""
Forces the limits of the named axis ("x" or "y") to exactly the
data range, unless called with C{False}.
"""
self.opts['axisExact'][axisName] = yes
| (self, axisName, yes=True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.