Python bokeh.models.CustomJS() Examples
The following are 11
code examples of bokeh.models.CustomJS().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
bokeh.models
, or try the search function
.
Example #1
Source File: bokeh.py From ipyvolume with MIT License | 6 votes |
def link_data_source_selection_to_widget(data_source, widget, trait_name): _ensure_widget_manager_hack() callback = CustomJS( args=dict(data=data_source), code=""" var indices = data.selected["1d"].indices var widget_id = '%s' if(jupyter_widget_manager) { // MYSTERY: if we use require, we end up at bokeh's require, which cannot find it, using requirejs it seems to work requirejs(["@jupyter-widgets/base"], function(widgets) { var widget_promise = widgets.unpack_models('IPY_MODEL_' +widget_id, jupyter_widget_manager) widget_promise.then(function(widget) { widget.set(%r, indices) widget.save_changes() }) }) } else { console.error("no widget manager") } """ % (widget.model_id, trait_name), ) data_source.selected.js_on_change("indices", callback)
Example #2
Source File: streams.py From EarthSim with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _create_vertex_split_link(self, action, poly_renderer, vertex_renderer, vertex_tool): cb = CustomJS(code=self.split_code, args={ 'poly': poly_renderer, 'vertex': vertex_renderer, 'tool': vertex_tool}) action.callback = cb
Example #3
Source File: __init__.py From parambokeh with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_customjs(self, change, p_name): """ Returns a CustomJS callback that can be attached to send the widget state across the notebook comms. """ data_template = "data = {{p_name: '{p_name}', value: cb_obj['{change}']}};" fetch_data = data_template.format(change=change, p_name=p_name) self_callback = JS_CALLBACK.format(comm_id=self.comm.id, timeout=self.timeout, debounce=self.debounce, plot_id=self.plot_id) js_callback = CustomJS(code='\n'.join([fetch_data, self_callback])) return js_callback
Example #4
Source File: plot.py From panel with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_model(self, doc, root=None, parent=None, comm=None): if root is None: return self._get_root(doc, comm) if self.object is None: model = BkSpacer() else: model = self.object properties = {} for p, value in self.param.get_param_values(): if (p not in Layoutable.param or p == 'name' or value is self.param[p].default): continue properties[p] = value model.update(**properties) if comm: self._wrap_bokeh_callbacks(root, model, doc, comm) ref = root.ref['id'] for js in model.select({'type': CustomJS}): js.code = js.code.replace(model.ref['id'], ref) if model._document and doc is not model._document: remove_root(model, doc) self._models[ref] = (model, parent) return model
Example #5
Source File: slider.py From panel with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_embed_state(self, root, values=None, max_opts=3): ref = root.ref['id'] w_model, parent = self._models[ref] _, _, doc, comm = state._views[ref] # Compute sampling start, end, step = w_model.start, w_model.end, w_model.step if values is None: span = end-start dtype = int if isinstance(step, int) else float if (span/step) > (max_opts-1): step = dtype(span/(max_opts-1)) values = [dtype(v) for v in np.arange(start, end+step, step)] elif any(v < start or v > end for v in values): raise ValueError('Supplied embed states for %s widget outside ' 'of valid range.' % type(self).__name__) # Replace model layout_opts = {k: v for k, v in self.param.get_param_values() if k in Layoutable.param and k != 'name'} dw = DiscreteSlider(options=values, name=self.name, **layout_opts) dw.link(self, value='value') self._models.pop(ref) index = parent.children.index(w_model) with config.set(embed=True): w_model = dw._get_model(doc, root, parent, comm) link = CustomJS(code=dw._jslink.code['value'], args={ 'source': w_model.children[1], 'target': w_model.children[0]}) parent.children[index] = w_model w_model = w_model.children[1] w_model.js_on_change('value', link) return (dw, w_model, values, lambda x: x.value, 'value', 'cb_obj.value')
Example #6
Source File: callbacks.py From geoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _create_vertex_split_link(self, action, poly_renderer, vertex_renderer, vertex_tool): cb = CustomJS(code=self.split_code, args={ 'poly': poly_renderer, 'vertex': vertex_renderer, 'tool': vertex_tool}) action.callback = cb
Example #7
Source File: test_embed.py From panel with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_embed_param_jslink(document, comm): select = Select(options=['A', 'B', 'C']) params = Param(select, parameters=['disabled']).layout panel = Row(select, params) with config.set(embed=True): model = panel.get_root(document, comm) embed_state(panel, model, document) assert len(document.roots) == 1 ref = model.ref['id'] cbs = list(model.select({'type': CustomJS})) assert len(cbs) == 2 cb1, cb2 = cbs cb1, cb2 = (cb1, cb2) if select._models[ref][0] is cb1.args['target'] else (cb2, cb1) assert cb1.code == """ var value = source['active']; value = value.indexOf(0) >= 0; value = value; try { var property = target.properties['disabled']; if (property !== undefined) { property.validate(value); } } catch(err) { console.log('WARNING: Could not set disabled on target, raised error: ' + err); return; } try { target['disabled'] = value; } catch(err) { console.log(err) } """ assert cb2.code == """ var value = source['disabled']; value = value; value = value ? [0] : []; try { var property = target.properties['active']; if (property !== undefined) { property.validate(value); } } catch(err) { console.log('WARNING: Could not set active on target, raised error: ' + err); return; } try { target['active'] = value; } catch(err) { console.log(err) } """
Example #8
Source File: test_embed.py From panel with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_embed_select_str_jslink(document, comm): select = Select(options=['A', 'B', 'C']) string = Str() select.link(string, value='object') panel = Row(select, string) with config.set(embed=True): model = panel.get_root(document, comm) embed_state(panel, model, document) assert len(document.roots) == 1 assert model is document.roots[0] ref = model.ref['id'] cbs = list(model.select({'type': CustomJS})) assert len(cbs) == 2 cb1, cb2 = cbs cb1, cb2 = (cb1, cb2) if select._models[ref][0] is cb1.args['source'] else (cb2, cb1) assert cb1.code == """ var value = source['value']; value = value; value = JSON.stringify(value).replace(/,/g, ", ").replace(/:/g, ": "); try { var property = target.properties['text']; if (property !== undefined) { property.validate(value); } } catch(err) { console.log('WARNING: Could not set text on target, raised error: ' + err); return; } try { target['text'] = value; } catch(err) { console.log(err) } """ assert cb2.code == """ var value = source['text']; value = value; value = value; try { var property = target.properties['value']; if (property !== undefined) { property.validate(value); } } catch(err) { console.log('WARNING: Could not set value on target, raised error: ' + err); return; } try { target['value'] = value; } catch(err) { console.log(err) } """
Example #9
Source File: test_embed.py From panel with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_embed_checkbox_str_jslink(document, comm): checkbox = Checkbox() string = Str() checkbox.link(string, value='object') panel = Row(checkbox, string) with config.set(embed=True): model = panel.get_root(document, comm) embed_state(panel, model, document) assert len(document.roots) == 1 assert model is document.roots[0] ref = model.ref['id'] cbs = list(model.select({'type': CustomJS})) assert len(cbs) == 2 cb1, cb2 = cbs cb1, cb2 = (cb1, cb2) if checkbox._models[ref][0] is cb1.args['source'] else (cb2, cb1) assert cb1.code == """ var value = source['active']; value = value.indexOf(0) >= 0; value = JSON.stringify(value).replace(/,/g, ", ").replace(/:/g, ": "); try { var property = target.properties['text']; if (property !== undefined) { property.validate(value); } } catch(err) { console.log('WARNING: Could not set text on target, raised error: ' + err); return; } try { target['text'] = value; } catch(err) { console.log(err) } """ assert cb2.code == """ var value = source['text']; value = value; value = value ? [0] : []; try { var property = target.properties['active']; if (property !== undefined) { property.validate(value); } } catch(err) { console.log('WARNING: Could not set active on target, raised error: ' + err); return; } try { target['active'] = value; } catch(err) { console.log(err) } """
Example #10
Source File: accordion.py From panel with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _get_objects(self, model, old_objects, doc, root, comm=None): """ Returns new child models for the layout while reusing unchanged models and cleaning up any dropped objects. """ from panel.pane.base import RerenderError, panel new_models = [] if len(self._names) != len(self): raise ValueError('Accordion names do not match objects, ensure ' 'that the Tabs.objects are not modified ' 'directly. Found %d names, expected %d.' % (len(self._names), len(self))) for i, (name, pane) in enumerate(zip(self._names, self)): pane = panel(pane, name=name) self.objects[i] = pane for obj in old_objects: if obj not in self.objects: self._panels[id(obj)]._cleanup(root) params = {k: v for k, v in self.param.get_param_values() if k in self._synced_properties} ref = root.ref['id'] current_objects = list(self) for i, (name, pane) in enumerate(zip(self._names, self)): params.update(self._apply_style(i)) if id(pane) in self._panels: card = self._panels[id(pane)] else: card = Card( pane, title=name, css_classes=['accordion'], header_css_classes=['accordion-header'] ) self._panels[id(pane)] = card card.param.set_param(**params) if ref in card._models: panel = card._models[ref][0] else: try: panel = card._get_model(doc, root, model, comm) if self.toggle: cb = CustomJS(args={'accordion': model}, code=self._toggle) panel.js_on_change('collapsed', cb) except RerenderError: return self._get_objects(model, current_objects[:i], doc, root, comm) new_models.append(panel) self._update_cards() return new_models
Example #11
Source File: configurator_footprint.py From CAVE with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _contour_radiobuttongroup(self, contour_data, color_mapper): """ Returns ------- radiobuttongroup: RadioButtonGroup radiobuttongroup widget to select one of the elements title: Div text-element to "show title" of widget """ labels = [l.replace('_', ' ') if l.startswith('budget') else l for l in contour_data.keys()] aliases = ['glyph' + str(i) for i in range(len(labels))] values = list(contour_data.values()) glyphs = [v[0] for v in values] mins = [v[1][0] for v in values] maxs = [v[1][1] for v in values] args = {name: glyph for name, glyph in zip(aliases, glyphs)} args['colormapper'] = color_mapper # Create javascript-code code = "var len_labels = " + str(len(aliases)) + "," code += "glyphs = [ " + ','.join(aliases) + '],' code += "mins = " + str(mins) + ',' code += "maxs = " + str(maxs) + ';' code += """ for (i = 0; i < len_labels; i++) { if (cb_obj.active === i) { // console.log('Setting to true: ' + i); glyphs[i].visible = true; colormapper.low = mins[i]; colormapper.high = maxs[i]; } else { // console.log('Setting to false: ' + i); glyphs[i].visible = false; } } """ # Create the actual checkbox-widget callback = CustomJS(args=args, code=code) radio = RadioButtonGroup(labels=labels, active=0, callback=callback) title = Div(text="Data used to estimate contour-plot") return radio, title