Exemple #1
0
    def create_widget(self):
        # Toggle - Connect to LSL stream
        self.button_lsl = Toggle(label='Connect to LSL')
        self.button_lsl.on_click(self.on_lsl_connect_toggle)

        # Toggle - Start/stop LSL stream recording
        self.button_record = Toggle(label='Start Recording',
                                    button_type='primary')
        self.button_record.on_click(self.on_lsl_record_toggle)

        # Select - Choose pre-trained model
        self.select_model = Select(title="Select pre-trained model")
        self.select_model.options = self.available_models
        self.select_model.on_change('value', self.on_model_change)

        # Checkbox - Choose settings
        self.div_settings = Div(text='<b>Settings</b>', align='center')
        self.checkbox_settings = CheckboxButtonGroup(labels=['Show signal'])
        self.checkbox_settings.on_change('active', self.on_settings_change)

        # Select - Channel to visualize
        self.select_channel = Select(title='Select channel', value='1 - Fp1')
        self.select_channel.on_change('value', self.on_channel_change)

        # Plot - LSL EEG Stream
        self.plot_stream = figure(title='Temporal EEG signal',
                                  x_axis_label='Time [s]',
                                  y_axis_label='Amplitude',
                                  plot_height=500,
                                  plot_width=800,
                                  visible=False)
        self.plot_stream.line(x='ts', y='eeg', source=self.channel_source)

        # Plot - Chronogram prediction vs results
        self.plot_chronogram = figure(title='Chronogram',
                                      x_axis_label='Time [s]',
                                      y_axis_label='Action',
                                      plot_height=300,
                                      plot_width=800)
        self.plot_chronogram.cross(x='ts',
                                   y='y_pred',
                                   color='red',
                                   source=self.chrono_source,
                                   legend_label='Prediction')
        self.plot_chronogram.legend.background_fill_alpha = 0.6
        self.plot_chronogram.yaxis.ticker = list(self.pred_decoding.keys())
        self.plot_chronogram.yaxis.major_label_overrides = self.pred_decoding

        # Div - Display useful information
        self.model_info = Div(text=f'<b>Model:</b> None')
        self.pred_info = Div(text=f'<b>Prediction:</b> None')
        self.image = Div()

        # Create layout
        column1 = column(self.button_lsl, self.button_record,
                         self.select_model, self.select_channel,
                         self.div_settings, self.checkbox_settings)
        column2 = column(self.plot_stream, self.plot_chronogram)
        column3 = column(self.model_info, self.pred_info, self.image)
        return row(column1, column2, column3)
Exemple #2
0
def volplot_2(df1):
    #Data for volcano plot 2:
    df1=df1.dropna(how='any')
    df1 = df1[df1.Fold_change != 0] #remove rows where fold change is 0
    df1["Log_Fold_change"]=np.log2(df1["Fold_change"])
    df1["Log_p_value"]=-np.log10(df1["p_value"])
    #Volcano plot 2:
    source=ColumnDataSource(df1)
    vol_hover=HoverTool(tooltips=[('Kinase','@Kinase'), ('Substrate', '@Substrate'),
                                 ('Modified Residue','@Phosphosite'), ('Fold Change','@Fold_change'), ('p-value', '@p_value')])
    p2 = figure(plot_width=700, plot_height=500)
    p2.title.text="Volcano Plot of the Log Fold Change and Log p-value for All Identified Kinases"
    p2.title.text_font_size = "15px"
    p2.xaxis.axis_label ="Log Fold Change"
    p2.yaxis.axis_label ="-Log p-value"
    p2.scatter(x='Log_Fold_change', y='Log_p_value', source=source)
    p2.add_tools(vol_hover)
    #Significance thresholds:
    sig5=Span(location=1.3, dimension='width', line_color='#800000', line_width=1.75, line_dash='dashed') #5%
    sig1=Span(location=2, dimension='width', line_color='#2F4F4F', line_width=1.75, line_dash='dashed') #1%
    toggle1=Toggle(label='1% Significance', button_type="success", active=True)
    toggle1.js_link('active', sig1, 'visible')
    toggle2=Toggle(label='5% Significance', button_type="success", active=True)
    toggle2.js_link('active', sig5, 'visible')
    p2.add_layout(sig1) #adds horizontal line where points below line are non-sig fold changes(-log(0.05)=1.3)
    p2.add_layout(sig5)
    plot3=layout([p2], [toggle1, toggle2])
    return plot3
