from .util import make_subheading alerts1 = dbc.Col( [ dbc.Alert("This is a primary alert", color="primary"), dbc.Alert("This is a secondary alert", color="secondary"), dbc.Alert("This is a success alert! Well done!", color="success"), dbc.Alert("This is a warning alert... be careful...", color="warning"), ], md=6, xs=12, ) alerts2 = dbc.Col( [ dbc.Alert("This is a danger alert. Scary!", color="danger"), dbc.Alert("This is an info alert. Good to know!", color="info"), dbc.Alert("This is a light alert", color="light"), dbc.Alert("This is a dark alert", color="dark"), ], md=6, xs=12, ) alerts = html.Div( [make_subheading("Alert", "alert"), dbc.Row([alerts1, alerts2])], className="mb-4", )
def test_msps001_basic_persistence(dash_dcc): app = Dash(__name__) app.layout = html.Div([ dcc.Checklist( id="checklist", options=[ { "label": "Slow 🐢", "value": "🐢" }, { "label": "Fast 🏎️", "value": "🏎️" }, { "label": "Faster 🚀", "value": "🚀" }, ], value=["🏎️"], persistence=True, ), dcc.DatePickerRange( id="datepickerrange", start_date="2017-08-21", end_date="2024-04-08", start_date_id="start_date", end_date_id="end_date", initial_visible_month="2019-05-01", persistence=True, ), dcc.DatePickerSingle(id="datepickersingle", date="2019-01-01", persistence=True), dcc.Dropdown( id="dropdownsingle", options=[ { "label": "One 1️⃣", "value": "1️⃣" }, { "label": "Two 2️⃣", "value": "2️⃣" }, { "label": "Three 3️⃣", "value": "3️⃣" }, ], value="2️⃣", persistence=True, ), dcc.Dropdown( id="dropdownmulti", options=[ { "label": "Four 4️⃣", "value": "4️⃣" }, { "label": "Five 5️⃣", "value": "5️⃣" }, { "label": "Six 6️⃣", "value": "6️⃣" }, ], value=["4️⃣"], multi=True, persistence=True, ), dcc.Input(id="input", value="yes", persistence=True), dcc.RadioItems( id="radioitems", options=[ { "label": "Red", "value": "r" }, { "label": "Green", "value": "g" }, { "label": "Blue", "value": "b" }, ], value="b", persistence=True, ), dcc.RangeSlider(id="rangeslider", min=0, max=10, step=1, value=[3, 7], persistence=True), dcc.Slider(id="slider", min=20, max=30, step=1, value=25, persistence=True), dcc.Tabs( id="tabs", children=[ dcc.Tab(label="Eh?", children="Tab A", value="A"), dcc.Tab(label="Bee", children="Tab B", value="B"), dcc.Tab(label="Sea", children="Tab C", value="C"), ], value="A", persistence=True, ), dcc.Textarea(id="textarea", value="knock knock", persistence=True), html.Div(id="settings"), ]) @app.callback( Output("settings", "children"), [ Input("checklist", "value"), Input("datepickerrange", "start_date"), Input("datepickerrange", "end_date"), Input("datepickersingle", "date"), Input("dropdownsingle", "value"), Input("dropdownmulti", "value"), Input("input", "value"), Input("radioitems", "value"), Input("rangeslider", "value"), Input("slider", "value"), Input("tabs", "value"), Input("textarea", "value"), ], ) def make_output(*args): return json.dumps(args) initial_settings = [ ["🏎️"], "2017-08-21", "2024-04-08", "2019-01-01", "2️⃣", ["4️⃣"], "yes", "b", [3, 7], 25, "A", "knock knock", ] dash_dcc.start_server(app) dash_dcc.wait_for_text_to_equal("#settings", json.dumps(initial_settings)) dash_dcc.find_element("#checklist label:last-child input").click() # 🚀 dash_dcc.select_date_range("datepickerrange", day_range=(4, )) dash_dcc.select_date_range("datepickerrange", day_range=(14, ), start_first=False) dash_dcc.find_element("#datepickersingle input").click() dash_dcc.select_date_single("datepickersingle", day="20") dash_dcc.find_element("#dropdownsingle .Select-input input").send_keys( "one" + Keys.ENTER) dash_dcc.find_element("#dropdownmulti .Select-input input").send_keys( "six" + Keys.ENTER) dash_dcc.find_element("#input").send_keys(" maybe") dash_dcc.find_element("#radioitems label:first-child input").click() # red range_slider = dash_dcc.find_element("#rangeslider") dash_dcc.click_at_coord_fractions(range_slider, 0.5, 0.25) # 5 dash_dcc.click_at_coord_fractions(range_slider, 0.8, 0.25) # 8 slider = dash_dcc.find_element("#slider") dash_dcc.click_at_coord_fractions(slider, 0.2, 0.25) # 22 dash_dcc.find_element("#tabs .tab:last-child").click() # C dash_dcc.find_element("#textarea").send_keys(Keys.ENTER + "who's there?") edited_settings = [ ["🏎️", "🚀"], "2019-05-04", "2019-05-14", "2019-01-20", "1️⃣", ["4️⃣", "6️⃣"], "yes maybe", "r", [5, 8], 22, "C", "knock knock\nwho's there?", ] dash_dcc.wait_for_text_to_equal("#settings", json.dumps(edited_settings)) # now reload the page - all of these settings should persist dash_dcc.wait_for_page() dash_dcc.wait_for_text_to_equal("#settings", json.dumps(edited_settings)) assert dash_dcc.get_logs() == []
def items(n): return [html.Div(id={"i": i}) for i in range(n)]
def test_rdls002_chained_loading_states(dash_duo): lock1, lock2, lock34 = Lock(), Lock(), Lock() app = Dash(__name__) def loading_wrapped_div(_id, color): return html.Div( dcc.Loading( html.Div( id=_id, style={ "width": 200, "height": 200, "backgroundColor": color }, ), className=_id, ), style={"display": "inline-block"}, ) app.layout = html.Div([ html.Button(id="button", children="Start", n_clicks=0), loading_wrapped_div("output-1", "hotpink"), loading_wrapped_div("output-2", "rebeccapurple"), loading_wrapped_div("output-3", "green"), loading_wrapped_div("output-4", "#FF851B"), ]) @app.callback(Output("output-1", "children"), [Input("button", "n_clicks")]) def update_output_1(n_clicks): with lock1: return "Output 1: {}".format(n_clicks) @app.callback(Output("output-2", "children"), [Input("output-1", "children")]) def update_output_2(children): with lock2: return "Output 2: {}".format(children) @app.callback( [Output("output-3", "children"), Output("output-4", "children")], [Input("output-2", "children")], ) def update_output_34(children): with lock34: return "Output 3: {}".format(children), "Output 4: {}".format( children) dash_duo.start_server(app) def find_spinners(*nums): if not nums: dash_duo.wait_for_no_elements(".dash-spinner") return for n in nums: dash_duo.find_element(".output-{} .dash-spinner".format(n)) assert len(dash_duo.find_elements(".dash-spinner")) == len(nums) def find_text(spec): templates = [ "Output 1: {}", "Output 2: Output 1: {}", "Output 3: Output 2: Output 1: {}", "Output 4: Output 2: Output 1: {}", ] for n, v in spec.items(): dash_duo.wait_for_text_to_equal("#output-{}".format(n), templates[n - 1].format(v)) find_text({1: 0, 2: 0, 3: 0, 4: 0}) find_spinners() btn = dash_duo.find_element("#button") # Can't use lock context managers here, because we want to acquire the # second lock before releasing the first lock1.acquire() btn.click() find_spinners(1) find_text({2: 0, 3: 0, 4: 0}) lock2.acquire() lock1.release() find_spinners(2) find_text({1: 1, 3: 0, 4: 0}) lock34.acquire() lock2.release() find_spinners(3, 4) find_text({1: 1, 2: 1}) lock34.release() find_spinners() find_text({1: 1, 2: 1, 3: 1, 4: 1})
import dash_bootstrap_components as dbc from dash import Input, Output, html standalone_radio_check = html.Div([ html.Div([ dbc.Checkbox( id="standalone-checkbox", label="This is a checkbox", value=False, ), dbc.Switch( id="standalone-switch", label="This is a toggle switch", value=False, ), dbc.RadioButton( id="standalone-radio", label="This is a radio button", value=False, ), ]), html.P(id="standalone-radio-check-output"), ]) @app.callback( Output("standalone-radio-check-output", "children"), [ Input("standalone-checkbox", "value"), Input("standalone-switch", "value"), Input("standalone-radio", "value"),
def load_panel(panel_n_clicks, current_contents): if current_contents or panel_n_clicks is None: raise PreventUpdate return html.Div(self.contents_layout(), id=self.id("inner_contents"))
app.layout = html.Div([ html.Div(children=[ html.Label('Dropdown'), dcc.Dropdown(['New York City', 'Montréal', 'San Francisco'], 'Montréal'), html.Br(), html.Label('Multi-Select Dropdown'), dcc.Dropdown(['New York City', 'Montréal', 'San Francisco'], ['Montréal', 'San Francisco'], multi=True), html.Br(), html.Label('Radio Items'), dcc.RadioItems(['New York City', 'Montréal', 'San Francisco'], 'Montréal'), ], style={ 'padding': 10, 'flex': 1 }), html.Div(children=[ html.Label('Checkboxes'), dcc.Checklist(['New York City', 'Montréal', 'San Francisco'], ['Montréal', 'San Francisco']), html.Br(), html.Label('Text Input'), dcc.Input(value='MTL', type='text'), html.Br(), html.Label('Slider'), dcc.Slider( min=0, max=9, marks={i: f'Label {i}' if i == 1 else str(i) for i in range(1, 6)}, value=5, ), ], style={ 'padding': 10, 'flex': 1 }) ], style={ 'display': 'flex', 'flex-direction': 'row' })
layout = html.Div(children=[ html.Div( className="container width60", children=[ html.H1(children="Quantum-robot Dashboard"), html.Div( className="row", children=[ dcc.Slider( id="refresh-slider", min=0, max=1, step=0.001, value=1), html.Div(id="refresh-slider-text"), ], ), html.H2(children="Bursts"), html.Div( className="row", children=[ dcc.Loading( className="loading", id="loading-bursts-bar", type="default", fullscreen=False, children=[ dcc.Graph(className="graph", id="bursts-bar") ], ), ], ), ], ), dcc.Interval( id="refresh-interval", interval=1, n_intervals=0 # (in milliseconds) ), ])
from sklearn import datasets from sklearn.cluster import KMeans iris_raw = datasets.load_iris() iris = pd.DataFrame(iris_raw["data"], columns=iris_raw["feature_names"]) app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) controls = dbc.Card( [ html.Div([ dbc.Label("X variable"), dcc.Dropdown( id="x-variable", options=[{ "label": col, "value": col } for col in iris.columns], value="sepal length (cm)", ), ]), html.Div([ dbc.Label("Y variable"), dcc.Dropdown( id="y-variable", options=[{ "label": col, "value": col } for col in iris.columns], value="sepal width (cm)", ),
def get_content(): # Load the data df = load_stats() # Check for empty data if df.empty: _txt = 'No stats loaded.' logging.debug(_txt) stats_content = html.Div( _txt, style={ 'padding-top': '100px', 'padding-bottom': '200px', 'padding-left': '400px', 'padding-right': '400px'} ) return stats_content # Make the graphs stats_graph_content = get_graph_content(df) # Get the rows and colums for the table stats_columns = [{"name": i, "id": i} for i in df.columns] print(df.columns) df.reset_index(inplace=True) stats_data = df.to_dict('rows') stats_content = [ dcc.Loading(id="loading-stats", children=[ html.Div(dcc.Tabs( id='tabs-stats', value='0', children=stats_graph_content, vertical=True))]), html.Button('Refresh Data', id='button-stats-refresh'), dcc.Dropdown( id='dropdown-stats-time', options=[ {'label': 'all time', 'value': 'ALL'}, {'label': '1 day', 'value': '1day'}, {'label': '1 week', 'value': '7day'}, {'label': '1 month', 'value': '30day'}, {'label': '1 year', 'value': '365day'}], value='ALL'), dcc.Dropdown( id='dropdown-stats-proj', multi=True, placeholder='Select Project(s)'), dcc.Dropdown( id='dropdown-stats-proc', multi=True, placeholder='Select Type(s)'), dcc.RadioItems( options=[ {'label': 'Row per Assessor', 'value': 'assr'}, #{'label': 'Session', 'value': 'sess'}, {'label': 'Row per Subject', 'value': 'subj'}], value='assr', id='radio-stats-pivot', labelStyle={'display': 'inline-block'}), dt.DataTable( columns=stats_columns, data=stats_data, filter_action='native', page_action='none', sort_action='native', id='datatable-stats', style_table={ 'overflowY': 'scroll', 'overflowX': 'scroll', 'width': '1000px'}, style_cell={ 'textAlign': 'left', 'padding': '5px 5px 0px 5px', 'width': '30px', 'overflow': 'hidden', 'textOverflow': 'ellipsis', 'height': 'auto', 'minWidth': '40', 'maxWidth': '60'}, style_header={ 'width': '80px', 'backgroundColor': 'white', 'fontWeight': 'bold', 'padding': '5px 15px 0px 10px'}, fill_width=False, export_format='xlsx', export_headers='names', export_columns='visible'), html.Label('0', id='label-rowcount')] return stats_content
def get_graph_content(df): tabs_content = [] tab_value = 0 box_width = 250 min_box_count = 4 logging.debug('get_stats_figure') # Check for empty data if len(df) == 0: logging.debug('empty data, using empty figure') return [plotly.subplots.make_subplots(rows=1, cols=1)] # Filter var list to only include those that have data var_list = [x for x in df.columns if not pd.isnull(df[x]).all()] # Filter var list to only stats variables, this also helps sort # by order in params yaml var_list = [x for x in data.get_variables() if x in var_list] # Determine how many boxplots we're making, depends on how many vars, use # minimum so graph doesn't get too small box_count = len(var_list) if box_count < min_box_count: box_count = min_box_count graph_width = box_width * box_count #print('box_count', box_count) #print('graph_width', graph_width) # Horizontal spacing cannot be greater than (1 / (cols - 1)) #hspacing = 1 / (box_count * 2) hspacing = 1 / (box_count * 4) #print('hspacing=', hspacing) # Make the figure with 1 row and a column for each var we are plotting fig = plotly.subplots.make_subplots( rows=1, cols=box_count, horizontal_spacing=hspacing, subplot_titles=var_list) # box plots # each proctype has specific set of fields to plot, # TODO: we need a dictionary listing them # then we just do the boxplots for the chosen proctypes (and maybe scan # types?, how did we do that for fmri scan type?) # Add traces to figure for i, var in enumerate(var_list): _row = 1 _col = i + 1 # Create boxplot for this var and add to figure fig.append_trace( go.Box( y=df[var], x=df['SITE'], boxpoints='all', text=df['assessor_label']), _row, _col) if var.startswith('con_') or var.startswith('inc_'): print(var, 'setting beta range') fig.update_yaxes(range=[-1,1], autorange=False) else: fig.update_yaxes(autorange=True) pass # Move the subtitles to bottom instead of top of each subplot for i in range(len(fig.layout.annotations)): fig.layout.annotations[i].update(y=-.15) #, font={'size': 18}) # Customize figure to hide legend and fit the graph fig.update_layout( showlegend=False, autosize=False, width=graph_width, margin=dict(l=20, r=40, t=40, b=80, pad=0)) # Build the tab # We set the graph to overflow and then limit the size to 1000px, this # makes the graph stay in a scrollable section label = 'ALL' graph = html.Div( dcc.Graph(figure=fig, style={'overflow': 'scroll'}), style={'width': '1000px'}) tab = dcc.Tab(label=label, value=str(tab_value), children=[graph]) tab_value += 1 # Append the tab tabs_content.append(tab) # Return the tabs return tabs_content
import dash_bootstrap_components as dbc from dash import Input, Output, html colorpicker = html.Div([ dbc.Label(["Select a ", html.Span("color", id="color")]), dbc.Input( type="color", id="colorpicker", value="#000000", style={ "width": 75, "height": 50 }, ), ]) app.clientside_callback( """ function(color) { return {"color": color} } """, Output("color", "style"), Input("colorpicker", "value"), ) # Regular Dash callback # @app.callback(Output("color", "style"), Input("colorpicker", "value")) # def update_text(color): # return {"color": color}
def test_graph_does_not_resize_in_tabs(dash_dcc, is_eager): app = Dash(__name__, eager_loading=is_eager) app.layout = html.Div([ html.H1("Dash Tabs component demo"), dcc.Tabs( id="tabs-example", value="tab-1-example", children=[ dcc.Tab(label="Tab One", value="tab-1-example", id="tab-1"), dcc.Tab(label="Tab Two", value="tab-2-example", id="tab-2"), dcc.Tab( label="Tab Three", value="tab-3-example", id="tab-3", disabled=True, disabled_className="disabled-tab", ), ], ), html.Div(id="tabs-content-example"), ]) @app.callback( Output("tabs-content-example", "children"), [Input("tabs-example", "value")], ) def render_content(tab): if tab == "tab-1-example": return html.Div([ html.H3("Tab content 1"), dcc.Graph( id="graph-1-tabs", figure={ "data": [{ "x": [1, 2, 3], "y": [3, 1, 2], "type": "bar" }] }, ), ]) elif tab == "tab-2-example": return html.Div([ html.H3("Tab content 2"), dcc.Graph( id="graph-2-tabs", figure={ "data": [{ "x": [1, 2, 3], "y": [5, 10, 6], "type": "bar" }] }, ), ]) dash_dcc.start_server(app) tab_one = dash_dcc.wait_for_element("#tab-1") tab_two = dash_dcc.wait_for_element("#tab-2") # wait for disabled tab with custom className dash_dcc.wait_for_element("#tab-3.disabled-tab") WebDriverWait(dash_dcc.driver, 10).until(EC.element_to_be_clickable((By.ID, "tab-2"))) # wait for Graph to be ready WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "#graph-1-tabs .main-svg"))) dash_dcc.percy_snapshot( "Tabs with Graph - initial (graph should not resize) ({})".format( "eager" if is_eager else "lazy")) tab_two.click() # wait for Graph to be ready WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "#graph-2-tabs .main-svg"))) dash_dcc.percy_snapshot( "Tabs with Graph - clicked tab 2 (graph should not resize) ({})". format("eager" if is_eager else "lazy")) WebDriverWait(dash_dcc.driver, 10).until(EC.element_to_be_clickable((By.ID, "tab-1"))) tab_one.click() # wait for Graph to be loaded after clicking WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "#graph-1-tabs .main-svg"))) dash_dcc.percy_snapshot( "Tabs with Graph - clicked tab 1 (graph should not resize) ({})". format("eager" if is_eager else "lazy")) assert dash_dcc.get_logs() == []
def test_tabs_render_without_selected(dash_dcc, is_eager): app = Dash(__name__, eager_loading=is_eager) menu = html.Div([html.Div("one", id="one"), html.Div("two", id="two")]) tabs_one = html.Div( [dcc.Tabs([dcc.Tab(dcc.Graph(id="graph-one"), label="tab-one-one")])], id="tabs-one", style={"display": "none"}, ) tabs_two = html.Div( [dcc.Tabs([dcc.Tab(dcc.Graph(id="graph-two"), label="tab-two-one")])], id="tabs-two", style={"display": "none"}, ) app.layout = html.Div([menu, tabs_one, tabs_two]) for i in ("one", "two"): @app.callback(Output("tabs-{}".format(i), "style"), [Input(i, "n_clicks")]) def on_click_update_tabs(n_clicks): if n_clicks is None: raise PreventUpdate if n_clicks % 2 == 1: return {"display": "block"} return {"display": "none"} @app.callback(Output("graph-{}".format(i), "figure"), [Input(i, "n_clicks")]) def on_click_update_graph(n_clicks): if n_clicks is None: raise PreventUpdate return { "data": [{ "x": [1, 2, 3, 4], "y": [4, 3, 2, 1] }], "layout": { "width": 700, "height": 450 }, } dash_dcc.start_server(app) button_one = dash_dcc.wait_for_element("#one") button_two = dash_dcc.wait_for_element("#two") button_one.click() # wait for tabs to be loaded after clicking WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "#graph-one .main-svg"))) time.sleep(1) dash_dcc.percy_snapshot( "Tabs-1 rendered ({})".format("eager" if is_eager else "lazy")) button_two.click() # wait for tabs to be loaded after clicking WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, "#graph-two .main-svg"))) time.sleep(1) dash_dcc.percy_snapshot( "Tabs-2 rendered ({})".format("eager" if is_eager else "lazy")) # do some extra tests while we're here # and have access to Graph and plotly.js check_graph_config_shape(dash_dcc) assert dash_dcc.get_logs() == []
def hello_world_example(app): app.layout = html.Div(children=[ html.H1("Hello World"), html.P("This is the first application. Yo") ])
def ensemble_layout( self, ensemble_id: str, ens_prev_id: str, ens_next_id: str, real_id: str, real_prev_id: str, real_next_id: str, ) -> wcc.FlexBox: return wcc.FlexBox(children=[ html.Div([ html.Label("Ensemble"), html.Div( style=self.set_grid_layout("12fr 1fr 1fr"), children=[ dcc.Dropdown( options=[{ "label": ens, "value": ens } for ens in self.ensembles], value=self.ensembles[0], id=ensemble_id, clearable=False, persistence=True, persistence_type="session", ), html.Button( style={ "fontSize": "2rem", "paddingLeft": "5px", "paddingRight": "5px", }, id=ens_prev_id, children="⬅", ), html.Button( style={ "fontSize": "2rem", "paddingLeft": "5px", "paddingRight": "5px", }, id=ens_next_id, children="➡", ), ], ), ]), html.Div(children=[ html.Label("Realization / Statistic"), html.Div( style=self.set_grid_layout("12fr 1fr 1fr"), children=[ dcc.Dropdown( options=[{ "label": real, "value": real } for real in self.realizations(self.ensembles[0]) ], value=self.realizations(self.ensembles[0])[0], id=real_id, clearable=False, persistence=True, persistence_type="session", ), html.Button( style={ "fontSize": "2rem", "paddingLeft": "5px", "paddingRight": "5px", }, id=real_prev_id, children="⬅", ), html.Button( style={ "fontSize": "2rem", "paddingLeft": "5px", "paddingRight": "5px", }, id=real_next_id, children="➡", ), ], ), ]), ])
import dash_bootstrap_components as dbc from dash import html textareas = html.Div( [ dbc.Textarea(className="mb-3", placeholder="A Textarea"), dbc.Textarea( valid=True, size="sm", className="mb-3", placeholder="A small, valid Textarea", ), dbc.Textarea( invalid=True, size="lg", placeholder="A large, invalid Textarea" ), ] )
def layout(self) -> html.Div: return html.Div( id=self.uuid("layout"), children=[ wcc.FlexBox( style={"fontSize": "1rem"}, children=[ html.Div( id=self.uuid("settings-view1"), style={ "margin": "10px", "flex": 4 }, children=[ self.selector.layout, self.ensemble_layout( ensemble_id=self.uuid("ensemble"), ens_prev_id=self.uuid("ensemble-prev"), ens_next_id=self.uuid("ensemble-next"), real_id=self.uuid("realization"), real_prev_id=self.uuid("realization-prev"), real_next_id=self.uuid("realization-next"), ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, id=self.uuid("settings-view2"), children=[ self.selector2.layout, self.ensemble_layout( ensemble_id=self.uuid("ensemble2"), ens_prev_id=self.uuid("ensemble2-prev"), ens_next_id=self.uuid("ensemble2-next"), real_id=self.uuid("realization2"), real_prev_id=self.uuid( "realization2-prev"), real_next_id=self.uuid( "realization2-next"), ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, id=self.uuid("settings-view3"), children=[ html.Label("Calculation"), html.Div( dcc.Dropdown( id=self.uuid("calculation"), value="Difference", clearable=False, options=[{ "label": i, "value": i } for i in [ "Difference", "Sum", "Product", "Quotient", ]], persistence=True, persistence_type="session", )), wcc.FlexBox(children=[ html.Div( style={ "width": "20%", "flex": 1 }, children=[ html.Label("Truncate Min"), dcc.Input( debounce=True, type="number", id=self.uuid( "truncate-diff-min"), persistence=True, persistence_type="session", ), ], ), html.Div( style={ "width": "20%", "flex": 1 }, children=[ html.Label("Truncate Max"), dcc.Input( debounce=True, type="number", id=self.uuid( "truncate-diff-max"), persistence=True, persistence_type="session", ), ], ), html.Label( style={"fontSize": "1.2rem"}, id=self.uuid("map3-label"), ), ]), ], ), ], ), wcc.FlexBox( style={"fontSize": "1rem"}, children=[ html.Div( style={ "height": self.map_height, "margin": "10px", "flex": 4, }, children=[ LeafletMap( syncedMaps=[ self.uuid("map2"), self.uuid("map3") ], id=self.uuid("map"), layers=[], unitScale={}, autoScaleMap=True, minZoom=-19, updateMode="replace", mouseCoords={"position": "bottomright"}, colorBar={"position": "bottomleft"}, switch={ "value": False, "disabled": False, "label": "Hillshading", }, ), ], ), html.Div( style={ "margin": "10px", "flex": 4 }, children=[ LeafletMap( syncedMaps=[ self.uuid("map"), self.uuid("map3") ], id=self.uuid("map2"), layers=[], unitScale={}, autoScaleMap=True, minZoom=-19, updateMode="replace", mouseCoords={"position": "bottomright"}, colorBar={"position": "bottomleft"}, switch={ "value": False, "disabled": False, "label": "Hillshading", }, ) ], ), html.Div( style={ "margin": "10px", "flex": 4 }, children=[ LeafletMap( syncedMaps=[ self.uuid("map"), self.uuid("map2") ], id=self.uuid("map3"), layers=[], unitScale={}, autoScaleMap=True, minZoom=-19, updateMode="replace", mouseCoords={"position": "bottomright"}, colorBar={"position": "bottomleft"}, switch={ "value": False, "disabled": False, "label": "Hillshading", }, ) ], ), dcc.Store( id=self.uuid("attribute-settings"), data=json.dumps(self.attribute_settings), storage_type="session", ), ], ), ], )
from dash import Dash, dcc, html import plotly.express as px import pandas as pd app = Dash(__name__) df = pd.DataFrame({ 'Fruit': ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"], "Amount": [4, 1, 2, 2, 4, 5], "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"] }) fig = px.bar(df, x="Fruit", y="Amount", color="City") app.layout = html.Div([ html.H1("Fruit Analysis App", style={'textAlign': 'center'}), dcc.Graph(id='example-graph', figure=fig) ], ) if __name__ == '__main__': app.run_server(debug=True)
sample_strengths_layout = [ dbc.CardHeader("Sample:診断結果"), sample_strengths_card ] layout_samples = dbc.Row( [ dbc.Col(dbc.Card(sample_mst_layout, color="dark", outline=True)), dbc.Col(dbc.Card(sample_strengths_layout, color="dark", outline=True)), ], className="mb-4", ) header_contents = html.Div([ html.H5('ストレングスファインダーの結果一覧をダウンロード', style=dict(padding="10px", borderLeft="5px #b31b1b solid")), html.P('') ]) considerations_contents = dbc.Alert([ html.H4("注意事項", className="alert-heading"), html.P("・本サイトからダウンロードしたデータには個人情報が含まれます。取り扱いには十分注意し、社外への情報共有は絶対に行わないでください"), html.P("・本サイトで収集したデータは、社内取り扱いのみに限定します"), html.P("・本サイトへのアクセスはBrainPadネットワークのみから許されています") ], color='warning') layout = html.Div([ header_contents, considerations_contents, layout_samples, Download(id="mst_download"), Download(id="strengths_download")
def test_rdls003_update_title(dash_duo, kwargs, expected_update_title, clientside_title): app = Dash("Dash", **kwargs) lock = Lock() app.layout = html.Div(children=[ html.H3("Press button see document title updating"), html.Div(id="output"), html.Button("Update", id="button", n_clicks=0), html.Button("Update Page", id="page", n_clicks=0), html.Div(id="dummy"), ]) if clientside_title: app.clientside_callback( """ function(n_clicks) { document.title = 'Page ' + n_clicks; return 'Page ' + n_clicks; } """, Output("dummy", "children"), [Input("page", "n_clicks")], ) @app.callback(Output("output", "children"), [Input("button", "n_clicks")]) def update(n): with lock: return n with lock: dash_duo.start_server(app) # check for update-title during startup # the clientside callback isn't blocking so it may update the title if not clientside_title: until(lambda: dash_duo.driver.title == expected_update_title, timeout=1) # check for original title after loading until( lambda: dash_duo.driver.title == "Page 0" if clientside_title else "Dash", timeout=1, ) with lock: dash_duo.find_element("#button").click() # check for update-title while processing callback if clientside_title and not kwargs.get("update_title", True): until(lambda: dash_duo.driver.title == "Page 0", timeout=1) else: until(lambda: dash_duo.driver.title == expected_update_title, timeout=1) if clientside_title: dash_duo.find_element("#page").click() dash_duo.wait_for_text_to_equal("#dummy", "Page 1") until(lambda: dash_duo.driver.title == "Page 1", timeout=1) # verify that when a separate callback runs, the page title gets restored dash_duo.find_element("#button").click() dash_duo.wait_for_text_to_equal("#output", "2") if clientside_title: until(lambda: dash_duo.driver.title == "Page 1", timeout=1) else: until(lambda: dash_duo.driver.title == "Dash", timeout=1)
app.layout = html.Div(children=[ html.H1(children="Hello Dash"), html.Div(children=""" Dash: A web application framework for Python. """), html.Br(), html.Div([ html.Label("Station:", id="station-label"), dcc.Dropdown( id="station-dropdown", options=[{ "label": i, "value": i } for i in df_stations.Stationsname.unique()], placeholder="Select weather station...", value="Essen-Bredeney", ), ]), html.Br(), html.Div([ html.Label("Year Slider", id="time-range-label"), dcc.RangeSlider( id="year-slider", min=df_weather["year"].min(), max=df_weather["year"].max(), value=[df_weather["year"].min(), df_weather["year"].max()], marks={ str(year): str(year) for year in df_weather["year"].unique() if year % 5 == 0 }, step=1, ), ]), html.Br(), html.Div([ html.Label("Period Slider", id="period-range-label"), dcc.RangeSlider( id="period-slider", min=df_weather["period_int"].min(), max=df_weather["period_int"].max(), value=[ df_weather["period_int"].min(), df_weather["period_int"].max(), ], marks={ str(period): str(period) for period in df_weather["period_int"].unique() # if period % 2 == 0 }, step=1, ), ]), dcc.Graph(id="temp_graph"), dcc.Graph(id="press_graph"), dcc.Graph(id="precip_graph"), dcc.Graph(id="cover_graph"), dcc.Graph(id="wind_mean_graph"), ])
import dash_bootstrap_components as dbc from dash.exceptions import PreventUpdate from dash.dependencies import Input, Output, State from . import tools as T graph_options = [{'label': 'Histograms', 'value': 'hist'}, {'label': 'Boxplots', 'value': 'boxplot'}, {'label': 'Probability Density', 'value': 'density'}] _label = 'Distributions' _layout = html.Div([ html.H3('Quality Control'), html.Button('Update', id='dist-update'), dcc.Dropdown(id='dist-graphs', options=graph_options, value=['hist'], multi=True, placeholder='Kinds of graphs'), dcc.Checklist(id='dist-select', options=[{'label': 'Dense', 'value': 'Dense'}], value=['Dense']), html.Div(id='dist-figures', style={'float': 'center'}) ]) layout_no_data = html.Div([ dcc.Markdown('''### No results generated yet. MINT has not been run yet. The Quality Control tabs uses the processed data. To generate it please add MS-files as well as a valid peaklist. Then execute MINT data processing routine witby clicking the `RUN MINT` button. Once results have been produced you can access the QC tools.'''), ]) def layout(): return _layout
import dash_bootstrap_components as dbc from dash import Input, Output, State, html modal = html.Div([ dbc.Button("Open modal", id="open-fs"), dbc.Modal( [ dbc.ModalHeader(dbc.ModalTitle("Fullscreen modal")), dbc.ModalBody("Wow this thing takes up a lot of space..."), ], id="modal-fs", fullscreen=True, ), ]) @app.callback( Output("modal-fs", "is_open"), Input("open-fs", "n_clicks"), State("modal-fs", "is_open"), ) def toggle_modal(n, is_open): if n: return not is_open return is_open
docs_content = html.Div( [ html.Div( [ html.H2( 'AntdDatePicker(id, className, style, *args, **kwargs)', style={ 'borderLeft': '4px solid grey', 'padding': '3px 0 3px 10px', 'backgroundColor': '#f5f5f5' } ), fac.AntdBackTop( containerId='docs-content', duration=0.6 ), html.Span( '主要参数说明:', id='主要参数说明', style={ 'borderLeft': '4px solid grey', 'padding': '3px 0 3px 10px', 'backgroundColor': '#f5f5f5', 'fontWeight': 'bold', 'fontSize': '1.2rem' } ), fmc.FefferyMarkdown( markdownStr=open('documents/AntdDatePicker.md', encoding='utf-8').read() ), html.Div( html.Span( '使用示例', id='使用示例', style={ 'borderLeft': '4px solid grey', 'padding': '3px 0 3px 10px', 'backgroundColor': '#f5f5f5', 'fontWeight': 'bold', 'fontSize': '1.2rem' } ), style={ 'marginBottom': '10px' } ), html.Div( [ fac.AntdDatePicker( picker='date', placeholder='请选择日期', defaultPickerValue='2020/01/01' ), fac.AntdDivider( '常规的日期选择', lineColor='#f0f0f0', innerTextOrientation='left' ), fac.AntdCollapse( fuc.FefferySyntaxHighlighter( showLineNumbers=True, showInlineLineNumbers=True, language='python', codeStyle='coy-without-shadows', codeString=''' fac.AntdDatePicker( picker='date', placeholder='请选择日期', defaultPickerValue='2020/01/01' )''' ), title='点击查看代码', is_open=False, ghost=True ) ], style={ 'marginBottom': '40px', 'padding': '10px 10px 20px 10px', 'border': '1px solid #f0f0f0' }, id='常规的日期选择', className='div-highlight' ), html.Div( [ fac.AntdDatePicker( picker='date', placeholder='请选择日期+时间', defaultPickerValue='2020/01/01', showTime=True ), fac.AntdDivider( '添加时间选择功能', lineColor='#f0f0f0', innerTextOrientation='left' ), fac.AntdCollapse( fuc.FefferySyntaxHighlighter( showLineNumbers=True, showInlineLineNumbers=True, language='python', codeStyle='coy-without-shadows', codeString=''' fac.AntdDatePicker( picker='date', placeholder='请选择日期+时间', defaultPickerValue='2020/01/01', showTime=True )''' ), title='点击查看代码', is_open=False, ghost=True ) ], style={ 'marginBottom': '40px', 'padding': '10px 10px 20px 10px', 'border': '1px solid #f0f0f0' }, id='添加时间选择功能', className='div-highlight' ), html.Div( [ fac.AntdDatePicker( picker='month', placeholder='请选择月份:', defaultPickerValue='2020/01' ), html.Div(style={'height': '25px'}), fac.AntdDatePicker( picker='year', placeholder='请选择年份', defaultPickerValue='2020' ), fac.AntdDivider( '其他时间粒度选择', lineColor='#f0f0f0', innerTextOrientation='left' ), fac.AntdCollapse( fuc.FefferySyntaxHighlighter( showLineNumbers=True, showInlineLineNumbers=True, language='python', codeStyle='coy-without-shadows', codeString=''' fac.AntdDatePicker( picker='month', placeholder='请选择月份:', defaultPickerValue='2020/01' ), html.Div(style={'height': '25px'}), fac.AntdDatePicker( picker='year', placeholder='请选择年份', defaultPickerValue='2020' )''' ), title='点击查看代码', is_open=False, ghost=True ) ], style={ 'marginBottom': '40px', 'padding': '10px 10px 20px 10px', 'border': '1px solid #f0f0f0' }, id='其他时间粒度选择', className='div-highlight' ), html.Div( [ fac.AntdDatePicker( id='date-picker-demo', picker='date', placeholder='请选择日期+时间', defaultPickerValue='2020/01/01', showTime=True ), html.Br(), fac.AntdSpin( html.Em(id='date-picker-demo-output'), text='回调中' ), fac.AntdDivider( '回调示例', lineColor='#f0f0f0', innerTextOrientation='left' ), fac.AntdCollapse( fuc.FefferySyntaxHighlighter( showLineNumbers=True, showInlineLineNumbers=True, language='python', codeStyle='coy-without-shadows', codeString=''' fac.AntdDatePicker( id='date-picker-demo', picker='date', placeholder='请选择日期+时间', defaultPickerValue='2020/01/01', showTime=True ), html.Br(), fac.AntdSpin( html.Em(id='date-picker-demo-output'), text='回调中' ) ... @app.callback( Output('date-picker-demo-output', 'children'), Input('date-picker-demo', 'value'), prevent_initial_call=True ) def date_picker_callback_demo(value): if value: return value return dash.no_update ''' ), title='点击查看代码', is_open=False, ghost=True ) ], style={ 'marginBottom': '40px', 'padding': '10px 10px 20px 10px', 'border': '1px solid #f0f0f0' }, id='回调示例', className='div-highlight' ), html.Div(style={'height': '100px'}) ], style={ 'flex': 'auto' } ), html.Div( fac.AntdAnchor( linkDict=[ {'title': '主要参数说明', 'href': '#主要参数说明'}, { 'title': '使用示例', 'href': '#使用示例', 'children': [ {'title': '常规的日期选择', 'href': '#常规的日期选择'}, {'title': '添加时间选择功能', 'href': '#添加时间选择功能'}, {'title': '其他时间粒度选择', 'href': '#其他时间粒度选择'}, {'title': '回调示例', 'href': '#回调示例'}, ] }, ], offsetTop=0 ), style={ 'flex': 'none', 'margin': '20px' } ) ], style={ 'display': 'flex' } )
def _set_layout(self): """ Create the layout of the app. """ self.app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) self._subplot_fig._fig['layout']['legend']['uirevision'] = True self.app.layout = dbc.Container( [ dbc.Row([ dbc.Col([ dcc.Graph(figure=self._subplot_fig._fig, id='fig', style={'height': '80vh'}), dash_table.DataTable( id='inferred-parameters-table', columns=([{ 'id': 'Run', 'name': 'Run' }] + [{ 'id': p, 'name': p } for p in self.params] + [{ 'id': 'Reproduction Number', 'name': 'Reproduction Number' }]), data=self._inferred_params_table) ], md=9), dbc.Col( [ html.Button('Run', id='run-button', n_clicks=0, style={ 'marginBottom': '1em', 'marginTop': '6em' }), dcc.Loading( id="loading-1", type="default", children=html.Div(id="run-optimisation")), html.Button('Reset', id='reset-button', n_clicks=0, style={'marginBottom': '1.8em'}), html.Br(), html. I("Enter in the below boxes to fix the parameter values" ), # noqa html.Br(), dcc.Input(id="Initial S", type="number", placeholder="Initial S", style={'marginBottom': '0.3em'}), dcc.Input(id="Initial E", type="number", placeholder="Initial E", style={'marginBottom': '0.3em'}), dcc.Input(id="Initial I", type="number", placeholder="Initial I", style={'marginBottom': '0.3em'}), dcc.Input(id="Initial R", type="number", placeholder="Initial R", style={'marginBottom': '0.3em'}), dcc.Input(id="Infection Rate", type="number", placeholder="Infection Rate", style={'marginBottom': '0.3em'}), dcc.Input(id="Incubation Rate", type="number", placeholder="Incubation Rate", style={'marginBottom': '0.3em'}), dcc.Input(id="Recovery Rate", type="number", placeholder="Recovery Rate", style={'marginBottom': '0.3em'}), html.Div(id="fixed-parameters-output"), ], md=3) ]) ], fluid=True)
def fibonacci_app(clientside): global fibonacci_count global fibonacci_sum_count fibonacci_count = 0 fibonacci_sum_count = 0 # This app tests 2 things in particular: # - clientside callbacks work the same as server-side # - callbacks using ALLSMALLER as an input to MATCH of the exact same id/prop app = Dash(__name__) app.layout = html.Div( [ dcc.Input(id="n", type="number", min=0, max=10, value=4), html.Div(id="series"), html.Div(id="sum"), ] ) @app.callback(Output("series", "children"), Input("n", "value")) def items(n): return [html.Div(id={"i": i}) for i in range(n)] if clientside: app.clientside_callback( """ function(vals) { var len = vals.length; return len < 2 ? len : +(vals[len - 1] || 0) + +(vals[len - 2] || 0); } """, Output({"i": MATCH}, "children"), Input({"i": ALLSMALLER}, "children"), ) app.clientside_callback( """ function(vals) { var sum = vals.reduce(function(a, b) { return +a + +b; }, 0); return vals.length + ' elements, sum: ' + sum; } """, Output("sum", "children"), Input({"i": ALL}, "children"), ) else: @app.callback( Output({"i": MATCH}, "children"), Input({"i": ALLSMALLER}, "children") ) def sequence(prev): global fibonacci_count fibonacci_count = fibonacci_count + 1 print(fibonacci_count) if len(prev) < 2: return len(prev) return int(prev[-1] or 0) + int(prev[-2] or 0) @app.callback(Output("sum", "children"), Input({"i": ALL}, "children")) def show_sum(seq): global fibonacci_sum_count fibonacci_sum_count = fibonacci_sum_count + 1 print("fibonacci_sum_count: ", fibonacci_sum_count) return "{} elements, sum: {}".format( len(seq), sum(int(v or 0) for v in seq) ) return app
from dash.dependencies import Input, Output import plotly.express as px external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # make a sample data frame with 6 columns df = pd.DataFrame({"Col " + str(i + 1): np.random.rand(30) for i in range(6)}) app.layout = html.Div([ html.Div(dcc.Graph(id='g1', config={'displayModeBar': False}), className='four columns'), html.Div(dcc.Graph(id='g2', config={'displayModeBar': False}), className='four columns'), html.Div(dcc.Graph(id='g3', config={'displayModeBar': False}), className='four columns') ], className='row') def get_figure(df, x_col, y_col, selectedpoints, selectedpoints_local): if selectedpoints_local and selectedpoints_local['range']: ranges = selectedpoints_local['range'] selection_bounds = { 'x0': ranges['x'][0], 'x1': ranges['x'][1], 'y0': ranges['y'][0], 'y1': ranges['y'][1]
def display_output(value, id): return html.Div("Dropdown {} = {}".format(id["index"], value))
def uncertainty_table_layout( uuid: str, ) -> html.Div: """Layout for the uncertainty table dialog""" return html.Div( children=[ wcc.FlexBox( children=[ html.Label( className="webviz-structunc-uncertainty-table-label", children="Statistics for well: ", id={"id": uuid, "element": "label"}, ), html.Button( "Recalculate", className="webviz-structunc-uncertainty-table-apply-btn", id={"id": uuid, "element": "apply-button"}, ), ] ), dash_table.DataTable( id={"id": uuid, "element": "table"}, columns=[ {"id": "Surface name", "name": "Surface name", "selectable": False}, {"id": "Ensemble", "name": "Ensemble", "selectable": False}, {"id": "Calculation", "name": "Calculation", "selectable": False}, {"id": "Pick no", "name": "Pick no", "selectable": False}, { "id": "TVD", "name": "TVD (MSL)", "selectable": False, }, { "id": "MD", "name": "MD (RKB)", "selectable": False, }, ], style_header={ "opacity": 0.5, }, style_filter={ "opacity": 0.5, }, style_data_conditional=[ { "if": {"column_id": "Surface name"}, "textAlign": "left", "width": "15%", }, { "if": {"column_id": "Ensemble"}, "textAlign": "left", "width": "15%", }, { "if": {"column_id": "Calculation"}, "textAlign": "left", "width": "10%", }, { "if": {"filter_query": '{Calculation} = "Mean"'}, "backgroundColor": "rgba(0,177,106,0.3)", }, ], sort_action="native", filter_action="native", ), ], )