text stringlengths 81 112k |
|---|
Return a driver function that can advance a sequence of sine values.
.. code-block:: none
value = A * sin(w*i + phi) + offset
Args:
w (float) : a frequency for the sine driver
A (float) : an amplitude for the sine driver
phi (float) : a phase offset to start the sine driver wi... |
Required Sphinx extension setup function.
def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(
collapsible_code_block,
html=(
html_visit_collapsible_code_block,
html_depart_collapsible_code_block
)
)
app.add_directive('collapsib... |
Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
collecting all nested ``Models`` on the go.
Args:
*discard (C... |
Look up a Bokeh model class, given its view model name.
Args:
view_model_name (str) :
A view model name for a Bokeh model to look up
Returns:
Model: the model class corresponding to ``view_model_name``
Raises:
KeyError, if the model cannot be found
Example:
... |
Visit all references to another Model without recursing into any
of the child Model; may visit the same Model more than once if
it's referenced more than once. Does not visit the passed-in value.
def _visit_immediate_value_references(value, visitor):
''' Visit all references to another Model without recurs... |
Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance and issubclass checks in a couple
places with `type` checks becau... |
A Bokeh protocol "reference" to this model, i.e. a dict of the
form:
.. code-block:: python
{
'type' : << view model name >>
'id' : << unique model id >>
}
Additionally there may be a `subtype` field if this model is a subtype.
def re... |
Link two Bokeh model properties using JavaScript.
This is a convenience method that simplifies adding a CustomJS callback
to update one Bokeh model property whenever another changes value.
Args:
attr (str) :
The name of a Bokeh property on this model
o... |
Attach a ``CustomJS`` callback to an arbitrary BokehJS model event.
On the BokehJS side, change events for model properties have the
form ``"change:property_name"``. As a convenience, if the event name
passed to this method is also the name of a property on the model,
then it will be pr... |
Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
*callbacks (callable) : callback functions to register
Returns:
None
Example:
.. code-block:: python
widget.on_change('... |
Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
def set_select(self, selector, updates):
''' Update objects that match a given selector with the speci... |
Returns a JSON string encoding the attributes of this object.
References to other objects are serialized as references
(just the object ID and type info), so the deserializer
will need to separately have the full attributes of those
other objects.
There's no corresponding ``fro... |
Attach a model to a Bokeh |Document|.
This private interface should only ever called by the Document
implementation to set the private ._document field properly
def _attach_document(self, doc):
''' Attach a model to a Bokeh |Document|.
This private interface should only ever called by... |
Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a Model, rather
than turning into a reference, n... |
Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-key
map_options: (GMapOptions)
Config... |
Return a copy of this color value.
Returns:
HSL
def copy(self):
''' Return a copy of this color value.
Returns:
HSL
'''
return HSL(self.h, self.s, self.l, self.a) |
Generate the CSS representation of this HSL color.
Returns:
str, ``"hsl(...)"`` or ``"hsla(...)"``
def to_css(self):
''' Generate the CSS representation of this HSL color.
Returns:
str, ``"hsl(...)"`` or ``"hsla(...)"``
'''
if self.a == 1.0:
... |
Return a corresponding :class:`~bokeh.colors.rgb.RGB` color for
this HSL color.
Returns:
HSL
def to_rgb(self):
''' Return a corresponding :class:`~bokeh.colors.rgb.RGB` color for
this HSL color.
Returns:
HSL
'''
from .rgb import RGB # p... |
Get the location of the server subpackage
def serverdir():
""" Get the location of the server subpackage
"""
path = join(ROOT_DIR, 'server')
path = normpath(path)
if sys.platform == 'cygwin': path = realpath(path)
return path |
Get the location of the bokehjs source files. If dev is True,
the files in bokehjs/build are preferred. Otherwise uses the files
in bokeh/server/static.
def bokehjsdir(dev=False):
""" Get the location of the bokehjs source files. If dev is True,
the files in bokehjs/build are preferred. Otherwise uses ... |
Install the Bokeh Server and its background tasks on a Tornado
``IOLoop``.
This method does *not* block and does *not* affect the state of the
Tornado ``IOLoop`` You must start and stop the loop yourself, i.e.
this method is typically useful when you are already explicitly
mana... |
Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for orderly cleanup (default: True)
Returns:
None... |
Run the Bokeh Server until shutdown is requested by the user,
either via a Keyboard interrupt (Ctrl-C) or SIGTERM.
Calling this method will start the Tornado ``IOLoop`` and block
all execution in the calling process.
Returns:
None
def run_until_shutdown(self):
''' ... |
Gets all currently active sessions for applications.
Args:
app_path (str, optional) :
The configured application path for the application to return
sessions for. If None, return active sessions for all
applications. (default: None)
Returns:
... |
Opens an app in a browser window or tab.
This method is useful for testing or running Bokeh server applications
on a local machine but should not call when running Bokeh server for
an actual deployment.
Args:
app_path (str) : the app path to open
The part of... |
Make a fresh module to run in.
Returns:
Module
def new_module(self):
''' Make a fresh module to run in.
Returns:
Module
'''
self.reset_run_errors()
if self._code is None:
return None
module_name = 'bk_script_' + make_id().... |
Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution... |
Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case.
def loop_until_clos... |
Pull a document from the server, overwriting the passed-in document
Args:
document : (Document)
The document to overwrite with server content.
Returns:
None
def pull_doc(self, document):
''' Pull a document from the server, overwriting the passed-in docum... |
Push a document to the server, overwriting any existing server-side doc.
Args:
document : (Document)
A Document to push to the server
Returns:
The server reply
def push_doc(self, document):
''' Push a document to the server, overwriting any existing ser... |
Ask for information about the server.
Returns:
A dictionary of server attributes.
def request_server_info(self):
''' Ask for information about the server.
Returns:
A dictionary of server attributes.
'''
if self._server_info is None:
self._s... |
Export the ``LayoutDOM`` object or document as a PNG.
If the filename is not given, it is derived from the script name (e.g.
``/foo/myplot.py`` will create ``/foo/myplot.png``)
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
... |
Export the SVG-enabled plots within a layout. Each plot will result
in a distinct SVG file.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
Args:
obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to ... |
Get a screenshot of a ``LayoutDOM`` object.
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
driver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum a... |
Crop the border from the layout
def _crop_image(image, left=0, top=0, right=0, bottom=0, **kwargs):
''' Crop the border from the layout
'''
return image.crop((left, top, right, bottom)) |
Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array]
def _data_from_df(df):
''' Create a ``dict`` of columns from a Pandas ``DataFrame``,
... |
Return the Bokeh-appropriate column name for a ``DataFrame`` index
If there is no named index, then `"index" is returned.
If there is a single named index, then ``df.index.name`` is returned.
If there is a multi-index, and the index names are all strings, then
the names are joined wit... |
Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the column name used
def add(self, data, name=No... |
Remove a column of data.
Args:
name (str) : name of the column to remove
Returns:
None
.. note::
If the column name does not exist, a warning is issued.
def remove(self, name):
''' Remove a column of data.
Args:
name (str) : na... |
Internal implementation to efficiently update data source columns
with new append-only data. The internal implementation adds the setter
attribute. [https://github.com/bokeh/bokeh/issues/6577]
In cases where it is necessary to update data columns in, this method
can efficiently send on... |
Efficiently update data source columns at specific locations
If it is only necessary to update a small subset of data in a
``ColumnDataSource``, this method can be used to efficiently update only
the subset, instead of requiring the entire data set to be sent.
This method should be pas... |
Silence a particular warning on all Bokeh models.
Args:
warning (Warning) : Bokeh warning to silence
silence (bool) : Whether or not to silence the warning
Returns:
A set containing the all silenced warnings
This function adds or removes warnings from a set of silencers which
... |
Apply validation and integrity checks to a collection of Bokeh models.
Args:
models (seq[Model]) : a collection of Models to test
Returns:
None
This function will emit log warning and error messages for all error or
warning conditions that are detected. For example, layouts without an... |
Apply this theme to a model.
.. warning::
Typically, don't call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of.
def apply_to_model(self, model):
''' Apply this theme to a model.
.. warning::
Typi... |
Find or create a (possibly temporary) Document to use for serializing
Bokeh content.
Typical usage is similar to:
.. code-block:: python
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
Inside the context manager, the mod... |
Traverses submodels to check for Python (event) callbacks
def submodel_has_python_callbacks(models):
''' Traverses submodels to check for Python (event) callbacks
'''
has_python_callback = False
for model in collect_models(models):
if len(model._callbacks) > 0 or len(model._event_callbacks) > ... |
Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx
layout function. Any keyword arguments will be passed to the
layout function.
Only two dimensional layouts are supported.
Args:
graph (networkx.Graph) : a networkx graph to render
layout_... |
Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
... |
Generate a random session ID.
Typically, each browser tab connected to a Bokeh application
has its own session ID. In production deployments of a Bokeh
app, session IDs should be random and unguessable - otherwise
users of the app could interfere with one another.
If session IDs are signed with a... |
Check the signature of a session ID, returning True if it's valid.
The server uses this function to check whether a session ID
was generated with the correct secret key. If signed sessions are disabled,
this function always returns True.
Args:
session_id (str) : The session ID to check
... |
Return a securely generated random string.
With the a-z, A-Z, 0-9 character set:
Length 12 is a 71-bit value. log_2((26+26+10)^12) =~ 71
Length 44 is a 261-bit value. log_2((26+26+10)^44) = 261
def _get_random_string(length=44,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
... |
Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can upd... |
Create a ``CustomJSTransform`` instance from a pair of Python
functions. The function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It's
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions... |
Create a ``CustomJSTransform`` instance from a pair of CoffeeScript
snippets. The function bodies are translated to JavaScript functions
using node and therefore require return statements.
The ``func`` snippet namespace will contain the variable ``x`` (the
untransformed value) at render... |
A decorator to mark abstract base classes derived from |HasProps|.
def abstract(cls):
''' A decorator to mark abstract base classes derived from |HasProps|.
'''
if not issubclass(cls, HasProps):
raise TypeError("%s is not a subclass of HasProps" % cls.__name__)
# running python with -OO will ... |
Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__``
def... |
Traverse the class hierarchy and accumulate the special dicts
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__dataspecs__``,
``__overridden_defaults__``
def accumulate_dict_from_superclasses(... |
Structural equality of models.
Args:
other (HasProps) : the other instance to compare to
Returns:
True, if properties are structurally equal, otherwise False
def equals(self, other):
''' Structural equality of models.
Args:
other (HasProps) : the o... |
Set a property value on this object from JSON.
Args:
name: (str) : name of the attribute to set
json: (JSON-value) : value to set to the attribute to
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is n... |
Updates the object's properties from a JSON attributes dictionary.
Args:
json_attributes: (JSON-dict) : attributes and values to update
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the at... |
Collect the names of properties on this class.
This method *optionally* traverses the class hierarchy and includes
properties defined on any parent classes.
Args:
with_bases (bool, optional) :
Whether to include properties defined on parent classes in
... |
Collect a dict mapping property names to their values.
This method *always* traverses the class hierarchy and includes
properties defined on any parent classes.
Non-serializable properties are skipped and property values are in
"serialized" format which may be slightly different from t... |
Query the properties values of |HasProps| instances with a
predicate.
Args:
query (callable) :
A callable that accepts property descriptors and returns True
or False
include_defaults (bool, optional) :
Whether to include propertie... |
Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so neither the caller nor the
|HasProps| instance should modify it).
... |
Indent all the lines in a given block of text by a specified amount.
Args:
text (str) :
The text to indent
n (int, optional) :
The amount to indent each line by (default: 2)
ch (char, optional) :
What character to fill the indentation with (default: " "... |
Join together sequences of strings into English-friendly phrases using
the conjunction ``or`` when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjuctio... |
Convert CamelCase to snake_case.
def snakify(name, sep='_'):
''' Convert CamelCase to snake_case. '''
name = re.sub("([A-Z]+)([A-Z][a-z])", r"\1%s\2" % sep, name)
name = re.sub("([a-z\\d])([A-Z])", r"\1%s\2" % sep, name)
return name.lower() |
Calls any on_session_destroyed callbacks defined on the Document
def _on_session_destroyed(session_context):
'''
Calls any on_session_destroyed callbacks defined on the Document
'''
callbacks = session_context._document.session_destroyed_callbacks
session_context._document.session_destroyed_callbac... |
Decorator to add a Message (and its revision) to the Protocol index.
Example:
.. code-block:: python
@register
class some_msg_1(Message):
msgtype = 'SOME-MSG'
revision = 1
@classmethod
def create(cls, **metadata):
... |
Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the... |
Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and cha... |
Open a browser displaying a session document.
If you have a session from ``pull_session()`` or ``push_session`` you
can ``show_session(session=mysession)``. If you don't need to open a
connection to the server yourself, you can show a new session in a
browser by providing just the ``url... |
Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case. This function is int... |
Pull the server's state and set it as session.document.
If this is called more than once, session.document will be the same
object instance but its contents will be overwritten.
Automatically calls :func:`connect` before pulling.
def pull(self):
''' Pull the server's state and set it ... |
Push the given document to the server and record it as session.document.
If this is called more than once, the Document has to be the same (or None
to mean "session.document").
.. note::
Automatically calls :func:`~connect` before pushing.
Args:
document (:clas... |
Open a browser displaying this session.
Args:
obj (LayoutDOM object, optional) : a Layout (Row/Column),
Plot or Widget object to display. The object will be added
to the session's document.
browser (str, optional) : browser to show with (default: None)
... |
Called by the ClientConnection we are using to notify us of disconnect.
def _notify_disconnected(self):
''' Called by the ClientConnection we are using to notify us of disconnect.
'''
if self.document is not None:
self.document.remove_on_change(self)
self._callbacks.rem... |
Creates a new message, assembled from JSON fragments.
Args:
header_json (``JSON``) :
metadata_json (``JSON``) :
content_json (``JSON``) :
Returns:
Message subclass
Raises:
MessageError
def assemble(cls, header_json, metadata_json,... |
Associate a buffer header and payload with this message.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
MessageError
def add_buffer(self, buf_header, buf_payload):
... |
Add a buffer header and payload that we read from the socket.
This differs from add_buffer() because we're validating vs.
the header's num_buffers, instead of filling in the header.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer... |
Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
locked (bool) :
Returns:
int ... |
Return a message header fragment dict.
Args:
request_id (str or None) :
Message ID of the message this message replies to
Returns:
dict : a message header
def create_header(cls, request_id=None):
''' Return a message header fragment dict.
Args:... |
Send the message on the given connection.
Args:
conn (WebSocketHandler) : a WebSocketHandler to send messages
Returns:
int : number of bytes sent
def send(self, conn):
''' Send the message on the given connection.
Args:
conn (WebSocketHandler) : a ... |
Returns whether all required parts of a message are present.
Returns:
bool : True if the message is complete, False otherwise
def complete(self):
''' Returns whether all required parts of a message are present.
Returns:
bool : True if the message is complete, False oth... |
A logging.basicConfig() wrapper that also undoes the default
Bokeh-specific configuration.
def basicConfig(*args, **kwargs):
"""
A logging.basicConfig() wrapper that also undoes the default
Bokeh-specific configuration.
"""
if default_handler is not None:
bokeh_logger.removeHandler(defa... |
Issue a nicely formatted deprecation warning.
def deprecated(since_or_msg, old=None, new=None, extra=None):
""" Issue a nicely formatted deprecation warning. """
if isinstance(since_or_msg, tuple):
if old is None or new is None:
raise ValueError("deprecated entity and a replacement are req... |
Execute the "bokeh" command line program.
def main():
''' Execute the "bokeh" command line program.
'''
import sys
from bokeh.command.bootstrap import main as _main
# Main entry point (see setup.py)
_main(sys.argv) |
Allow the session to be discarded and don't get change notifications from it anymore
def detach_session(self):
"""Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session is not None:
self._session.unsubscribe(self)
self._session =... |
Sends a PATCH-DOC message, returning a Future that's completed when it's written out.
def send_patch_document(self, event):
""" Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """
msg = self.protocol.create('PATCH-DOC', [event])
return self._socket.send_mes... |
Given a JSON representation of the models in a graph, and new model
objects, set the properties on the models from the JSON
Args:
references_json (``JSON``)
JSON specifying attributes and values to initialize new model
objects with.
references (dict[str, Model])
... |
Given a JSON representation of all the models in a graph, return a
dict of new model objects.
Args:
references_json (``JSON``)
JSON specifying new Bokeh models to create
Returns:
dict[str, Model]
def instantiate_references_json(references_json):
''' Given a JSON representa... |
Given a list of all models in a graph, return JSON representing
them and their properties.
Args:
references (seq[Model]) :
A list of models to convert to JSON
Returns:
list
def references_json(references):
''' Given a list of all models in a graph, return JSON representing... |
Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError... |
Generate an inline visual representations of a single color palette.
This function evaluates the expression ``"palette = %s" % text``, in the
context of a ``globals`` namespace that has previously imported all of
``bokeh.plotting``. The resulting value for ``palette`` is used to
construct a sequence of... |
Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression
for a ``ColumnDataSource``.
Examples:
.. code-block:: python
p.wedge(start_angle=cumsum('angle', include_zero=True),
end_angle=cumsum('angle'),
...)
will generate a ``C... |
Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
value (float) : the fixed offset to add to column data
range (Range, optional) : a range to use for co... |
Create a ``DataSpec`` dict that applies a client-side
``CategoricalColorMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
palette (seq[color]) : a list of colors to use for colormapping
factors (seq) : a ... |
Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq[string]) : a list of hatch patterns to use to map to
factors (seq)... |
Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be parameterized by glyph type.
Args:
field_name (str) : a field name... |
Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
width (float) : the width of the random distribution to apply
mean (float, optional) : an offset to ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.