Exemple #3
0
 def _initialize_toggle_div(self):
     for space in self._spaces:            
         width = self._plot[space].plot_width
         height = 40
         sizing_mode = self._plot[space].sizing_mode
         label = self._name+" ~ "+self._data.get_var_dist(self._name)
         text = """parents: %s <br>dims: %s"""%(self._data.get_var_parents(self._name),list(self._data.get_idx_dimensions(self._name)))
         if sizing_mode == 'fixed':
             self._toggle[space] = Toggle(label = label,  active = False, 
             width = width, height = height, sizing_mode = sizing_mode, margin = (0,0,0,0))
             self._div[space] = Div(text = text,
             width = width, height = height, sizing_mode = sizing_mode, margin = (0,0,0,0), background=BORDER_COLORS[0] )
         elif sizing_mode == 'scale_width' or sizing_mode == 'stretch_width':
             self._toggle[space] = Toggle(label = label,  active = False, 
             height = height, sizing_mode = sizing_mode, margin = (0,0,0,0))   
             self._div[space] = Div(text = text,
             height = height, sizing_mode = sizing_mode, margin = (0,0,0,0), background=BORDER_COLORS[0] )         
         elif sizing_mode == 'scale_height' or sizing_mode == 'stretch_height':
             self._toggle[space] = Toggle(label = label,  active = False, 
             width = width, sizing_mode = sizing_mode, margin = (0,0,0,0)) 
             self._div[space] = Div(text = text,
             width = width, sizing_mode = sizing_mode, margin = (0,0,0,0), background=BORDER_COLORS[0] )
         else:
             self._toggle[space] = Toggle(label = label,  active = False, 
             sizing_mode = sizing_mode, margin = (0,0,0,0)) 
             self._div[space] = Div(text = text, sizing_mode = sizing_mode, margin = (0,0,0,0), background=BORDER_COLORS[0] )
         self._toggle[space].js_link('active', self._plot[space], 'visible')
Exemple #4
0
    def test_js_on_click_executes(self, bokeh_model_page: BokehModelPage) -> None:
        button = Toggle()
        button.js_on_click(CustomJS(code=RECORD("value", "cb_obj.active")))

        page = bokeh_model_page(button)

        button_el = find_element_for(page.driver, button, ".bk-btn")
        button_el.click()

        results = page.results
        assert results == {'value': True}

        button_el = find_element_for(page.driver, button, ".bk-btn")
        button_el.click()

        results = page.results
        assert results == {'value': False}

        button_el = find_element_for(page.driver, button, ".bk-btn")
        button_el.click()

        results = page.results
        assert results == {'value': True}

        assert page.has_no_console_errors()
