Python bokeh.models.widgets.Div() Examples

The following are 12 code examples of bokeh.models.widgets.Div(). 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.widgets , or try the search function .
Example #1
Source File: main.py    From flight_review with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def show_exception_page():
            """ show an error page in case of an unknown/unhandled exception """
            title = 'Internal Error'

            error_message = ('<h3>Internal Server Error</h3>'
                             '<p>Please open an issue on <a '
                             'href="https://github.com/PX4/flight_review/issues" target="_blank">'
                             'https://github.com/PX4/flight_review/issues</a> with a link '
                             'to this log.')
            div = Div(text=error_message, width=int(plot_width*0.9))
            plots = [widgetbox(div, width=int(plot_width*0.9))]
            curdoc().template_variables['internal_error'] = True
            return (title, error_message, plots)


        # check which plots to show 
Example #2
Source File: __init__.py    From parambokeh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _update_trait(self, p_name, p_value, widget=None):
        widget = self._widgets[p_name] if widget is None else widget
        if isinstance(p_value, tuple):
            p_value, size = p_value
        if isinstance(widget, Div):
            widget.text = p_value
        else:
            if widget.children:
                widget.children.remove(widget.children[0])
            widget.children.append(p_value) 
Example #3
Source File: master_app.py    From estimagic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _setup_tabs(sec_to_elements):
    """Create tabs for each section in sec_to_elements with titles.

    Args:
        sec_to_elements (dict): A nested dictionary. The first level keys will be the
        sections ("running", "succeeded", "failed", "scheduled"). The second level keys
        are the database names and the second level values a list consisting of the
        link to the dashboard and a button to activate tha dashboard.

    Returns:
        tabs (bokeh.models.Tabs): a tab for every section in sec_to_elements.

    """
    tab_list = []
    for section, name_to_row in sec_to_elements.items():
        text = f"{len(name_to_row.column_names)} optimizations {section}"
        table_rows = [Row(Div(text=text, width=400), name=f"{section}_how_many")]
        for name, row in name_to_row.data.items():
            table_rows.append(Row(*row, name=name))
        panel = Panel(
            child=Column(*table_rows, name=f"{section}_col"),
            title=section.capitalize(),
            name=f"{section}_panel",
        )
        tab_list.append(panel)
    tabs = Tabs(tabs=tab_list, name="tabs")
    return tabs 
Example #4
Source File: utilities.py    From estimagic with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_dashboard_link(name):
    """Create a link refering to *name*'s monitoring app.

    Args:
        name (str): Uniqe name of the database.

    Returns:
        div (bokeh.models.widgets.Div): Link to the database's monitoring page.
    """
    div_name = f"link_{name}"
    open_in_new_tab = r'target="_blank"'
    text = f"<a href=./{name} {open_in_new_tab}> {name}!</a>"
    div = Div(text=text, name=div_name, width=400)
    return div 
Example #5
Source File: bokeh.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def generate_model(self, figurepage_idx: int = 0) -> Model:
        """Returns a model generated from internal blueprints"""
        if figurepage_idx >= len(self.figurepages):
            raise RuntimeError(f'Cannot generate model for FigurePage with index {figurepage_idx} as there are only {len(self.figurepages)}.')

        figurepage = self.figurepages[figurepage_idx]
        if not self._is_optreturn:
            tabs = self.generate_model_tabs(figurepage)
        else:
            tabs = []

        # now append analyzer tab(s)
        analyzers = figurepage.analyzers
        panel_analyzer = self.get_analyzer_panel(analyzers)
        if panel_analyzer is not None:
            tabs.append(panel_analyzer)

        # append meta tab
        if not self._is_optreturn:
            assert figurepage.strategy is not None
            meta = Div(text=metadata.get_metadata_div(figurepage.strategy))
            metapanel = Panel(child=meta, title="Meta")
            tabs.append(metapanel)

        model = Tabs(tabs=tabs)

        # attach the model to the underlying figure for later reference (e.g. unit test)
        figurepage.model = model

        return model 
