def test_adding_next_tick_twice(self) -> None: with (LoopAndGroup()) as ctx: func = _make_invocation_counter(ctx.io_loop, stop_after=2) ctx.group.add_next_tick_callback(callback=func, callback_id=make_id()) ctx.group.add_next_tick_callback(callback=func, callback_id=make_id()) assert 2 == func.count()
def test_adding_periodic_twice(self) -> None: with (LoopAndGroup()) as ctx: func = _make_invocation_counter(ctx.io_loop, stop_after=2) ctx.group.add_periodic_callback(callback=func, period_milliseconds=3, callback_id=make_id()) ctx.group.add_periodic_callback(callback=func, period_milliseconds=2, callback_id=make_id()) assert 2 == func.count()
def test_same_callback_as_all_three_types(self) -> None: with (LoopAndGroup()) as ctx: func = _make_invocation_counter(ctx.io_loop, stop_after=5) # we want the timeout and next_tick to run before the periodic ctx.group.add_periodic_callback(callback=func, period_milliseconds=2, callback_id=make_id()) ctx.group.add_timeout_callback(callback=func, timeout_milliseconds=1, callback_id=make_id()) ctx.group.add_next_tick_callback(callback=func, callback_id=make_id()) assert 5 == func.count()
def _plot_to_json(plot): """Convert plot to JSON objects necessary for rendering with `bokehJS`. Parameters ---------- plot : bokeh.plotting.figure.Figure Bokeh plot object to be rendered. Returns ------- (str, str) Returns (docs_json, render_items) json for the desired plot. """ render_items = [{'docid': plot._id, 'elementid': make_id()}] doc = Document() doc.add_root(plot) docs_json_inner = doc.to_json() docs_json = {render_items[0]['docid']: docs_json_inner} docs_json = serialize_json(docs_json) render_items = serialize_json(render_items) custom_model_js = bundle_all_models() return docs_json, render_items, custom_model_js
def test_next_tick_does_not_run_if_removed_immediately(self) -> None: with (LoopAndGroup(quit_after=15)) as ctx: func = _make_invocation_counter(ctx.io_loop) cb_id = make_id() ctx.group.add_next_tick_callback(callback=func, callback_id=cb_id) ctx.group.remove_next_tick_callback(cb_id) assert 0 == func.count()
def _load_notebook_html(self, resources=None, hide_banner=False, load_timeout=5000): FINALIZE_JS = 'Bokeh.$("#%s").text("BokehJS is loading...");' from bokeh.core.templates import AUTOLOAD_NB_JS, NOTEBOOK_LOAD from bokeh.util.serialization import make_id from bokeh.resources import CDN if resources is None: resources = CDN element_id = make_id() js = AUTOLOAD_NB_JS.render(elementid='' if hide_banner else element_id, js_urls=resources.js_files, css_urls=resources.css_files, js_raw=resources.js_raw + [FINALIZE_JS % element_id], css_raw=resources.css_raw_str, force=1, timeout=load_timeout) return js
def html_for_render_items(docs_json, render_items, template=None, template_variables={}): json_id = make_id() json = escape(serialize_json(docs_json), quote=False) json = wrap_in_script_tag(json, "application/json", json_id) script = wrap_in_script_tag(script_for_render_items(json_id, render_items)) context = template_variables.copy() context.update( dict( title='', plot_script=json + script, docs=render_items, base=NB_TEMPLATE_BASE, macros=MACROS, )) if len(render_items) == 1: context["doc"] = context["docs"][0] context["roots"] = context["doc"].roots if template is None: template = NB_TEMPLATE_BASE elif isinstance(template, string_types): template = _env.from_string("{% extends base %}\n" + template) return template.render(context)
def test_periodic_does_not_run_if_removed_immediately(self) -> None: with (LoopAndGroup(quit_after=15)) as ctx: func = _make_invocation_counter(ctx.io_loop, stop_after=5) cb_id = make_id() ctx.group.add_periodic_callback(callback=func, period_milliseconds=1, callback_id=cb_id) ctx.group.remove_periodic_callback(cb_id) assert 0 == func.count()
def new_module(self): """Make a fresh module to run in.""" if self.failed: return None module_name = 'bk_script_' + make_id().replace('-', '') module = ModuleType(module_name) module.__dict__['__file__'] = os.path.abspath(self._path) return module
def test_remove_all_callbacks(self) -> None: with (LoopAndGroup(quit_after=15)) as ctx: # add a callback that will remove all the others def remove_all(): ctx.group.remove_all_callbacks() ctx.group.add_next_tick_callback(callback=remove_all, callback_id=make_id()) # none of these should run func = _make_invocation_counter(ctx.io_loop, stop_after=5) ctx.group.add_periodic_callback(callback=func, period_milliseconds=2, callback_id=make_id()) ctx.group.add_timeout_callback(callback=func, timeout_milliseconds=1, callback_id=make_id()) ctx.group.add_next_tick_callback(callback=func, callback_id=make_id()) assert 0 == func.count()
def test_removing_next_tick_twice(self) -> None: with (LoopAndGroup(quit_after=15)) as ctx: func = _make_invocation_counter(ctx.io_loop) cb_id = make_id() ctx.group.add_next_tick_callback(callback=func, callback_id=cb_id) ctx.group.remove_next_tick_callback(cb_id) with pytest.raises(ValueError) as exc: ctx.group.remove_next_tick_callback(cb_id) assert 0 == func.count() assert "twice" in repr(exc.value)
def test_next_tick_runs(self) -> None: with (LoopAndGroup()) as ctx: func = _make_invocation_counter(ctx.io_loop) assert 0 == len(ctx.group._next_tick_callback_removers) ctx.group.add_next_tick_callback(callback=func, callback_id=make_id()) assert 1 == len(ctx.group._next_tick_callback_removers) assert 1 == func.count() # check for leaks assert 0 == len(ctx.group._next_tick_callback_removers)
def doRender(self, handlerId): clientHasBokeh = self.options.get("nostore_bokeh", "false") == "true" if not clientHasBokeh: output_notebook(hide_banner=True) data = self.entity.getNextData() if data is None: return x = None y = None if isinstance(data, (list, np.ndarray)): x = list( range(self.windowSize) ) if self.glyphRenderer is None else self.glyphRenderer.data_source.data[ 'x'] y = data if self.glyphRenderer is None else self._concatArrays( self.glyphRenderer.data_source.data['y'], data) if len(y) < self.windowSize: y = [0] * (self.windowSize - len(y)) + y elif len(y) > self.windowSize: y = self._delWindowElements(y) elif isinstance(data, pandas.core.frame.DataFrame): pd = pd.drop(pd.index[[0]]) #pd.index = list(range(len(pd.index))) pd['x'] = list(range(len(pd.index))) else: x = data[0] y = data[1] if self.glyphRenderer is None: self.glyphRenderer = self.createGlyphRenderer(self.figure, x, y) else: self.updateGlyphRenderer(self.figure, self.glyphRenderer) if self.glyphRenderer is None: print("Error: no glyphRenderer found") return self.glyphRenderer.data_source.data['x'] = x self.glyphRenderer.data_source.data['y'] = y if not self.handleId: self.handleId = make_id() if self.figure not in _state.document.roots: _state.document.add_root(self.figure) target = notebook_div(self.figure, self.handleId) from IPython.display import display as ipythonDisplay, HTML, Javascript ipythonDisplay(HTML(target)) self.comms_handle = _CommsHandle(get_comms(self.handleId), _state.document, _state.document.to_json()) else: push_notebook(handle=self.comms_handle)
def test_removing_periodic_twice(self) -> None: with (LoopAndGroup(quit_after=15)) as ctx: func = _make_invocation_counter(ctx.io_loop, stop_after=5) cb_id = make_id() ctx.group.add_periodic_callback(callback=func, period_milliseconds=1, callback_id=cb_id) ctx.group.remove_periodic_callback(cb_id) with pytest.raises(ValueError) as exc: ctx.group.remove_periodic_callback(cb_id) assert 0 == func.count() assert "twice" in repr(exc.value)
def generate(self, references, buffers): if not isinstance(self.msg_data, bytes): msg = MessageSent(kind=self.kind, msg_type=self.msg_type, msg_data=self.msg_data) else: msg = MessageSentBuffers(kind=self.kind, msg_type=self.msg_type) assert buffers is not None buffer_id = make_id() buf = (dict(id=buffer_id), self.msg_data) buffers.append(buf) return msg
def _load_notebook_html(resources=None, verbose=False, hide_banner=False, load_timeout=5000): global _notebook_loaded from bokeh import __version__ from bokeh.core.templates import AUTOLOAD_NB_JS, NOTEBOOK_LOAD from bokeh.util.serialization import make_id from bokeh.util.compiler import bundle_all_models from bokeh.resources import CDN if resources is None: resources = CDN if resources.mode == 'inline': js_info = 'inline' css_info = 'inline' else: js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn'] if _notebook_loaded and verbose: warnings.append('Warning: BokehJS previously loaded') _notebook_loaded = resources element_id = make_id() html = NOTEBOOK_LOAD.render( element_id = element_id, verbose = verbose, js_info = js_info, css_info = css_info, bokeh_version = __version__, warnings = warnings, hide_banner = hide_banner, ) custom_models_js = bundle_all_models() js = AUTOLOAD_NB_JS.render( elementid = '' if hide_banner else element_id, js_urls = resources.js_files, css_urls = resources.css_files, js_raw = resources.js_raw + [custom_models_js] + ([] if hide_banner else [FINALIZE_JS % element_id]), css_raw = resources.css_raw_str, force = True, timeout = load_timeout ) return html, js
def create_header(cls, request_id=None): ''' 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 ''' header = {'msgid': bkserial.make_id(), 'msgtype': cls.msgtype} if request_id is not None: header['reqid'] = request_id return header
def test_periodic_runs(self) -> None: with (LoopAndGroup()) as ctx: func = _make_invocation_counter(ctx.io_loop, stop_after=5) assert 0 == len(ctx.group._periodic_callback_removers) cb_id = make_id() ctx.group.add_periodic_callback(callback=func, period_milliseconds=1, callback_id=cb_id) assert 1 == len(ctx.group._periodic_callback_removers) assert 5 == func.count() # check for leaks... periodic doesn't self-remove though assert 1 == len(ctx.group._periodic_callback_removers) ctx.group.remove_periodic_callback(cb_id) assert 0 == len(ctx.group._periodic_callback_removers)
def feature_scatterplot(fset_path, features_to_plot): """Create scatter plot of feature set. Parameters ---------- fset_path : str Path to feature set to be plotted. features_to_plot : list of str List of feature names to be plotted. Returns ------- (str, str) Returns (docs_json, render_items) json for the desired plot. """ fset, data = featurize.load_featureset(fset_path) fset = fset[features_to_plot] colors = cycle(palette[5]) plots = np.array([[figure(width=300, height=200) for j in range(len(features_to_plot))] for i in range(len(features_to_plot))]) for (j, i), p in np.ndenumerate(plots): if (j == i == 0): p.title.text = "Scatterplot matrix" p.circle(fset.values[:,i], fset.values[:,j], color=next(colors)) p.xaxis.minor_tick_line_color = None p.yaxis.minor_tick_line_color = None p.ygrid[0].ticker.desired_num_ticks = 2 p.xgrid[0].ticker.desired_num_ticks = 4 p.outline_line_color = None p.axis.visible = None plot = gridplot(plots.tolist(), ncol=len(features_to_plot), mergetools=True, responsive=True, title="Test") # Convert plot to json objects necessary for rendering with bokeh on the # frontend render_items = [{'docid': plot._id, 'elementid': make_id()}] doc = Document() doc.add_root(plot) docs_json_inner = doc.to_json() docs_json = {render_items[0]['docid']: docs_json_inner} docs_json = serialize_json(docs_json) render_items = serialize_json(render_items) return docs_json, render_items
def create_header(cls, request_id=None): ''' 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 ''' header = { 'msgid' : bkserial.make_id(), 'msgtype' : cls.msgtype } if request_id is not None: header['reqid'] = request_id return header
def build_script_tag(): elementid = make_id() relative_urls, url = settings.BOKEH_SERVE_SETTINGS[ 'relative_urls'], settings.BOKEH_SERVE_SETTINGS['url'] _session_id = session_id.generate_session_id( secret_key=settings.BOKEH_SECRET_KEY, signed=True) app_path = server._get_app_path(url) src_path = server._src_path(url, elementid) src_path += server._process_app_path(app_path) src_path += server._process_relative_urls(relative_urls, url) src_path += server._process_session_id(_session_id) src_path += server._process_resources('default') src_path += server._process_arguments(arguments) return server.encode_utf8( server.AUTOLOAD_TAG.render(src_path=src_path, app_path=app_path, elementid=elementid))
def create_header(cls, request_id: ID | None = None) -> Header: ''' 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 ''' header = Header( msgid=bkserial.make_id(), msgtype=cls.msgtype, ) if request_id is not None: header['reqid'] = request_id return header
def _load_notebook_html(self, resources=None, hide_banner=False, load_timeout=5000): from bokeh.core.templates import AUTOLOAD_NB_JS from bokeh.util.serialization import make_id from bokeh.resources import CDN if resources is None: resources = CDN element_id = make_id() js = AUTOLOAD_NB_JS.render( elementid = '' if hide_banner else element_id, js_urls = resources.js_files, css_urls = resources.css_files, js_raw = resources.js_raw, css_raw = resources.css_raw_str, force = 1, timeout = load_timeout ) return js
def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000): """加载 Bokeh 资源 :param resources: 目前不支持自定义静态资源的链接 :param verbose: 开启 Bokeh 日志 并显示 Bokeh 加载标签 :param hide_banner: 不支持 :param load_timeout: 不支持 :return: None """ from bokeh.util.serialization import make_id js_gists = ["console.log('Load BokehJS complete.')"] html = '' if verbose: element_id = make_id() html += """ <div class="bk-root"> <a href="https://bokeh.org" target="_blank" class="bk-logo bk-logo-small bk-logo-notebook"></a> <span id="{element_id}" style="font-family: Helvetica, Arial, sans-serif;font-size: 13px;">Loading BokehJS ...</span> </div> """.format(element_id=element_id) js_gists.append( "document.getElementById({element_id}).innerHTML = 'Load BokehJS complete.'" .format(element_id=element_id)) js_gists.append('Bokeh.set_log_level("info");') js_gists.append( "console.log('Set bokeh log level to INFO because you set `output_notebook(verbose=True)`')" ) put_html(requirejs_tpl % (html, '\n'.join(js_gists)), sanitize=False)
def test_default(self): bus._simple_id = 999 assert bus.make_id() == "1000" assert bus.make_id() == "1001" assert bus.make_id() == "1002"
def make_cb(cb): return ctx.group.add_next_tick_callback(cb, callback_id=make_id())
def test_simple_ids_yes(self): bus._simple_id = 999 os.environ["BOKEH_SIMPLE_IDS"] = "yes" assert bus.make_id() == "1000" assert bus.make_id() == "1001" assert bus.make_id() == "1002"
def test_simple_ids_no(self): os.environ["BOKEH_SIMPLE_IDS"] = "no" assert len(bus.make_id()) == 36 assert isinstance(bus.make_id(), str) del os.environ["BOKEH_SIMPLE_IDS"]
def __init__(self, label, callback): self.ref = "button-" + make_id() self.obj = Button(label=label, css_classes=[self.ref]) self.obj.js_on_event('button_click', callback)
def test_simple_ids_yes(self) -> None: bus._simple_id = 999 with envset(BOKEH_SIMPLE_IDS="yes"): assert bus.make_id() == "1000" assert bus.make_id() == "1001" assert bus.make_id() == "1002"
def test_simple_ids(self): import os os.environ["BOKEH_SIMPLE_IDS"] = "yes" self.assertEqual(make_id(), "1001") self.assertEqual(make_id(), "1002") del os.environ["BOKEH_SIMPLE_IDS"]
def test_id(): assert len(bus.make_id()) == 36 assert isinstance(bus.make_id(), str)
def test_id_with_simple_ids(): import os os.environ["BOKEH_SIMPLE_IDS"] = "yes" assert bus.make_id() == "1001" assert bus.make_id() == "1002" del os.environ["BOKEH_SIMPLE_IDS"]
def test_simple_ids_no(self) -> None: with envset(BOKEH_SIMPLE_IDS="no"): assert len(bus.make_id()) == 36 assert isinstance(bus.make_id(), str)
def test_basic(self): self.assertEqual(len(make_id()), 36) self.assertTrue(isinstance(make_id(), str))
def test_default(self) -> None: bus._simple_id = 999 assert bus.make_id() == "1000" assert bus.make_id() == "1001" assert bus.make_id() == "1002"