Exemple #5
0
 def ajoute_toggle_extrémités(self) -> None:
     size = 4
     fill_color = "DarkSlateGray"
     self.g = (self.tron.set_index(
         self.tron_idx_name).geometry.boundary.dropna().explode().droplevel(
             1).rename("geometry").reset_index().reset_index())
     idx_g = self.g.columns[0]  # colonne qui contient le numéro de ligne
     self.src_extr = GeoJSONDataSource(geojson=self.g.to_json())
     self.filter_extr = IndexFilter(list(range(self.g.shape[0])))
     self.index_extrémités_par_tron = (
         self.tron.reset_index()  # numéro de ligne dans la colonne idx_g
         .merge(
             self.g, on=self.tron_idx_name
         )  # inner join donc tous les tronçons non localisés n'y sont pas
         .groupby(f"{idx_g}_x").apply(
             lambda s: list(s[f"{idx_g}_y"])).to_dict())
     view = CDSView(source=self.src_extr, filters=[self.filter_extr])
     self.extr_renderer = self.p.circle(
         x="x",
         y="y",
         size=size,
         fill_color=fill_color,
         line_color=fill_color,
         source=self.src_extr,
         visible=False,
         view=view,
     )
     self.toggle_extr = Toggle(label="Affiche les extrémités",
                               button_type="success",
                               width=100)
     self.toggle_extr.js_link("active", self.extr_renderer, "visible")
    def initialise_media_interface(self) -> None:
        self._trajectory_slider = Slider(
            title="Trajectory Index",
            value=0,
            start=0,
            end=max(len(self._trajectory), 1),
            step=1,
            width=self.controls_width,
        )
        self._trajectory_slider.on_change("value", self.update_frame)

        self._play_pause = Toggle(name="Play/Pause",
                                  label="Play/Pause",
                                  width=int(self.controls_width / 3))
        self._play_pause.on_click(self._play_pause_toggle)
        self._nextFrame = Button(label="Next",
                                 width=int(self.controls_width / 3))
        self._nextFrame.on_click(self._incr_index)
        self._prevFrame = Button(label="Previous",
                                 width=int(self.controls_width / 3))
        self._prevFrame.on_click(self._decr_index)
        self._increment_size = Slider(
            title="Increment Size",
            value=10,
            start=1,
            end=100,
            step=1,
            width=self.controls_width,
        )
Exemple #7
0
    def test_displays_label(self, bokeh_model_page: BokehModelPage) -> None:
        button = Toggle(label="label")

        page = bokeh_model_page(button)

        button = find_element_for(page.driver, button, ".bk-btn")
        assert button.text == "label"
Exemple #8
0
    def test_callback_property_executes(self, bokeh_model_page):
        button = Toggle(css_classes=['foo'])
        button.callback = CustomJS(code=RECORD("value", "cb_obj.active"))

        page = bokeh_model_page(button)

        button = page.driver.find_element_by_class_name('foo')
        button.click()

        results = page.results
        assert results == {'value': True}

        button = page.driver.find_element_by_class_name('foo')
        button.click()

        results = page.results
        assert results == {'value': False}

        button = page.driver.find_element_by_class_name('foo')
        button.click()

        results = page.results
        assert results == {'value': True}

        assert page.has_no_console_errors()
def test_custom_js_tick_formatter() -> None:
    source = ColumnDataSource({
        'fruits': ['apples', 'bananas', 'pears'],
        'counts': [6, 7, 3]
    })

    toggle = Toggle(label='Uppercase Ticks')

    formatter = bmf.CustomJSTickFormatter(code="""
        let label = source.data['fruits'][index];
        return toggle.active ? label.toUpperCase() : label
    """, args={'source': source, 'toggle': toggle})

    assert 'source' in formatter.args
    assert formatter.args['source'] is source
    assert 'toggle' in formatter.args
    assert formatter.args['toggle'] is toggle

    cutoff = 5

    formatter = bmf.CustomJSTickFormatter(code="""
        this.precision = this.precision || (ticks.length > cutoff ? 1 : 2);
        return Math.floor(tick) + " + " + (tick % 1).toFixed(this.precision);
    """, args={'cutoff': cutoff})

    assert 'cutoff' in formatter.args
    assert formatter.args['cutoff'] == cutoff

    with pytest.raises(AttributeError):
        # does not accept kwargs
        formatter = bmf.CustomJSTickFormatter(code="""
            this.precision = this.precision || (ticks.length > cutoff ? 1 : 2);
            return Math.floor(tick) + " + " + (tick % 1).toFixed(this.precision);
        """, cutoff=cutoff)
Exemple #10
0
    def test_displays_label(self, bokeh_model_page) -> None:
        button = Toggle(label="label", css_classes=["foo"])

        page = bokeh_model_page(button)

        button = page.driver.find_element_by_css_selector('.foo .bk-btn')
        assert button.text == "label"