Example #6
Source File: liveclient.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, doc: Document, push_fnc, bokeh_fac: callable, push_data_fnc:callable, strategy: bt.Strategy, figurepage_idx: int = 0, lookback: int = 20):
        self._slider_aspectratio = None
        self._push_data_fnc = push_data_fnc
        self._push_fnc = push_fnc
        self._figurepage_idx = figurepage_idx
        self.last_data_index = -1
        self._lookback = lookback
        self._strategy = strategy
        self._current_group = None
        self.document = doc

        self._bokeh_fac = bokeh_fac
        self._bokeh = None

        bokeh = self._bokeh_fac()  # temporary bokeh object to get tradingdomains and scheme
        self._scheme = copy(bokeh.p.scheme)  # preserve original scheme as originally provided by the user

        tradingdomains = bokeh.list_tradingdomains(strategy)
        self._current_group = tradingdomains[0]
        self._select_tradingdomain = Select(value=self._current_group, options=tradingdomains)
        self._select_tradingdomain.on_change('value', self._on_select_group)

        btn_refresh_analyzers = Button(label='Refresh Analyzers', width=100)
        btn_refresh_analyzers.on_click(self._on_click_refresh_analyzers)

        td_label = Div(text="Trading Domain:", margin=(9, 5, 15, 5))
        controls = row(children=[td_label, self._select_tradingdomain, btn_refresh_analyzers])
        self.model = column(children=[controls, Tabs(tabs=[])], sizing_mode=self._scheme.plot_sizing_mode)

        # append meta tab
        meta = Div(text=metadata.get_metadata_div(strategy))
        self._panel_metadata = Panel(child=meta, title="Meta")

        self._refreshmodel() 
Example #7
Source File: liveclient.py    From backtrader_plotting with GNU General Public License v3.0 5 votes vote down vote up
def _get_config_panel(self):
        def on_change_checkbox(vals):
            for i, f in enumerate(self._bokeh.figurepages[0].figure_envs):
                if i > 1:
                    continue
                f.figure.visible = i in vals

        self._slider_aspectratio = Slider(value=self._scheme.plotaspectratio, start=0.1, end=10.0, step=0.1)

        button = Button(label="Save", button_type="success")
        button.on_click(self.on_button_save_config)

        r1 = row(children=[Div(text='Aspect Ratio', margin=(15, 10, 0, 10)), self._slider_aspectratio])

        return Panel(child=column(children=[r1, button]), title='Config') 
Example #8
Source File: plotted_tables.py    From flight_review with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_logged_messages(logged_messages, plot_width):
    """
    get a bokeh widgetbox object with a table of the logged text messages
    :param logged_messages: ulog.logged_messages
    """
    log_times = []
    log_levels = []
    log_messages = []
    for m in logged_messages:
        m1, s1 = divmod(int(m.timestamp/1e6), 60)
        h1, m1 = divmod(m1, 60)
        log_times.append("{:d}:{:02d}:{:02d}".format(h1, m1, s1))
        log_levels.append(m.log_level_str())
        log_messages.append(m.message)
    log_data = dict(
        times=log_times,
        levels=log_levels,
        messages=log_messages)
    source = ColumnDataSource(log_data)
    columns = [
        TableColumn(field="times", title="Time",
                    width=int(plot_width*0.15), sortable=False),
        TableColumn(field="levels", title="Level",
                    width=int(plot_width*0.1), sortable=False),
        TableColumn(field="messages", title="Message",
                    width=int(plot_width*0.75), sortable=False),
        ]
    data_table = DataTable(source=source, columns=columns, width=plot_width,
                           height=300, sortable=False, selectable=False)
    div = Div(text="""<b>Logged Messages</b>""", width=int(plot_width/2))
    return widgetbox(div, data_table, width=plot_width) 
