text
stringlengths
81
112k
Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run. def start(self): ''' Start the Bokeh Server ...
Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (default: True) Returns: None def stop(self, wait=True): ''' Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (defaul...
Get an active a session by name application path and session ID. Args: app_path (str) : The configured application path for the application to return a session for. session_id (str) : The session ID of the session to retrieve. Re...
Gets all currently active sessions for an application. Args: app_path (str) : The configured application path for the application to return sessions for. Returns: list[ServerSession] def get_sessions(self, app_path): ''' Gets all current...
Internal shared implementation to handle both error and warning validation checks. Args: code code_or_name (int or str) : a defined error code or custom message validator_type (str) : either "error" or "warning" Returns: validation decorator def _validator(code_or_name, validator_...
Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : objects that match the query Queries are spe...
Test whether a given Bokeh model matches a given selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Returns: bool : True if the object matches, False otherwise In general, the selec...
Required Sphinx extension setup function. def setup(app): ''' Required Sphinx extension setup function. ''' app.add_config_value('bokeh_gallery_dir', join("docs", "gallery"), 'html') app.connect('config-inited', config_inited_handler) app.add_directive('bokeh-gallery', BokehGalleryDirective)
Generate a default filename with a given extension, attempting to use the filename of the currently running process, if possible. If the filename of the current process is not available (or would not be writable), then a temporary file with the given extension is returned. Args: ext (str) : th...
Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. def detect_current_filename(): ''' Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. ''' import inspect ...
Return True if the given base dir is not accessible or writeable def _no_access(basedir): ''' Return True if the given base dir is not accessible or writeable ''' import os return not os.access(basedir, os.W_OK | os.X_OK)
Whether a give base directory is on the system exex prefix def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is not None and basedir.startswith(prefix))
Required Sphinx extension setup function. def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node(bokeh_palette_group, html=(html_visit_bokeh_palette_group, None)) app.add_directive('bokeh-palette-group', BokehPaletteGroupDirective)
Return args for ``-o`` / ``--output`` to specify where output should be written, and for a ``--args`` to pass on any additional command line args to the subcommand. Subclasses should append these to their class ``args``. Example: .. code-block:: python cla...
Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist. def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0): """ Given a kwargs dict, a prefix, and a default value, lo...
Takes a string and returns a corresponding `Tool` instance. def _tool_from_string(name): """ Takes a string and returns a corresponding `Tool` instance. """ known_tools = sorted(_known_tools.keys()) if name in known_tools: tool_fn = _known_tools[name] if isinstance(tool_fn, string_types):...
Adds tools to the plot object Args: plot (Plot): instance of a plot object tools (seq[Tool or str]|str): list of tool types or string listing the tool names. Those are converted using the _tool_from_string function. I.e.: `wheel_zoom,box_zoom,reset`. tooltips (string...
Adds tools to the plot object Args: toolbar (Toolbar): instance of a Toolbar object tools_map (dict[str]|Tool): tool_map from _process_tools_arg active_drag (str or Tool): the tool to set active for drag active_inspect (str or Tool): the tool to set active for inspect active...
Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript. def from_py_func(cls, func): """ Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript. """ from bokeh.util.depr...
Write a message to the websocket after obtaining the appropriate Bokeh Document lock. def write_message(self, message, binary=False, locked=True): ''' Write a message to the websocket after obtaining the appropriate Bokeh Document lock. ''' def write_message_unlocked(): ...
Collect external resources set on resource_attr attribute of all models. def _collect_external_resources(self, resource_attr): """ Collect external resources set on resource_attr attribute of all models.""" external_resources = [] for _, cls in sorted(Model.model_class_reverse_map.items(), ke...
Set the log level for python Bokeh code. def py_log_level(self, default='none'): ''' Set the log level for python Bokeh code. ''' level = self._get_str("PY_LOG_LEVEL", default, "debug") LEVELS = {'trace': logging.TRACE, 'debug': logging.DEBUG, 'info'...
Return the secret_key, converted to bytes and cached. def secret_key_bytes(self): ''' Return the secret_key, converted to bytes and cached. ''' if not hasattr(self, '_secret_key_bytes'): key = self.secret_key() if key is None: self._secret_key_bytes = No...
The absolute path of the BokehJS source code in the installed Bokeh source tree. def bokehjssrcdir(self): ''' The absolute path of the BokehJS source code in the installed Bokeh source tree. ''' if self._is_dev or self.debugjs: bokehjssrcdir = abspath(join(ROOT_DIR,...
The CSS files in the BokehJS directory. def css_files(self): ''' The CSS files in the BokehJS directory. ''' bokehjsdir = self.bokehjsdir() js_files = [] for root, dirnames, files in os.walk(bokehjsdir): for fname in files: if fname.endswith(".css"):...
Return a serialized JSON representation of objects, suitable to send to BokehJS. This function is typically used to serialize single python objects in the manner expected by BokehJS. In particular, many datetime values are automatically normalized to an expected format. Some Bokeh objects can also ...
Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder. def transform_python_types(self...
The required ``default`` method for ``JSONEncoder`` subclasses. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder. def default(self, obj): ''' The required ``default`` me...
Add a handler to the pipeline used to initialize new documents. Args: handler (Handler) : a handler for this Application to use to process Documents def add(self, handler): ''' Add a handler to the pipeline used to initialize new documents. Args: handle...
Fills in a new document using the Application's handlers. def initialize_document(self, doc): ''' Fills in a new document using the Application's handlers. ''' for h in self._handlers: # TODO (havocp) we need to check the 'failed' flag on each handler # and build a comp...
Invoked to execute code when a new session is created. This method calls ``on_session_created`` on each handler, in order, with the session context passed as the only argument. May return a ``Future`` which will delay session creation until the ``Future`` completes. def on_session_cre...
Allow flexible selector syntax. Returns: dict def _select_helper(args, kwargs): """ Allow flexible selector syntax. Returns: dict """ if len(args) > 1: raise TypeError("select accepts at most ONE positional argument.") if len(args) > 0 and len(kwargs) > 0: ra...
Query this object and all of its references for objects that match the given selector. There are a few different ways to call the ``select`` method. The most general is to supply a JSON-like query dictionary as the single argument or as keyword arguments: Args: sele...
Splattable list of :class:`~bokeh.models.annotations.Legend` objects. def legend(self): ''' Splattable list of :class:`~bokeh.models.annotations.Legend` objects. ''' panels = self.above + self.below + self.left + self.right + self.center legends = [obj for obj in panels if isinstance(o...
Splattable list of :class:`~bokeh.models.tools.HoverTool` objects. def hover(self): ''' Splattable list of :class:`~bokeh.models.tools.HoverTool` objects. ''' hovers = [obj for obj in self.tools if isinstance(obj, HoverTool)] return _list_attr_splat(hovers)
Adds an object to the plot in a specified place. Args: obj (Renderer) : the object to add to the Plot place (str, optional) : where to add the object (default: 'center') Valid places are: 'left', 'right', 'above', 'below', 'center'. Returns: None de...
Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None def add_tools(self, *tools): ''' Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None ''' ...
Adds a glyph to the plot with associated data sources and ranges. This function will take care of creating and configuring a Glyph object, and then add it to the plot's list of renderers. Args: source (DataSource) : a data source for the glyphs to all use glyph (Glyph) ...
Adds new ``TileRenderer`` into ``Plot.renderers`` Args: tile_source (TileSource) : a tile source instance which contain tileset configuration Keyword Arguments: Additional keyword arguments are passed on as-is to the tile renderer Returns: TileRenderer : Ti...
Create a row of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the row. Can be any of the following - :class:`~bokeh.models.plot...
Create a column of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the column. Can be any of the following - :class:`~bokeh.model...
Create a column of bokeh widgets with predefined styling. Args: children (list of :class:`~bokeh.models.widgets.widget.Widget`): A list of widgets. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout ...
Create a grid-based arrangement of Bokeh Layout objects. Args: children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget...
Create a grid of plots rendered on separate canvases. The ``gridplot`` function builds a single toolbar for all the plots in the grid. ``gridplot`` is designed to layout a set of plots. For general grid layout, use the :func:`~bokeh.layouts.layout` function. Args: children (list of lists of :c...
Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but...
Recursively create grid from input lists. def _create_grid(iterable, sizing_mode, layer=0): """Recursively create grid from input lists.""" return_list = [] for item in iterable: if isinstance(item, list): return_list.append(_create_grid(item, sizing_mode, layer+1)) elif isinsta...
Yield successive n-sized chunks from list, l. def _chunks(l, ncols): """Yield successive n-sized chunks from list, l.""" assert isinstance(ncols, int), "ncols must be an integer" for i in range(0, len(l), ncols): yield l[i: i+ncols]
Wrap a callback function to execute without first obtaining the document lock. Args: func (callable) : The function to wrap Returns: callable : a function wrapped to execute without a |Document| lock. While inside an unlocked callback, it is completely *unsafe* to modify ``curdoc(...
Return a script tag that embeds content from a Bokeh server. Bokeh apps embedded using these methods will NOT set the browser window title. Args: url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAU...
Return a script tag that embeds content from a specific existing session on a Bokeh server. This function is typically only useful for serving from a a specific session that was previously created using the ``bokeh.client`` API. Bokeh apps embedded using these methods will NOT set the browser window t...
Produce a canonical Bokeh server URL. Args: url (str) A URL to clean, or "defatul". If "default" then the ``BOKEH_SERVER_HTTP_URL`` will be returned. Returns: str def _clean_url(url): ''' Produce a canonical Bokeh server URL. Args: url (str) ...
Extract the app path from a Bokeh server URL Args: url (str) : Returns: str def _get_app_path(url): ''' Extract the app path from a Bokeh server URL Args: url (str) : Returns: str ''' app_path = urlparse(url).path.rstrip("/") if not app_path.startswi...
Return user-supplied HTML arguments to add to a Bokeh server URL. Args: arguments (dict[str, object]) : Key/value pairs to add to the URL Returns: str def _process_arguments(arguments): ''' Return user-supplied HTML arguments to add to a Bokeh server URL. Args: ar...
Implement a check_origin policy for Tornado to call. The supplied origin will be compared to the Bokeh server whitelist. If the origin is not allow, an error will be logged and ``False`` will be returned. Args: origin (str) : The URL of the connection origin ...
Initialize a connection to a client. Returns: None def open(self): ''' Initialize a connection to a client. Returns: None ''' log.info('WebSocket connection opened') proto_version = self.get_argument("bokeh-protocol-version", default=None) ...
Perform the specific steps needed to open a connection to a Bokeh session Specifically, this method coordinates: * Getting a session for a session ID (creating a new one if needed) * Creating a protocol receiver and hander * Opening a new ServerConnection and sending it an ACK ...
Process an individual wire protocol fragment. The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got. Args: ...
Send a Bokeh Server protocol message to the connected client. Args: message (Message) : a message to send def send_message(self, message): ''' Send a Bokeh Server protocol message to the connected client. Args: message (Message) : a message to send ''' ...
Override parent write_message with a version that acquires a write lock before writing. def write_message(self, message, binary=False, locked=True): ''' Override parent write_message with a version that acquires a write lock before writing. ''' if locked: with (yiel...
Clean up when the connection is closed. def on_close(self): ''' Clean up when the connection is closed. ''' log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason) if self.connection is not None: self.application.client_lost(self.conn...
Generate rendered CSS and JS resources suitable for the given collection of Bokeh objects Args: objs (seq[Model or Document]) : resources (BaseResources or tuple[BaseResources]) Returns: tuple def bundle_for_objs_and_resources(objs, resources): ''' Generate rendered CSS and J...
Whether any of a collection of objects satisfies a given query predicate Args: objs (seq[Model or Document]) : query (callable) Returns: True, if ``query(obj)`` is True for some object in ``objs``, else False def _any(objs, query): ''' Whether any of a collection of objects satis...
Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: bool def _use_gl(objs): ''' Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: ...
Whether a collection of Bokeh objects contains a TableWidget Args: objs (seq[Model or Document]) : Returns: bool def _use_tables(objs): ''' Whether a collection of Bokeh objects contains a TableWidget Args: objs (seq[Model or Document]) : Returns: bool ''' ...
Whether a collection of Bokeh objects contains a any Widget Args: objs (seq[Model or Document]) : Returns: bool def _use_widgets(objs): ''' Whether a collection of Bokeh objects contains a any Widget Args: objs (seq[Model or Document]) : Returns: bool ''' ...
``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of...
Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. Args: obj (HasProps) : the object to get the serialized at...
Sets the value of this property from a JSON value. Args: obj: (HasProps) : instance to set the property value on json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) ...
Get the default value that will be used for a specific instance. Args: obj (HasProps) : The instance to get the default value for. Returns: object def instance_default(self, obj): ''' Get the default value that will be used for a specific instance. Args: ...
Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomeran...
Send a change event notification if the property is set to a value is not equal to ``old``. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare Returns: None...
Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for ...
Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc. def _get_default(self, obj): ''' Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyConta...
Internal implementation to set property values, that is used by __set__, set_from_json, etc. Delegate to the |Property| instance to prepare the value appropriately, then `set. Args: obj (HasProps) The object the property is being set on. old (ob...
Internal implementation helper to set property values. This function handles bookkeeping around noting whether values have been explicitly set, etc. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous v...
A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container ...
Unconditionally send a change event notification for the property. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property new (obj) : The new value of the property ...
Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomeran...
Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to the superclass ``set_from_json`` to be handled. Args: ...
Internal helper for dealing with units associated units properties when setting values on |UnitsSpec| properties. When ``value`` is a dict, this function may mutate the value of the associated units property. Args: obj (HasProps) : instance to update units spec property val...
Install a new notebook display hook. Bokeh comes with support for Jupyter notebooks built-in. However, there are other kinds of notebooks in use by different communities. This function provides a mechanism for other projects to instruct Bokeh how to display content in other notebooks. This functio...
Update Bokeh plots in a Jupyter notebook output cells with new data or property values. When working the the notebook, the ``show`` function can be passed the argument ``notebook_handle=True``, which will cause it to return a handle object that can be used to update the Bokeh output later. When ``p...
Run an installed notebook hook with supplied arguments. Args: noteboook_type (str) : Name of an existing installed notebook hook actions (str) : Name of the hook action to execute, ``'doc'`` or ``'app'`` All other arguments and keyword arguments are passed to the hook ...
Given a UUID id of a div removed or replaced in the Jupyter notebook, destroy the corresponding server sessions and stop it. def destroy_server(server_id): ''' Given a UUID id of a div removed or replaced in the Jupyter notebook, destroy the corresponding server sessions and stop it. ''' server = ...
Prepare the IPython notebook for displaying Bokeh plots. Args: resources (Resource, optional) : how and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to report detailed settings (default: False) hide_banner (bool, optional): ...
Embed a Bokeh server application in a Jupyter Notebook output cell. Args: app (Application or callable) : A Bokeh Application to embed inline in a Jupyter notebook. state (State) : ** Unused ** notebook_url (str or callable) : The URL of the notebook se...
Clamp numeric values to be non-negative, an optionally, less than a given maximum. Args: value (float) : A number to clamp. maximum (float, optional) : A max bound to to clamp to. If None, there is no upper bound, and values are o...
Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color def darken(self, amount): ''' Darken (reduce the luminance) of this color. Args: amount (float...
Lighten (increase the luminance) of this color. Args: amount (float) : Amount to increase the luminance by (clamped above zero) Returns: Color def lighten(self, amount): ''' Lighten (increase the luminance) of this color. Args: amou...
Set up a handler for button state changes (clicks). Args: handler (func) : handler function to call when button is toggled. Returns: None def on_click(self, handler): """ Set up a handler for button state changes (clicks). Args: handler (func) : ha...
Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None def on_click(self, handler): ''' Set up a handler for button or menu item clicks. Args: handler (func) : handle...
Set up a JavaScript handler for button or menu item clicks. def js_on_click(self, handler): ''' Set up a JavaScript handler for button or menu item clicks. ''' self.js_on_event(ButtonClick, handler) self.js_on_event(MenuItemClick, handler)
Attempt to import an optional dependency. Silently returns None if the requested module is not available. Args: mod_name (str) : name of the optional module to try to import Returns: imported module or None, if import fails def import_optional(mod_name): ''' Attempt to import an opti...
Detect if PhantomJS is avaiable in PATH, at a minimum version. Args: version (str, optional) : Required minimum version for PhantomJS (mostly for testing) Returns: str, path to PhantomJS def detect_phantomjs(version='2.1'): ''' Detect if PhantomJS is avaiable in PATH, at a min...
Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message. def consume(self, fragment): ''' ...
Required Sphinx extension setup function. def setup(app): ''' Required Sphinx extension setup function. ''' app.add_autodocumenter(ColorDocumenter) app.add_autodocumenter(EnumDocumenter) app.add_autodocumenter(PropDocumenter) app.add_autodocumenter(ModelDocumenter)
Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce def bounce(sequence): ''' Return a d...
Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine d...
Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver def linear(m=1, b=0): ''' Return a driver function that can advance a sequence...
Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce def repeat(sequence): ''' Return a driver function th...