Exemple #11
0
    def test_js_on_click_executes(self, bokeh_model_page) -> None:
        button = Toggle(css_classes=['foo'])
        button.js_on_click(CustomJS(code=RECORD("value", "cb_obj.active")))

        page = bokeh_model_page(button)

        button = page.driver.find_element_by_css_selector('.foo .bk-btn')
        button.click()

        results = page.results
        assert results == {'value': True}

        button = page.driver.find_element_by_css_selector('.foo .bk-btn')
        button.click()

        results = page.results
        assert results == {'value': False}

        button = page.driver.find_element_by_css_selector('.foo .bk-btn')
        button.click()

        results = page.results
        assert results == {'value': True}

        assert page.has_no_console_errors()
Exemple #12
0
    def _init_recorder(self):
        self.rec_button = Toggle(label=u"\u25CF  Record",
                                 button_type="default",
                                 active=False,
                                 width=210)
        self.file_name_widget = TextInput(value="test_file",
                                          title="File name:",
                                          width=210)
        self.file_type_widget = RadioGroup(labels=["EDF (BDF+)", "CSV"],
                                           active=0,
                                           width=210)

        columns = [
            widgets.TableColumn(
                field='timer',
                title="Record time",
                formatter=widgets.StringFormatter(text_align='center'))
        ]
        self.timer = widgets.DataTable(source=self._timer_source,
                                       index_position=None,
                                       sortable=False,
                                       reorderable=False,
                                       header_row=False,
                                       columns=columns,
                                       width=210,
                                       height=50,
                                       css_classes=["timer_widget"])

        self.rec_button.on_click(self._toggle_rec)
        return column(Spacer(width=210, height=5), self.file_name_widget,
                      self.file_type_widget, self.rec_button, self.timer)
Exemple #13
0
    def test_displays_button_type(self, typ, bokeh_model_page) -> None:
        button = Toggle(button_type=typ, css_classes=["foo"])

        page = bokeh_model_page(button)

        button = page.driver.find_element_by_css_selector('.foo .bk-btn')
        assert typ in button.get_attribute('class')
Exemple #14
0
 def _init_push2lsl(self):
     push2lsl_title = Div(text="""Push to LSL""", width=170, height=10)
     self.push2lsl_button = Toggle(label=u"\u25CF  Start", button_type="default", active=False,
                                   width=170, height=35)
     self.push2lsl_button.on_click(self._toggle_push2lsl)
     return column([Spacer(width=170, height=30), push2lsl_title, self.push2lsl_button],
                   width=170, height=200, sizing_mode='fixed')
Exemple #15
0
    def test_displays_button_type(self, typ, bokeh_model_page: BokehModelPage) -> None:
        button = Toggle(button_type=typ)

        page = bokeh_model_page(button)

        button = find_element_for(page.driver, button, ".bk-btn")
        assert typ in button.get_attribute('class')
Exemple #16
0
    def test_displays_button_type(self, typ, bokeh_model_page):
        button = Toggle(button_type=typ, css_classes=["foo"])

        page = bokeh_model_page(button)

        button_div = page.driver.find_element_by_class_name('foo')
        button = button_div.find_element_by_tag_name("button")
        assert typ in button.get_attribute('class')
Exemple #17
0
    def test_displays_label(self, bokeh_model_page):
        button = Toggle(label="label", css_classes=["foo"])

        page = bokeh_model_page(button)

        button_div = page.driver.find_element_by_class_name('foo')
        button = button_div.find_element_by_tag_name("button")
        assert button.text == "label"
Exemple #18
0
    def _add_cookie_saver_to_doc(self):
        """Adds a dummy bokeh widget to the bokeh document.

        This dummy widget can be used to store cookies using a JS callback.
        """
        cookie_saver = Toggle(visible=False, name="cookie_saver")
        cookie_saver.js_on_change("active", CustomJS(code=""))
        self._doc.add_root(cookie_saver)
 def createButtons(self, figNames):
     """helper function that creates all my toggle buttons based on FIGNAMES"""
     toggles = []
     for name in figNames:
         toggle = Toggle(label=name, active=True)
         toggleFunction = self.toggleFunction(toggle)
         toggle.on_click(toggleFunction)
         toggles.append(toggle)
     return toggles
