text
stringlengths
81
112k
Yields closed issues (closed after a given datetime) given a list of issues. def closed_issues(issues, after): """Yields closed issues (closed after a given datetime) given a list of issues.""" logging.info('finding closed issues after {}...'.format(after)) seen = set() for issue in issues: if ...
Yields unique set of issues given a list of issues. def all_issues(issues): """Yields unique set of issues given a list of issues.""" logging.info('finding issues...') seen = set() for issue in issues: if issue['title'] not in seen: seen.add(issue['title']) yield issue
Returns github API URL for querying tags. def get_issues_url(page, after): """Returns github API URL for querying tags.""" template = '{base_url}/{owner}/{repo}/issues?state=closed&per_page=100&page={page}&since={after}' return template.format(page=page, after=after.isoformat(), **API_PARAMS)
Parse ISO8601 timestamps given by github API. def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
Reads given URL as JSON and returns data as loaded python object. def read_url(url): """Reads given URL as JSON and returns data as loaded python object.""" logging.debug('reading {url} ...'.format(url=url)) token = os.environ.get("BOKEH_GITHUB_API_TOKEN") headers = {} if token: headers['Au...
Hits the github API for all closed issues after the given date, returns the data. def query_all_issues(after): """Hits the github API for all closed issues after the given date, returns the data.""" page = count(1) data = [] while True: page_data = query_issues(next(page), after) if not...
Given a list of tags, returns the datetime of the tag with the given name; Otherwise None. def dateof(tag_name, tags): """Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.""" for tag in tags: if tag['name'] == tag_name: commit = read_url(tag['commit'...
Gets data from query_func, optionally saving that data to a file; or loads data from a file. def get_data(query_func, load_data=False, save_data=False): """Gets data from query_func, optionally saving that data to a file; or loads data from a file.""" if hasattr(query_func, '__name__'): func_name = que...
Checks issues for BEP 1 compliance. def check_issues(issues, after=None): """Checks issues for BEP 1 compliance.""" issues = closed_issues(issues, after) if after else all_issues(issues) issues = sorted(issues, key=ISSUES_SORT_KEY) have_warnings = False for section, issue_group in groupby(issues,...
Returns log line for given issue. def issue_line(issue): """Returns log line for given issue.""" template = '#{number} {tags}{title}' tags = issue_tags(issue) params = { 'title': issue['title'].capitalize().rstrip('.'), 'number': issue['number'], 'tags': ' '.join('[{}]'.format(t...
Prints out changelog. def generate_changelog(issues, after, heading, rtag=False): """Prints out changelog.""" relevent = relevant_issues(issues, after) relevent = sorted(relevent, key=ISSUES_BY_SECTION) def write(func, endofline="", append=""): func(heading + '\n' + '-' * 20 + endofline) ...
Return a copy of this color value. Returns: :class:`~bokeh.colors.rgb.RGB` def copy(self): ''' Return a copy of this color value. Returns: :class:`~bokeh.colors.rgb.RGB` ''' return RGB(self.r, self.g, self.b, self.a)
Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` def to_css(self): ''' Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` ''' if self.a == 1.0: ...
Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` def to_hsl(self): ''' Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` ''' from .hsl import HSL # prevent circular ...
Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, then if the value inside the Future is another Future we yield until it's done as well, and so on. def yield_for_all_futures(result): """ Converts result into a Future by collapsing any f...
Removes all registered callbacks. def remove_all_callbacks(self): """ Removes all registered callbacks.""" for cb_id in list(self._next_tick_callback_removers.keys()): self.remove_next_tick_callback(cb_id) for cb_id in list(self._timeout_callback_removers.keys()): self.r...
Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback. def add_next_tick_callback(self, callback, callback_id=None): """ Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback.""" def ...
Adds a callback to be run once after timeout_milliseconds. Returns an ID that can be used with remove_timeout_callback. def add_timeout_callback(self, callback, timeout_milliseconds, callback_id=None): """ Adds a callback to be run once after timeout_milliseconds. Returns an ID that can be used...
Adds a callback to be run every period_milliseconds until it is removed. Returns an ID that can be used with remove_periodic_callback. def add_periodic_callback(self, callback, period_milliseconds, callback_id=None): """ Adds a callback to be run every period_milliseconds until it is removed. R...
Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. def bokeh_commit(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a Bokeh Github issue. Returns 2 par...
Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. def bokeh_issue(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a Bokeh Github issue. Returns 2 part...
Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags for releases, or to master otherwise. The link text is simply the URL path supplied, so typical usage might look like: .. code-block:: none All of the examples are located in the :bokeh-tree:`examples` subdirectory o...
Required Sphinx extension setup function. def setup(app): ''' Required Sphinx extension setup function. ''' app.add_role('bokeh-commit', bokeh_commit) app.add_role('bokeh-issue', bokeh_issue) app.add_role('bokeh-pull', bokeh_pull) app.add_role('bokeh-tree', bokeh_tree)
Return a link to a Bokeh Github resource. Args: app (Sphinx app) : current app rawtext (str) : text being replaced with link node. role (str) : role name kind (str) : resource type (issue, pull, etc.) api_type (str) : type for api link id : (str) : id of the resource...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists....
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 collected here. **This is an "out" paramete...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists. ''' ...
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnDataChanged' 'column_source' : <reference to a CDS> 'new' : <new data to steam to column_source> ...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_streamed`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_streamed`` if it exists. ''' super(...
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnsStreamed' 'column_source' : <reference to a CDS> 'data' : <new data to steam to column_source> ...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_patched`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_patched`` if it exists. ''' super(Co...
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: references (dict[str, Model]) : If the event ...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists....
Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists. def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exi...
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 develop (bool, optional) : whether the comm...
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 def show_help(bokehjs_action): ''' Print information about ext...
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 sdist, no action is taken. Note tha...
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 ``--install-js` is NOT. Returns: ...
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 signal that BokehJS is already pack...
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 wheel installed is not a fa...
Prompt users whether to build a new BokehJS or install an existing one. Returns: bool : True, if a new build is requested, False otherwise 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, F...
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 into the python source tre...
Copy built BokehJS files into the Python source tree. Returns: None 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 = jo...
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 from: https://www.redblobgames.com/grids/hexagons/#hex-to-pixel ...
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 array of x-coordinates to convert y (array[float]) : A ...
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: x (array[float]) : A NumPy array of x-coordinates for binnin...
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 r (array[float]) : ...
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 appropriately named parent directory def versions_from_parentdir(paren...
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE 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["dista...
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 ...
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 ...
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(...
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 ...
Convert any recognized timedelta value to floating point absolute milliseconds. Arg: obj (object) : the object to convert Returns: float : milliseconds def convert_timedelta_type(obj): ''' Convert any recognized timedelta value to floating point absolute milliseconds. Arg: ...
Convert any recognized date, time, or datetime value to floating point milliseconds since epoch. Arg: obj (object) : the object to convert Returns: float : milliseconds def convert_datetime_type(obj): ''' Convert any recognized date, time, or datetime value to floating point milli...
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 def convert_datetime_array(array): ''' Convert NumP...
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 overridden by setting the en...
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 output to standard lists This function can encode some d...
Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to transform Returns: list or dict def transform_array_to_list(array): ''' Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to tr...
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 using a binary encoding, but setting this argument to True wi...
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 binary encoding, but setting this argument to True will ...
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, converting non-JSON items Args: obj (list) : a list...
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 be provided, and any columns that may be sent as binary buffer...
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' : << dtype name >>, 'order' ...
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 def decode_base64_dict(data): ''' Decode a base64 encoded array into a NumPy array. Args: ...
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 arguments to the functions. ...
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`` (the untransformed value) at render time as well...
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', BokehJSConte...
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 def get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept...
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(in...
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_path (str) : Returns: (js, tag) : Jav...
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 resources are **already loaded**. The html template in which they will be embedded needs ...
Return an HTML document that embeds Bokeh Model or Document objects. The data for the plot is stored directly in the returned HTML, with support for customizing the JS/CSS resources independently and customizing the jinja2 template. Args: models (Model or Document or seq[Model]) : Bokeh object...
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 be supplied in the JavaScript call. theme (Th...
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 updates to obj as well as any optional buffers def process...
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. 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 better solution can be found found later. ...
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: ...
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: ...
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...
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....
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`` def die(message, status=1): ''' Print an error message a...
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` objects for new client sessions. However, in many cases on...
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_application` on each to generate the mapping. Args: path (...
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) : network address that the server will be listening on Example: .. c...
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 = ha...
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...
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 function returns a 2-tuple with the new socket ...
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]) : A list of host patterns to match again...
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. This function will return ``True`` if the ...
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 inst...
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 files). Any other active output modes continue to be active. Args: ...
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 are not provided. If the filename is not given and not provided via output state, it is derived fr...
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...
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), ...
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._loo...
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, relative URLs are used (default: None) ...