INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._docume...
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists. ''' super(ModelChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_model_changed'): ...
Create a JSON representation of this event suitable for sending to clients.
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collect...
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists. ''' super(ColumnDataChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_column_data_changed'): receiver...
Create a JSON representation of this event suitable for sending to clients.
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnDataChanged' 'column_source' : <reference to a CDS> 'new' ...
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_streamed`` if it exists. ''' super(ColumnsStreamedEvent, self).dispatch(receiver) if hasattr(receiver, '_columns_streamed'): receiver._column...
Create a JSON representation of this event suitable for sending to clients.
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnsStreamed' 'column_source' : <reference to a CDS> 'data' ...
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_patched`` if it exists. ''' super(ColumnsPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_columns_patched'): receiver._columns_p...
Create a JSON representation of this event suitable for sending to clients.
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: referenc...
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists. ''' super(SessionCallbackAdded, self).dispatch(receiver) if hasattr(receiver, '_session_callback_added'): ...
Dispatch handling of this event to a receiver.
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists. ''' super(SessionCallbackRemoved, self).dispatch(receiver) if hasattr(receiver, '_session_callback_removed'): ...
Print a useful report after setuptools output describing where and how BokehJS is installed.
def show_bokehjs(bokehjs_action, develop=False): ''' Print a useful report after setuptools output describing where and how BokehJS is installed. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree ...
Print information about extra Bokeh - specific command line options.
def show_help(bokehjs_action): ''' Print information about extra Bokeh-specific command line options. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree Returns: None ''' print() if ...
Build a new BokehJS ( and install it ) or install a previously build BokehJS.
def build_or_install_bokehjs(): ''' Build a new BokehJS (and install it) or install a previously build BokehJS. If no options ``--build-js`` or ``--install-js`` are detected, the user is prompted for what to do. If ``--existing-js`` is detected, then this setup.py is being run from a packaged ...
Check for sdist and ensure we always build BokehJS when packaging
def fixup_building_sdist(): ''' Check for 'sdist' and ensure we always build BokehJS when packaging Source distributions do not ship with BokehJS source code, but must ship with a pre-built BokehJS library. This function modifies ``sys.argv`` as necessary so that ``--build-js`` IS present, and ``--inst...
If we are installing FROM an sdist then a pre - built BokehJS is already installed in the python source tree.
def fixup_for_packaged(): ''' If we are installing FROM an sdist, then a pre-built BokehJS is already installed in the python source tree. The command line options ``--build-js`` or ``--install-js`` are removed from ``sys.argv``, with a warning. Also adds ``--existing-js`` to ``sys.argv`` to signa...
A cmdclass that works around a setuptools deficiency.
def get_cmdclass(): ''' A ``cmdclass`` that works around a setuptools deficiency. There is no need to build wheels when installing a package, however some versions of setuptools seem to mandate this. This is a hacky workaround that modifies the ``cmdclass`` returned by versioneer so that not having ...
Prompt users whether to build a new BokehJS or install an existing one.
def jsbuild_prompt(): ''' Prompt users whether to build a new BokehJS or install an existing one. Returns: bool : True, if a new build is requested, False otherwise ''' print(BOKEHJS_BUILD_PROMPT) mapping = {"1": True, "2": False} value = input("Choice? ") while value not in mappin...
Build BokehJS files ( CSS JS etc ) under the bokehjs source subdirectory.
def build_js(): ''' Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them in...
Copy built BokehJS files into the Python source tree.
def install_js(): ''' Copy built BokehJS files into the Python source tree. Returns: None ''' target_jsdir = join(SERVER, 'static', 'js') target_cssdir = join(SERVER, 'static', 'css') target_tslibdir = join(SERVER, 'static', 'lib') STATIC_ASSETS = [ join(JS, 'bokeh.js'), ...
Map axial * ( q r ) * coordinates to cartesian * ( x y ) * coordinates of tiles centers.
def axial_to_cartesian(q, r, size, orientation, aspect_scale=1): ''' Map axial *(q,r)* coordinates to cartesian *(x,y)* coordinates of tiles centers. This function can be useful for positioning other Bokeh glyphs with cartesian coordinates in relation to a hex tiling. This function was adapted fro...
Map Cartesion * ( x y ) * points to axial * ( q r ) * coordinates of enclosing tiles.
def cartesian_to_axial(x, y, size, orientation, aspect_scale=1): ''' Map Cartesion *(x,y)* points to axial *(q,r)* coordinates of enclosing tiles. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#pixel-to-hex Args: x (array[float]) : A NumPy arr...
Perform an equal - weight binning of data points into hexagonal tiles.
def hexbin(x, y, size, orientation="pointytop", aspect_scale=1): ''' Perform an equal-weight binning of data points into hexagonal tiles. For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews. Args: ...
Round floating point axial hex coordinates to integer * ( q r ) * coordinates.
def _round_hex(q, r): ''' Round floating point axial hex coordinates to integer *(q,r)* coordinates. This code was adapted from: https://www.redblobgames.com/grids/hexagons/#rounding Args: q (array[float]) : NumPy array of Floating point axial *q* coordinates to round ...
Try to determine the version from the parent directory name.
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an ap...
TAG [. post. devDISTANCE ] -- No - dirty.
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exce...
Some property types need to wrap their values in special containers etc.
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, list): if isinstance(value, PropertyValueList): return value else: return PropertyValueList(value) else: ...
Some property types need to wrap their values in special containers etc.
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, dict): if isinstance(value, PropertyValueDict): return value else: return PropertyValueDict(value) else: ...
Decodes column source data encoded as lists or base64 strings.
def from_json(self, json, models=None): ''' Decodes column source data encoded as lists or base64 strings. ''' if json is None: return None elif not isinstance(json, dict): raise DeserializationError("%s expected a dict or None, got %s" % (self, json)) new...
Some property types need to wrap their values in special containers etc.
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, dict): if isinstance(value, PropertyValueColumnData): return value else: return PropertyValueColumnData(value) ...
Convert any recognized timedelta value to floating point absolute milliseconds.
def convert_timedelta_type(obj): ''' Convert any recognized timedelta value to floating point absolute milliseconds. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' if isinstance(obj, dt.timedelta): return obj.total_seconds() * 1000. eli...
Convert any recognized date time or datetime value to floating point milliseconds since epoch.
def convert_datetime_type(obj): ''' Convert any recognized date, time, or datetime value to floating point milliseconds since epoch. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' # Pandas NaT if pd and obj is pd.NaT: return np.nan ...
Convert NumPy datetime arrays to arrays to milliseconds since epoch.
def convert_datetime_array(array): ''' Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array ''' ...
Return a new unique ID for a Bokeh object.
def make_id(): ''' Return a new unique ID for a Bokeh object. Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overr...
Transform a NumPy arrays into serialized format
def transform_array(array, force_list=False, buffers=None): ''' Transform a NumPy arrays into serialized format Converts un-serializable dtypes and returns JSON serializable format Args: array (np.ndarray) : a NumPy array to be transformed force_list (bool, optional) : whether to only ...
Transforms a NumPy array into a list of values
def transform_array_to_list(array): ''' Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to transform Returns: list or dict ''' if (array.dtype.kind in ('u', 'i', 'f') and (~np.isfinite(array)).any()): transformed = array.as...
Transforms a Pandas series into serialized form
def transform_series(series, force_list=False, buffers=None): ''' Transforms a Pandas series into serialized form Args: series (pd.Series) : the Pandas series to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes usi...
Transforms a NumPy array into serialized form.
def serialize_array(array, force_list=False, buffers=None): ''' Transforms a NumPy array into serialized form. Args: array (np.ndarray) : the NumPy array to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a ...
Recursively traverse an object until a flat list is found.
def traverse_data(obj, use_numpy=True, buffers=None): ''' Recursively traverse an object until a flat list is found. If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle ``nan``, ``inf``, and ``-inf``. Otherwise, iterate through all items, co...
Transform ColumnSourceData data to a serialized format
def transform_column_source_data(data, buffers=None, cols=None): ''' Transform ``ColumnSourceData`` data to a serialized format Args: data (dict) : the mapping of names to data columns to transform buffers (set, optional) : If binary buffers are desired, the buffers parameter may b...
Send a numpy array as an unencoded binary buffer
def encode_binary_dict(array, buffers): ''' Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype...
Decode a base64 encoded array into a NumPy array.
def decode_base64_dict(data): ''' Decode a base64 encoded array into a NumPy array. Args: data (dict) : encoded array data to decode Data should have the format encoded by :func:`encode_base64_dict`. Returns: np.ndarray ''' b64 = base64.b64decode(data['__ndarray__']) arra...
Create a CustomJSHover instance from a Python functions. The function is translated to JavaScript using PScript.
def from_py_func(cls, code): ''' Create a ``CustomJSHover`` instance from a Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It is possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword ...
Create a CustomJSHover instance from a CoffeeScript snippet. The function bodies are translated to JavaScript functions using node and therefore require return statements.
def from_coffeescript(cls, code, args={}): ''' Create a CustomJSHover instance from a CoffeeScript snippet. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``code`` snippet namespace will contain the variable ``value`` (...
Required Sphinx extension setup function.
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node( bokehjs_content, html=( html_visit_bokehjs_content, html_depart_bokehjs_content ) ) app.add_directive('bokehjs-content', BokehJSContent)
this is copied from sphinx. directives. code. CodeBlock. run
def get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an arguments instead of reading from self """ # type: () -> List[nodes.Node] document = self.state.document ...
This is largely copied from bokeh. sphinxext. bokeh_plot. run
def get_code_language(self): """ This is largely copied from bokeh.sphinxext.bokeh_plot.run """ js_source = self.get_js_source() if self.options.get("include_html", False): resources = get_sphinx_resources(include_bokehjs_api=True) html_source = BJS_HTML.r...
Return JavaScript code and a script tag that can be used to embed Bokeh Plots.
def autoload_static(model, resources, script_path): ''' Return JavaScript code and a script tag that can be used to embed Bokeh Plots. The data for the plot is stored directly in the returned JavaScript code. Args: model (Model or Document) : resources (Resources) : script_pa...
Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML.
def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc): ''' Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can be found in examples/embed/embed_multiple.py The returned components assume that BokehJS reso...
Return an HTML document that embeds Bokeh Model or Document objects.
def file_html(models, resources, title=None, template=FILE, template_variables={}, theme=FromCurdoc, suppress_callback_warning=False, _always_new=False): ''' Return an HTML document that embeds Bokeh Model or Document ...
Return a JSON block that can be used to embed standalone Bokeh content.
def json_item(model, target=None, theme=FromCurdoc): ''' Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must ...
Create a JSON string describing a patch to be applied as well as any optional buffers.
def process_document_events(events, use_buffers=True): ''' Create a JSON string describing a patch to be applied as well as any optional buffers. Args: events : list of events to be translated into patches Returns: str, list : JSON string which can be applied to make the given upda...
Dev API used to wrap the callback with decorators.
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return PeriodicCallback(self._document, new_callback, self._period, self._id)
Dev API used to wrap the callback with decorators.
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return TimeoutCallback(self._document, new_callback, self._timeout, self._id)
Generate a key to cache a custom extension implementation with.
def calc_cache_key(custom_models): ''' Generate a key to cache a custom extension implementation with. There is no metadata other than the Model classes, so this is the only base to generate a cache key. We build the model keys from the list of ``model.full_name``. This is not ideal but possibly a...
Create a bundle of selected models.
def bundle_models(models): """Create a bundle of selected `models`. """ custom_models = _get_custom_models(models) if custom_models is None: return None key = calc_cache_key(custom_models) bundle = _bundle_cache.get(key, None) if bundle is None: try: _bundle_cache[ke...
Returns CustomModels for models with a custom __implementation__
def _get_custom_models(models): """Returns CustomModels for models with a custom `__implementation__`""" if models is None: models = Model.model_class_reverse_map.values() custom_models = OrderedDict() for cls in models: impl = getattr(cls, "__implementation__", None) if impl i...
Returns the compiled implementation of supplied models.
def _compile_models(custom_models): """Returns the compiled implementation of supplied `models`. """ ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name) custom_impls = {} dependencies = [] for model in ordered_models: dependencies.extend(list(model.dependencie...
Create a JavaScript bundle with selected models.
def _bundle_models(custom_models): """ Create a JavaScript bundle with selected `models`. """ exports = [] modules = [] def read_json(name): with io.open(join(bokehjs_dir, "js", name + ".json"), encoding="utf-8") as f: return json.loads(f.read()) bundles = ["bokeh", "bokeh-api"...
Print an error message and exit.
def die(message, status=1): ''' Print an error message and exit. This function will call ``sys.exit`` with the given ``status`` and the process will terminate. Args: message (str) : error message to print status (int) : the exit status to pass to ``sys.exit`` ''' print(messag...
Return a Bokeh application built using a single handler for a script notebook or directory.
def build_single_handler_application(path, argv=None): ''' Return a Bokeh application built using a single handler for a script, notebook, or directory. In general a Bokeh :class:`~bokeh.application.application.Application` may have any number of handlers to initialize :class:`~bokeh.document.Document`...
Return a dictionary mapping routes to Bokeh applications built using single handlers for specified files or directories.
def build_single_handler_applications(paths, argvs=None): ''' Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_applicati...
A context manager to help print more informative error messages when a Server cannot be started due to a network problem.
def report_server_init_errors(address=None, port=None, **kwargs): ''' A context manager to help print more informative error messages when a ``Server`` cannot be started due to a network problem. Args: address (str) : network address that the server will be listening on port (int) : networ...
Distance between ( lat1 lon1 ) and ( lat2 lon2 ).
def distance(p1, p2): """Distance between (lat1, lon1) and (lat2, lon2). """ R = 6371 lat1, lon1 = p1 lat2, lon2 = p2 phi1 = radians(lat1) phi2 = radians(lat2) delta_lat = radians(lat2 - lat1) delta_lon = radians(lon2 - lon1) a = haversin(delta_lat) + cos(phi1) * cos(phi2) * haver...
Required Sphinx extension setup function.
def setup(app): ''' Required Sphinx extension setup function. ''' # These two are deprecated and no longer have any effect, to be removed 2.0 app.add_config_value('bokeh_plot_pyfile_include_dirs', [], 'html') app.add_config_value('bokeh_plot_use_relative_paths', False, 'html') app.add_directive('b...
Bind a socket to a port on an address.
def bind_sockets(address, port): ''' Bind a socket to a port on an address. Args: address (str) : An address to bind a port on, e.g. ``"localhost"`` port (int) : A port number to bind. Pass 0 to have the OS automatically choose a free port. This functi...
Check a given request host against a whitelist.
def check_whitelist(host, whitelist): ''' Check a given request host against a whitelist. Args: host (str) : A host string to compare against a whitelist. If the host does not specify a port, then ``":80"`` is implicitly assumed. whitelist (seq[str]) : ...
Match a host string against a pattern
def match_host(host, pattern): ''' Match a host string against a pattern Args: host (str) A hostname to compare to the given pattern pattern (str) A string representing a hostname pattern, possibly including wildcards for ip address octets or ports. Thi...
Notebook type acceptable values are jupyter as well as any names defined by external notebook hooks that have been installed.
def notebook_type(self, notebook_type): ''' Notebook type, acceptable values are 'jupyter' as well as any names defined by external notebook hooks that have been installed. ''' if notebook_type is None or not isinstance(notebook_type, string_types): raise ValueError("Noteboo...
Configure output to a standalone HTML file.
def output_file(self, filename, title="Bokeh Plot", mode="cdn", root_dir=None): ''' Configure output to a standalone HTML file. Calling ``output_file`` not clear the effects of any other calls to ``output_notebook``, etc. It adds an additional output destination (publishing to HTML file...
Save an HTML file with the data for the current document.
def save(obj, filename=None, resources=None, title=None, template=None, state=None, **kwargs): ''' Save an HTML file with the data for the current document. Will fall back to the default output state (or an explicitly provided :class:`State` object) for ``filename``, ``resources``, or ``title`` if they ...
Collect page names for the sitemap as HTML pages are built.
def html_page_context(app, pagename, templatename, context, doctree): ''' Collect page names for the sitemap as HTML pages are built. ''' site = context['SITEMAP_BASE_URL'] version = context['version'] app.sitemap_links.add(site + version + '/' + pagename + ".html")
Generate a sitemap. txt from the collected HTML page links.
def build_finished(app, exception): ''' Generate a ``sitemap.txt`` from the collected HTML page links. ''' filename = join(app.outdir, "sitemap.txt") links_iter = status_iterator(sorted(app.sitemap_links), 'adding links to sitemap... ', ...
Required Sphinx extension setup function.
def setup(app): ''' Required Sphinx extension setup function. ''' app.connect('html-page-context', html_page_context) app.connect('build-finished', build_finished) app.sitemap_links = set()
Start a Bokeh Server Tornado Application on a given Tornado IOLoop.
def initialize(self, io_loop): ''' Start a Bokeh Server Tornado Application on a given Tornado IOLoop. ''' self._loop = io_loop for app_context in self._applications.values(): app_context._loop = self._loop self._clients = set() self._stats_job = PeriodicC...
Provide a: class: ~bokeh. resources. Resources that specifies where Bokeh application sessions should load BokehJS resources from.
def resources(self, absolute_url=None): ''' Provide a :class:`~bokeh.resources.Resources` that specifies where Bokeh application sessions should load BokehJS resources from. Args: absolute_url (bool): An absolute URL prefix to use for locating resources. If None, ...
Start the Bokeh Server application.
def start(self): ''' 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. ''' sel...
Stop the Bokeh Server application.
def stop(self, wait=True): ''' Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (default: True) Returns: None ''' # TODO should probably close all connections and shut down all sessions here for context ...
Get an active a session by name application path and session ID.
def get_session(self, app_path, session_id): ''' 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) : ...
Gets all currently active sessions for an application.
def get_sessions(self, app_path): ''' 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] ''' ...
Internal shared implementation to handle both error and warning validation checks.
def _validator(code_or_name, validator_type): ''' 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: validat...
Query a collection of Bokeh models and yield any that match the a selector.
def find(objs, selector, context=None): ''' 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 : o...
Test whether a given Bokeh model matches a given selector.
def match(obj, selector, context=None): ''' 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 mat...
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.
def default_filename(ext): ''' 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...
Attempt to return the filename of the currently running Python process
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 filename = None frame = inspect.currentframe() try: while frame.f_back and frame.f_globals.get('name') != '_...
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.
def other_args(cls): ''' 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-bl...
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, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist. """ result = dict() # TODO: The need to do...
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): tool_fn = _known_tools[tool_fn] return ...
Adds tools to the plot object
def _process_tools_arg(plot, tools, tooltips=None): """ 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....
Adds tools to the plot object
def _process_active_tools(toolbar, tool_map, active_drag, active_inspect, active_scroll, active_tap): """ 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 ...
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.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 releas...
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(): if self._socket.protocol is None: # Tornado is maybe supposed to do this, ...
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(), key=lambda arg: arg[0]): external = getattr(cls, resource_attr, ...
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' : logging.INFO, 'warn' ...
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 = None else: self._secret_key_b...
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, '..', 'bokehjs', 'src')) if isdir(bokehjssrcdir): return bok...