Exemple #20
0
    def __init__(self):
        print('entrou')

        self.file = r'C:\Users\User\Desktop\teste_opencv\ch01_test.mp4'


        self.source_01 = ColumnDataSource(dict(time=[], value=[], mean=[], diff=[], cumulative=[]))
        self.img_source_01 = ColumnDataSource(dict(img=[]))

        fig_01 = figure(plot_height=150, plot_width=500, tools='xpan,xwheel_zoom,xbox_zoom,reset')
        fig_01.circle(x='time', y='value', source=self.source_01, legend_label='OPENCV READS', color=Spectral4[2])
        fig_01.step(x='time', y='diff', source=self.source_01, color=Spectral4[1], line_width=2, legend_label='DIFFERENCE')
        fig_01.legend.location = 'bottom_left'

        # fig_01.yaxis.axis_label = 'Hydrometer Value'

        fig_03 = figure(plot_height=200, plot_width=500, tools='xpan,xwheel_zoom,xbox_zoom,reset')
        fig_03.line(x='time', y='cumulative', source=self.source_01, line_width=2, color=Spectral4[3], legend_label='TOTAL VOLUME (L)')
        fig_03.legend.location = 'bottom_right'

        # fig_03.yaxis.axis_label = 'Total Volume (L)'

        fig_04 = figure(plot_height=200, plot_width=500, tools='xpan,xwheel_zoom,xbox_zoom,reset', y_range=(0,1))
        fig_04.line(x='time', y='mean', source=self.source_01, line_width=2, color=Spectral4[0], legend_label='FLOW RATE (L/s)')

        # fig_04.yaxis.axis_label = 'Flow Rate (L/s)'

        fig_02 = figure(plot_width=650, plot_height=500,
                        x_axis_type=None, y_axis_type=None, tools='pan,wheel_zoom,', name='image')
        fig_02.image_rgba('img', x=0, y=0, dw=140, dh=140, source=self.img_source_01)

        fig_01.toolbar.autohide = True
        fig_02.toolbar.autohide = True
        fig_03.toolbar.autohide = True
        fig_04.toolbar.autohide = True

        fig_04.xaxis.axis_label = 'Time (s)'

        self.toggle = Toggle(label='Run/Stop', button_type='success')

        self.t = dt.datetime.now()
        self.time_video = 0

        self.cumulative = 0

        div01 = Div(text='''<b>@AlexNAKobayashi</b>''', style={'font-size':'150%'})


        self.video = cv.VideoCapture(self.file)
        self.n_frame = 0

        self.rect_pts_BEFORE_np = np.float32([[628, 665], [752, 660], [750, 574], [626, 573]])
        self.rect_pts_AFTER = np.float32([[0,140],[140,140],[140,0],[0,0]])
        self.matrix = cv.getPerspectiveTransform(self.rect_pts_BEFORE_np, self.rect_pts_AFTER)

        curdoc().add_root(column(row(column(fig_02, div01),column(fig_01, fig_03, fig_04)), self.toggle))
        curdoc().add_periodic_callback(self._calc_analog_clock, 1)
def test_switch_to_linear_scale():
    button = Toggle(active=False)
    linear_plot = figure(name="linear_plot")
    log_plot = figure(name="log_plot")

    _switch_to_linear_scale(button=button,
                            linear_criterion_plot=linear_plot,
                            log_criterion_plot=log_plot)

    assert linear_plot.visible is True
    assert log_plot.visible is False
    assert button.button_type == "default"
Exemple #22
0
 def modify_doc(doc):
     source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
     plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
     plot.add_glyph(source, Circle(x='x', y='y', size=20))
     plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data"))))
     button = Toggle(css_classes=['foo'])
     def cb(value):
         if value:
             source.data=dict(x=[10, 20], y=[10, 10])
         else:
             source.data=dict(x=[100, 200], y=[100, 100])
     button.on_click(cb)
     doc.add_root(column(button, plot))
Exemple #23
0
 def create_direction_toggle(self) -> Toggle:
     direction = self.plot.glyph.direction
     active = self.DIRECTION_TOGGLE_STATE[direction]
     toggle = Toggle(
         label=direction,
         button_type="primary",
         active=active,
         margin=(24, 0, 0, 5),
         width=100,
     )
     toggle.on_change("active", partial(self.handle_direction_change,
                                        toggle))
     return toggle