Example #9
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_plot_size(plot):
    """
    Computes the size of bokeh models that make up a layout such as
    figures, rows, columns, widgetboxes and Plot.
    """
    if isinstance(plot, GridBox):
        ndmapping = NdMapping({(x, y): fig for fig, y, x in plot.children}, kdims=['x', 'y'])
        cols = ndmapping.groupby('x')
        rows = ndmapping.groupby('y')
        width = sum([max([compute_plot_size(f)[0] for f in col]) for col in cols])
        height = sum([max([compute_plot_size(f)[1] for f in row]) for row in rows])
        return width, height
    elif isinstance(plot, (Div, ToolbarBox)):
        # Cannot compute size for Div or ToolbarBox
        return 0, 0
    elif isinstance(plot, (Row, Column, WidgetBox, Tabs)):
        if not plot.children: return 0, 0
        if isinstance(plot, Row) or (isinstance(plot, ToolbarBox) and plot.toolbar_location not in ['right', 'left']):
            w_agg, h_agg = (np.sum, np.max)
        elif isinstance(plot, Tabs):
            w_agg, h_agg = (np.max, np.max)
        else:
            w_agg, h_agg = (np.max, np.sum)
        widths, heights = zip(*[compute_plot_size(child) for child in plot.children])
        return w_agg(widths), h_agg(heights)
    elif isinstance(plot, (Figure, Chart)):
        if plot.plot_width:
            width = plot.plot_width
        else:
            width = plot.frame_width + plot.min_border_right + plot.min_border_left
        if plot.plot_height:
            height = plot.plot_height
        else:
            height = plot.frame_height + plot.min_border_bottom + plot.min_border_top
        return width, height
    elif isinstance(plot, (Plot, DataTable, Spacer)):
        return plot.width, plot.height
    else:
        return 0, 0 
Example #10
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pad_width(model, table_padding=0.85, tabs_padding=1.2):
    """
    Computes the width of a model and sets up appropriate padding
    for Tabs and DataTable types.
    """
    if isinstance(model, Row):
        vals = [pad_width(child) for child in model.children]
        width = np.max([v for v in vals if v is not None])
    elif isinstance(model, Column):
        vals = [pad_width(child) for child in model.children]
        width = np.sum([v for v in vals if v is not None])
    elif isinstance(model, Tabs):
        vals = [pad_width(t) for t in model.tabs]
        width = np.max([v for v in vals if v is not None])
        for model in model.tabs:
            model.width = width
            width = int(tabs_padding*width)
    elif isinstance(model, DataTable):
        width = model.width
        model.width = int(table_padding*width)
    elif isinstance(model, (WidgetBox, Div)):
        width = model.width
    elif model:
        width = model.plot_width
    else:
        width = 0
    return width 
Example #11
Source File: __init__.py    From parambokeh with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def widgets(self):
        """Return name,widget boxes for all parameters (i.e., a property sheet)"""

        params = self.parameterized.params().items()
        key_fn = lambda x: x[1].precedence if x[1].precedence is not None else self.p.default_precedence
        sorted_precedence = sorted(params, key=key_fn)
        outputs = [k for k, p in sorted_precedence if isinstance(p, _View)]
        filtered = [(k,p) for (k,p) in sorted_precedence
                    if ((p.precedence is None) or (p.precedence >= self.p.display_threshold))
                    and k not in outputs]
        groups = itertools.groupby(filtered, key=key_fn)
        sorted_groups = [sorted(grp) for (k,grp) in groups]
        ordered_params = [el[0] for group in sorted_groups for el in group]

        # Format name specially
        ordered_params.pop(ordered_params.index('name'))
        widgets = [Div(text='<b>{0}</b>'.format(self.parameterized.name))]

        def format_name(pname):
            p = self.parameterized.params(pname)
            # omit name for buttons, which already show the name on the button
            name = "" if issubclass(type(p),param.Action) else pname
            return Div(text=name)

        if self.p.show_labels:
            widgets += [self.widget(pname) for pname in ordered_params]
        else:
            widgets += [self.widget(pname) for pname in ordered_params]

        if self.p.button and not (self.p.callback is None and self.p.next_n==0):
            display_button = Button(label=self.p.button_text)
            def click_cb():
                # Execute and clear changes since last button press
                try:
                    self.execute(self._changed)
                except Exception as e:
                    self._changed.clear()
                    raise e
                self._changed.clear()
            display_button.on_click(click_cb)
            widgets.append(display_button)

        outputs = [self.widget(pname) for pname in outputs]
        return widgets, outputs 
Example #12
Source File: configurator_footprint.py    From CAVE with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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