def standard_layout(self, controls=[], visuals=[]) -> List: """ Return a basic layout with controls on the left and visuals in the center of the screen. :param controls: The controls (slicers etc.) of your dashboard as a `List` :param visuals: The visuals (charts etc.) of your dashboard as a `List` This function can be used in your implementation of dashboard() like this:: def dashboard(self) -> List: return standard_layout( controls = [control1, control2, ...], visuals = [visual1, visual2, ...] ) """ return [ Row([ Col( width=12, children=[ Div(className="slicers-card", children=controls) ], ), ]), Row( [ Col(width=12, children=[Div(children=self.visuals_wrapper(visuals))]) ], justify="start", ), ]
def Panel(head, body, idHtml=None, className=None): return Div(id=idHtml, className=f"panel panel-default {className}", children=[ Div(head, className="panel-heading"), Div(body, className="panel-body") ])
def test_exception_event_not_in_component(self): app = dash.Dash('') app.layout = Div([ Div(id='button'), Div(id='output'), Div(id='graph-output'), dcc.Graph(id='graph') ], id='body') for id in ['output', 'body']: self.assertRaises( exceptions.NonExistantEventException, app.callback, Output(id, 'children'), events=[Event(id, 'style')] ) app.callback( Output(id, 'children'), events=[Event(id, 'click')] ) self.assertRaises( exceptions.NonExistantEventException, app.callback, Output('output', 'children'), events=[Event('graph', 'zoom')] ) app.callback( Output('graph-output', 'children'), events=[Event('graph', 'click')] )
def test_gene002_arbitrary_resources(dash_duo): app = Dash(__name__) app.layout = Div([Button(id="btn"), Div(id="container")]) @app.callback(Output("container", "children"), [Input("btn", "n_clicks")]) def update_container(n_clicks): if n_clicks is None: raise PreventUpdate return StyledComponent(id="styled", value="Styled", style={"font-family": "godfather"}) dash_duo.start_server(app) assert (dash_duo.driver.execute_script( "return document.fonts.check('1em godfather')") is False) dash_duo.wait_for_element("#btn").click() assert dash_duo.wait_for_element("#styled").text == "Styled" WebDriverWait(dash_duo.driver, 10).until( lambda _: dash_duo.driver.execute_script( "return document.fonts.check('1em godfather')") is True, ) dash_duo.percy_snapshot(name="gene002-arbitrary-resource")
def get_files(iscompleted, filenames, upload_id): ctx = callback_context element_id = ctx.triggered[0]['prop_id'].split('.')[0] print(element_id) if not iscompleted: return if filenames is not None: if upload_id: root_folder = Path(UPLOAD_FOLDER_ROOT) / upload_id else: root_folder = Path(UPLOAD_FOLDER_ROOT) counter = Counter() for filename in filenames: file = root_folder / filename archive = zipfile.ZipFile(file, 'r') for one in archive.namelist()[1:]: print(one) with archive.open(one) as file_open: counter[load_one_file(file_open)] += 1 remove(file) print("{} removed".format(file)) return Div([ '{} log files were processed and added to database, {} files were not processed due to errors,' ' not log files are omitted and were not taken into account'. format(counter["good"], counter["bad"]) ]) return Div("No Files Uploaded Yet!")
def per_machine_per_device_pie_charts(GPU_STATS, KEEP_ALIVE): compute_machines = [] for machine_name, machine in GPU_STATS.items(): machine_devices = [] devices = machine["devices"] for i, d in enumerate(devices): used = d["used"] // MB_DIVISOR total = d["total"] // MB_DIVISOR used_ratio = used / total used_ratio = [used_ratio] + [1.0 - used_ratio] hover_text = [f"used:{used:.0f}mb", f"free:{total - used:.0f}mb"] machine_devices.append( Div( [ Graph( id=f"gpu_stats_{machine_name}{i}", figure={ "data": [ graph_objs.Pie( values=used_ratio, text=hover_text, name="used ratio", hole=0.4, ) ], "layout": graph_objs.Layout( title=f"{d['name']} cuda_idx:{d['id']}", showlegend=False, hovermode="closest", ), }, style={ "width": "100%", }, ) ], className="col", )) compute_machines.append( Div( [ H3( f"{machine_name}: {KEEP_ALIVE[machine_name]} sec ago", className="text-monospace", style={"text-decoration": "underline"}, ), Div([*machine_devices], className="row"), ], style={ "text-align": "center", "width": "100%", }, )) return compute_machines
def layout(symbols): """Return the UI layout.""" periods = [('1 day', 0), ('1 week', 1), ('1 month', 2), ('3 months', 3), ('1 year', 4), ('5 years', 5)] return Div([ H3('Stock prices'), Div([ Div([_symbol_selector_dropdown(symbols)], style={ 'width': '45%', 'float': 'left', 'display': 'inline-block' }), Div([_period_selector_radio(periods)], style={ 'width': '45%', 'float': 'right', 'display': 'inline-block' }) ], style={ 'display': 'inline-block', 'width': '100%' }), Graph(id='plot-stock', config={'displayModeBar': False}) ])
def mk_trim_row_header(make: str, model: str, trim: str) -> Div: return Div( className="mmt-trim mmt-trim-box", children=[ Div( className="mmt-trim mmt-trim-left", children=[ dbc.Checklist( className=INPID_MMT_DISABLE, id=dict( id=INPID_MMT_DISABLE, make=make, model=model, trim=trim, ), value=[True], options=[dict(label="", value=True)], switch=True, **PERSIST_ARGS, ) ], ), Div( className="mmt-trim mmt-trim-right", children=html.Span(trim.upper(), className="mmt-trim"), ), ], )
def test_callback_registry(self): app = dash.Dash('') input = dcc.Input(id='input') input._events = ['blur', 'change'] app.layout = Div([ input, Div(id='output-1'), Div(id='output-2'), Div(id='output-3') ], id='body') app.callback(Output('body', 'children'), [Input('input', 'value')]) app.callback(Output('output-1', 'children'), [Input('input', 'value')]) app.callback( Output('output-2', 'children'), [Input('input', 'value')], state=[State('input', 'value')], ) app.callback( Output('output-3', 'children'), [Input('input', 'value')], state=[State('input', 'value')], events=[Event('input', 'blur')], )
def test_exception_prop_not_in_component(self): app = dash.Dash('') app.layout = Div([ dcc.Input(id='input'), Div(id='output') ], id='body') self.assertRaises( exceptions.NonExistantPropException, app.callback, Output('output', 'non-there'), [Input('input', 'value')] ) self.assertRaises( exceptions.NonExistantPropException, app.callback, Output('output', 'children'), [Input('input', 'valuez')] ) self.assertRaises( exceptions.NonExistantPropException, app.callback, Output('body', 'childrenz'), [Input('input', 'value')] )
def _set_layout(assets): asset_names = sorted(assets.keys()) header_elements = [ Div( [ H1("Data Asset Visualiser", className="header-title"), P("Load assets from JSON Lines files", className="header-description"), ], className="header", ), Div( dcc.Dropdown( id="asset-filter", options=[{"label": a, "value": a} for a in asset_names], value="", clearable=True, className="dropdown", ), className="menu", ), ] body = Div(_generate_body(), id="charts-body", className="wrapper") all_elements = header_elements + [body] return Div(all_elements)
def test_dbnl_002_manual_active(dash_duo): """ Update active status using a callback. """ app = Dash() app.layout = Div([ # Location is required to fire events to History Location(id="url"), NavLink("Page 1", id="page-1-link", href="/page-1"), NavLink("Page 2", id="page-2-link", href="/page-2"), NavLink("Page 3", id="page-3-link", href="/page-3"), Div(id="content"), ]) @app.callback( [Output("page-{}-link".format(i), "active") for i in range(1, 4)], Input("url", "pathname"), ) def set_active(pathname): return [pathname == "/page-{}".format(i) for i in range(1, 4)] dash_duo.start_server(app) assert all([ "active" not in dash_duo.wait_for_element_by_id( "page-{}-link".format(i)).get_attribute("class") for i in range(1, 4) ]) dash_duo.wait_for_element_by_id("page-1-link").click() # wait for callback to update page WebDriverWait(dash_duo.driver, timeout=10).until(lambda d: "active" in d.find_element_by_id( "page-1-link").get_attribute("class")) assert "active" in dash_duo.wait_for_element_by_id( "page-1-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-2-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-3-link").get_attribute("class") dash_duo.wait_for_element_by_id("page-3-link").click() # wait for callback to update page WebDriverWait( dash_duo.driver, timeout=10).until(lambda d: "active" not in d.find_element_by_id( "page-1-link").get_attribute("class")) assert "active" not in dash_duo.wait_for_element_by_id( "page-1-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-2-link").get_attribute("class") assert "active" in dash_duo.wait_for_element_by_id( "page-3-link").get_attribute("class")
def base() -> Div: ''' Returns a dash website base ''' return Div([ Location(id='url', refresh=False), external_link(rel='icon', href='assets/img/favicon.ico'), Div(id='page_content') ])
def get_html(self): """Glues individual setup components together """ return Div(className="app", children=self.components["navbar"].html + [ Div(className="app-content", children=self.components["sidebar"].html + self.components["index"].html) ])
def makeCard(plot, view, hide=False): layout = \ { 'title' : f'<b>{plot} of {view}</b>', 'xaxis_showgrid' : False, 'xaxis_zeroline' : False, 'xaxis_visible' : False, 'yaxis_showgrid' : False, 'yaxis_zeroline' : False, 'yaxis_visible' : False, 'paper_bgcolor' : BG_PAPER, 'plot_bgcolor' : BG_PLOT, } config = \ { 'displaylogo' : False, 'showTips' : True, 'frameMargins' : 0, } style = \ { 'background' : 'blue' } wrap = plot.replace('plot', 'wrap') card = plot.replace('plot', 'card') mask = plot.replace('plot', 'mask') load = plot.replace('plot', 'load') figure = upFigure(traces=[], layout=layout) return Div(id=wrap, className='wrap', children=[ Card(id=card, className=f'{view}', children=[ Div(id=mask, className='mask', hidden=False, children=[ Loading(id=load, className='load', children=[ Graph(id=plot, figure=figure, config=config, style=style) ]), ]) ]) ])
def get_layout(): return Div([ html.H2("Confusion Matrix"), Dropdown(id='cm-dropdown', options=get_dropdown_list(models), clearable=True, value=-1), Div(id='cm-out') ])
def test_suppress_callback_exception(self): app = dash.Dash('') app.layout = Div([dcc.Input(id='input'), Div(id='output')], id='body') self.assertRaises(exceptions.NonExistentIdException, app.callback, Output('id-not-there', 'children'), [Input('input', 'value')]) app.config.supress_callback_exceptions = True app.callback(Output('id-not-there', 'children'), [Input('input', 'value')])
def get_item_hud(hud_title='LCL FORECAST ANALYSIS', hud_1_0='', hud_1_1='') \ -> Container: """ :param hud_title: str top of HUD :param hud_1_0: str Byline Position 1 :param hud_1_1: str Byline Position 2 :param hud_1_2: str :return: Container: 'item-hud-container' Row Container:'item-hud-title-container' Col H1: 'hud-title' Container: 'item-hud-byline-container' Row Navbar: item-hud-bar' NavItem: H2: 'hud-1-0' H2: hud-1-1' Row Tabs: 'table-tabs-nav' Tab: 'tab-all """ layout = Container( fluid=True, id='item-hud-container', children=[ Row( Container( id='item-hud-title-container', children=[Col(H1(id='hud-title', children=hud_title))])), Container( id='item-hud-byline-container', style=VISIBILITY_HIDDEN, children=[ Row([ Navbar(id='item-hud-bar', children=[ NavItem(H2(hud_1_0, id='hud-1-0')), NavItem(H2(hud_1_1, id='hud-1-1')) ]) ]), Row([ Tabs( id='table-tabs-nav', children=[Tab(tab_id='tab-all', label='All')], ) ], id='item-hub-tabs-row') ]), Div(id='datasource-1'), Div(id='datasource-2') ]) return layout
def setUp(self): self.app = dash.Dash('my-app') self.app.layout = Div([ Div('Hello World', id='header', style={'color': 'red'}), dcc.Input(id='id1', placeholder='Type a value'), dcc.Input(id='id2', placeholder='Type a value') ]) self.client = self.app.server.test_client() self.maxDiff = 100 * 1000
def test_dbnl001_auto_active(dash_duo): """ Checks that NavLink is able to automatically set active status based on the current location. """ app = Dash() app.layout = Div([ # Location is required to fire events to History Location(id="url"), NavLink("Page 1", id="page-1-link", href="/page-1", active=True), NavLink("Page 2", id="page-2-link", href="/page-2", active=False), NavLink("Page 3", id="page-3-link", href="/page-3", active="partial"), NavLink( "Page 3 - extra", id="page-3-extra-link", href="/page-3/extra", active="exact", ), Div(id="content"), ]) dash_duo.start_server(app) assert "active" in dash_duo.wait_for_element_by_id( "page-1-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-2-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-3-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-3-extra-link").get_attribute("class") dash_duo.wait_for_element_by_id("page-3-link").click() assert "active" in dash_duo.wait_for_element_by_id( "page-1-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-2-link").get_attribute("class") assert "active" in dash_duo.wait_for_element_by_id( "page-3-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-3-extra-link").get_attribute("class") dash_duo.wait_for_element_by_id("page-3-extra-link").click() assert "active" in dash_duo.wait_for_element_by_id( "page-1-link").get_attribute("class") assert "active" not in dash_duo.wait_for_element_by_id( "page-2-link").get_attribute("class") assert "active" in dash_duo.wait_for_element_by_id( "page-3-link").get_attribute("class") assert "active" in dash_duo.wait_for_element_by_id( "page-3-extra-link").get_attribute("class")
def show_dag(selected_dag): from airflow import models, settings dagbag = models.DagBag(settings.DAGS_FOLDER) dag = dagbag.get_dag(selected_dag) return [ Div('Click on a task to see its output', className="panel-heading"), Div(plot.dashdag(dag, html_id=DAGRE_HTML_ID), className="panel-body") ]
def main_layout_header(): """Dash layout with a top-header""" return Div([ Div(id="header", children=[ Header(), Div(id=server.config['NAVBAR_CONTAINER_ID']), ]), Div(className='container-fluid', children=Row(Col(id=server.config['CONTENT_CONTAINER_ID']))), dcc.Location(id='url', refresh=False), Div(DataTable(rows=[{}]), style={'display': 'none'}) ])
def get_html(self): """Glues individual setup components together """ return Div(children= self.components["navbar"].html + [Container( children=Row(self.components["sidebar"].html + [Div( id="page-wrapper", children=self.components["index"].html )]), fluid=True, className="mt-5", )])
def get_layout(): return Div([ Dropdown( id='models-dropdown', options=get_dropdown_list(models), clearable=True, multi=True, value=[], ), Div(id='report'), Div(learning_history.generate_layout(graphs), ), Div(id='dummy') ])
def makeRoot_RisksBar(hide=F): return Div(Container([ Col([ Label('operational region(s)'), Div(id='risks-area-div', children=Dropdown(id='risks-area', placeholder='Select Operating Area(s)', options=[{ 'label': v, 'value': v } for v in data['alist']], value=data['alist'][0:], multi=True)), Tooltip( children= 'Select Operating Area(s) to See Details on the Geographical Footprint Map', id='risks-area-tip', target='risks-area-div', placement='right') ], className='dis nop r1p', width=6, style={'display': 'none'}), Col( [ Label('operational footprint'), Div(id='risks-foot-div', children=Dropdown(id='risks-foot', placeholder='Select Corporate Footprint', options=[{ 'label': k, 'value': v } for k, v in data['fdict'].items()], value='subsidiaries')), Tooltip( children= 'Select Footprint Metric to See Details on the Geographical Footprint Map', id='risks-foot-tip', target='risks-foot-div', placement='left') ], className='dis nop', width=3, ) ], id='risks-tool', fluid=True, style={'padding': '0rem'}), id='risks-wrap', hidden=hide)
def test_exception_component_is_not_right_type(self): app = dash.Dash('') app.layout = Div([dcc.Input(id='input'), Div(id='output')], id='body') test_args = [ ['asdf', ['asdf'], [], []], [Output('output', 'children'), Input('input', 'value'), [], []], [Output('output', 'children'), [], State('input', 'value'), []], ] for args in test_args: self.assertRaises(exceptions.IncorrectTypeException, app.callback, *args)
def get_html(self): """Glues individual setup components together """ return Div( className="app", children=self.components["navbar"].html + [ Div( className="app-content", children=self.components["sidebar"].html + self.components["index"].html ), Store(id="root-store"), Location(id='location') ] )
def test_exception_event_not_in_component(self): # no events anymore, period! app = dash.Dash('') app.layout = Div([ Div(id='button'), Div(id='output'), Div(id='graph-output'), dcc.Graph(id='graph') ], id='body') for id in ['output', 'body']: self.assertRaises(TypeError, app.callback, Output(id, 'children'), events=[])
def get_html(self) -> List[ComponentMeta]: """Initializes the header dash html """ return [Div( id="more_intro_wrapper", children=[Markdown(id="more_intro", dangerously_allow_html=True)] )]
def Error(message): return Div(id="alert-div", className="alert alert-danger alert-dismissible", children=[ Strong("Error!"), f" {message}", ])