Exemple #24
0
    def test_server_on_click_round_trip(
            self, bokeh_server_page: BokehServerPage) -> None:
        button = Toggle()

        def modify_doc(doc):
            source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
            plot = Plot(height=400,
                        width=400,
                        x_range=Range1d(0, 1),
                        y_range=Range1d(0, 1),
                        min_border=0)
            plot.add_glyph(source, Circle(x='x', y='y', size=20))
            plot.tags.append(
                CustomJS(name="custom-action",
                         args=dict(s=source),
                         code=RECORD("data", "s.data")))

            def cb(event):
                if button.active:
                    source.data = dict(x=[10, 20], y=[10, 10])
                else:
                    source.data = dict(x=[100, 200], y=[100, 100])

            button.on_event('button_click', cb)
            doc.add_root(column(button, plot))

        page = bokeh_server_page(modify_doc)

        button_el = find_element_for(page.driver, button, ".bk-btn")
        button_el.click()

        page.eval_custom_action()

        results = page.results
        assert results == {'data': {'x': [10, 20], 'y': [10, 10]}}

        button_el = find_element_for(page.driver, button, ".bk-btn")
        button_el.click()

        page.eval_custom_action()

        results = page.results
        assert results == {'data': {'x': [100, 200], 'y': [100, 100]}}

        button_el = find_element_for(page.driver, button, ".bk-btn")
        button_el.click()

        page.eval_custom_action()

        results = page.results
        assert results == {'data': {'x': [10, 20], 'y': [10, 10]}}
    def createRowVal(self, text):

        select = Toggle(label='', width=config['select-width'], height=20)
        textData = Div(text=text, width=config['textData-width'], height=20)
        value = MultiChoice(value=[self.getLabel(text)],
                            options=self.labels,
                            width=config['label-width'])
        # value       = Select( title = '', value = self.getLabel(text), options=self.labels, width=config['label-width']  )

        result = row([select, value, textData], width=config['total-width'])

        self.rowVals.append(result)

        return result
Exemple #26
0
def toggle(filter_col, filter):
    title = re.sub(r'\s*[(]F[0-9]+[)]\s*', '', filter_col)
    class_select = title.replace(" ", "")
    title = title.upper()
    select_toggle = Toggle(
        label=title,
        width=175,
        name=class_select,
        active=True
        )

    select_toggle.js_link('active', filter, 'visible')

    return select_toggle
Exemple #27
0
    def __init__(self, controller):
        # Simulation controls
        self.agents = wrap(Slider(start=PARAMETERS['agents'][0], end=PARAMETERS['agents'][2],
                                  value=controller.params['agents'], step=1, title="Number of agents"), controller, 'agents')
        self.initial_immunity = wrap(Slider(start=PARAMETERS['initial_immunity'][0], end=PARAMETERS['initial_immunity'][2],
                                            value=controller.params['initial_immunity'] * 100, step=1, title="Initial immunity (%)"), controller, 'initial_immunity')

        self.simulation_controls.append(self.agents)
        self.simulation_controls.append(self.initial_immunity)

        # Disease controls
        self.sickness_proximity = wrap(Slider(start=PARAMETERS['sickness_proximity'][0], end=PARAMETERS['sickness_proximity'][2],
                                              value=controller.params['sickness_proximity'], step=1, title="Sickness proximity"), controller, "sickness_proximity")
        self.sickness_duration = wrap(Slider(start=PARAMETERS['sickness_duration'][0], end=PARAMETERS['sickness_duration'][2],
                                             value=controller.params['sickness_duration'], step=1, title="Sickness duration (ticks)"), controller, "sickness_duration")
        self.disease_controls.append(self.sickness_proximity)
        self.disease_controls.append(self.sickness_duration)

        # Response controls
        self.distancing_factor = wrap(Slider(start=PARAMETERS['distancing_factor'][0], end=PARAMETERS['distancing_factor'][2],
                                             value=controller.params['distancing_factor'] * 100, step=0.5, title="Physical distancing factor (%)"), controller, "distancing_factor")
        self.quarantine_delay = wrap(Slider(start=PARAMETERS['quarantine_delay'][0], end=PARAMETERS['quarantine_delay'][2],
                                            value=controller.params['quarantine_delay'], step=1, title="Quarantine delay (ticks)"), controller, "quarantine_delay")

        self.quarantine_toggle = Toggle(label="Quarantine enabled" if controller.params['quarantining'] else "Quarantine disabled",
                                        button_type="success" if controller.params['quarantining'] else "danger", active=controller.params['quarantining'])

        self.response_controls.append(self.distancing_factor)
        self.response_controls.append(self.quarantine_delay)
        self.response_controls.append(self.quarantine_toggle)

        def toggle_callback(event):
            controller.update_parameter(
                'quarantining', not controller.params['quarantining'])

            if controller.params['quarantining']:
                self.quarantine_toggle.label = "Quarantine enabled"
                self.quarantine_toggle.button_type = "success"

                controller.update_parameter(
                    'quarantine_delay', controller.params['quarantine_delay'])
            else:
                self.quarantine_toggle.label = "Quarantine disabled"
                self.quarantine_toggle.button_type = "danger"

            controller.reset()

        self.quarantine_toggle.on_click(toggle_callback)
Exemple #28
0
    def visibility_button2(self):
        self.location_visibility_button = Toggle(label='Hide points',
                                                 button_type='success')
        assert not self.location_handles[1:]

        def set_visibility(multiline):
            return CustomJS(args=dict(multiline=multiline),
                            code="""
                    multiline.visible=!multiline.visible;
                    if (multiline.visible) {
                        this.label='Hide points';
                    } else {
                        this.label='Show points';
                    }
                    """)

        self.location_visibility_button.js_on_click(
            set_visibility(self.location_handles[0]))
        return self.location_visibility_button
Exemple #29
0
def _create_restart_button(
    doc,
    database,
    session_data,
    start_params,
    updating_options,
):
    """Create the button that restarts the convergence plots.

    Args:
        doc (bokeh.Document)
        database (sqlalchemy.MetaData): Bound metadata object.
        session_data (dict): dictionary with the last retrieved row id
        start_params (pd.DataFrame): See :ref:`params`
        updating_options (dict): Specification how to update the plotting data.
            It contains rollover, update_frequency, update_chunk, jump and stride.

    Returns:
        bokeh.layouts.Row

    """
    # (Re)start convergence plot button
    restart_button = Toggle(
        active=False,
        label="Start Updating",
        button_type="danger",
        width=200,
        height=30,
        name="restart_button",
    )
    restart_callback = partial(
        reset_and_start_convergence,
        session_data=session_data,
        doc=doc,
        database=database,
        button=restart_button,
        start_params=start_params,
        updating_options=updating_options,
    )
    restart_button.on_change("active", restart_callback)
    return restart_button
Exemple #30
0
    def collision(self, site, collision_time):

        code = '''object.visible = toggle.active'''
        #toggles = []
        
        for s, e in collision_time:
            print('start={}, end={}, tz={}'.format(s, e, site.timezone))
            s = pytz.timezone("US/Hawaii").localize(s)
            e = pytz.timezone("US/Hawaii").localize(e)

            #print('making callback...')
            #callback = CustomJS.from_coffeescript(code=code, args={})
            callback = CustomJS(code=code, args={})
            #print('making toggle...')
            toggle = Toggle(label="{}-{}".format(s.strftime("%Y-%m-%d %H:%M:%S"), e.strftime("%H:%M:%S")), button_type="default", active=True, callback=callback, width=20, height=25)
            self.toggles.append(toggle)
            #print('making laser annotation...')
            laser_collision = BoxAnnotation(left=s, right=e, bottom=self.y_min, top=self.y_max, fill_alpha=0.2, fill_color='magenta', line_color='magenta', line_alpha=0.2)
            #print('adding layout...') 
            self.fig.add_layout(laser_collision)
            callback.args = {'toggle': toggle, 'object': laser_collision}