コード例 #1
0
def test_tabs002_without_children(dash_dcc):
    app = Dash(__name__)
    app.layout = html.Div([
        html.H1("Dash Tabs component demo"),
        dcc.Tabs(
            id="tabs",
            value="tab-2",
            children=[
                dcc.Tab(label="Tab one", value="tab-1", id="tab-1"),
                dcc.Tab(label="Tab two", value="tab-2", id="tab-2"),
            ],
        ),
        html.Div(id="tabs-content"),
    ])

    @app.callback(
        Output("tabs-content", "children"),
        [Input("tabs", "value")],
    )
    def render_content(tab):
        if tab == "tab-1":
            return html.Div([html.H3("Test content 1")], id="test-tab-1")
        elif tab == "tab-2":
            return html.Div([html.H3("Test content 2")], id="test-tab-2")

    dash_dcc.start_server(app)
    dash_dcc.wait_for_text_to_equal("#tabs-content", "Test content 2")
    dash_dcc.percy_snapshot("Core initial tab - tab 2")

    dash_dcc.wait_for_element("#tab-1").click()
    dash_dcc.wait_for_text_to_equal("#tabs-content", "Test content 1")
    assert dash_dcc.get_logs() == []
コード例 #2
0
 def layout(self) -> dcc.Tabs:
     return dcc.Tabs(children=[
         dcc.Tab(
             label="Cross section & map view",
             children=[
                 wcc.FlexBox(
                     id=self.ids("layout"),
                     children=[
                         html.Div(style={"flex": 1},
                                  children=self.left_flexbox_layout),
                         html.Div(
                             style={"flex": 1.5},
                             children=self.cross_section_widgets_layout,
                         ),
                     ],
                 )
             ],
         ),
         dcc.Tab(
             label="Target Points",
             children=[html.Div(children=self.target_points_tab_layout)],
         ),
         dcc.Tab(label="Well Points",
                 children=[self.well_points_tab_layout]),
     ])
コード例 #3
0
def test_tabs004_without_value(dash_dcc):
    app = Dash(__name__)

    app.layout = html.Div([
        html.H1("Dash Tabs component demo"),
        dcc.Tabs(
            id="tabs-without-value",
            children=[
                dcc.Tab(label="Tab One", value="tab-1"),
                dcc.Tab(label="Tab Two", value="tab-2"),
            ],
        ),
        html.Div(id="tabs-content"),
    ])

    @app.callback(Output("tabs-content", "children"),
                  [Input("tabs-without-value", "value")])
    def render_content(tab):
        if tab == "tab-1":
            return html.H3("Default selected Tab content 1")
        elif tab == "tab-2":
            return html.H3("Tab content 2")

    dash_dcc.start_server(app)
    dash_dcc.wait_for_text_to_equal("#tabs-content",
                                    "Default selected Tab content 1")
    dash_dcc.percy_snapshot("Core Tab 1 should be selected by default")
    assert dash_dcc.get_logs() == []
コード例 #4
0
def test_cbsc003_callback_with_unloaded_async_component(dash_duo):
    app = Dash()
    app.layout = html.Div(
        children=[
            dcc.Tabs(
                children=[
                    dcc.Tab(
                        children=[
                            html.Button(id="btn", children="Update Input"),
                            html.Div(id="output", children=["Hello"]),
                        ]
                    ),
                    dcc.Tab(children=dash_table.DataTable(id="other-table")),
                ]
            )
        ]
    )

    @app.callback(Output("output", "children"), [Input("btn", "n_clicks")])
    def update_out(n_clicks):
        if n_clicks is None:
            raise PreventUpdate

        return "Bye"

    dash_duo.start_server(app)

    dash_duo.wait_for_text_to_equal("#output", "Hello")
    dash_duo.find_element("#btn").click()
    dash_duo.wait_for_text_to_equal("#output", "Bye")
    assert dash_duo.get_logs() == []
コード例 #5
0
def test_tabs001_in_vertical_mode(dash_dcc):
    app = Dash(__name__)
    app.layout = html.Div([
        dcc.Tabs(
            id="tabs",
            value="tab-3",
            children=[
                dcc.Tab(
                    label="Tab one",
                    value="tab-1",
                    id="tab-1",
                    children=[html.Div("Tab One Content")],
                ),
                dcc.Tab(
                    label="Tab two",
                    value="tab-2",
                    id="tab-2",
                    children=[html.Div("Tab Two Content")],
                ),
                dcc.Tab(
                    label="Tab three",
                    value="tab-3",
                    id="tab-3",
                    children=[html.Div("Tab Three Content")],
                ),
            ],
            vertical=True,
        ),
        html.Div(id="tabs-content"),
    ])

    dash_dcc.start_server(app)
    dash_dcc.wait_for_text_to_equal("#tab-3", "Tab three")
    dash_dcc.percy_snapshot("Core Tabs - vertical mode")
    assert dash_dcc.get_logs() == []
コード例 #6
0
def test_tabs005_disabled(dash_dcc):
    app = Dash(__name__, assets_folder="../../assets")
    app.layout = html.Div([
        html.H1("Dash Tabs component with disabled tab demo"),
        dcc.Tabs(
            id="tabs-example",
            value="tab-2",
            children=[
                dcc.Tab(
                    label="Disabled Tab",
                    value="tab-1",
                    id="tab-1",
                    className="test-custom-tab",
                    disabled=True,
                ),
                dcc.Tab(
                    label="Active Tab",
                    value="tab-2",
                    id="tab-2",
                    className="test-custom-tab",
                ),
            ],
        ),
        html.Div(id="tabs-content-example"),
    ])

    dash_dcc.start_server(app)

    dash_dcc.wait_for_element("#tab-2")
    dash_dcc.wait_for_element(".tab--disabled")
    assert dash_dcc.get_logs() == []
コード例 #7
0
ファイル: index.py プロジェクト: bud42/dax-dashboard
def get_layout():
    qa_content = qa.get_content()
    activity_content = activity.get_content()
    stats_content = stats.get_content()
    reports_content = reports.get_content()

    report_content = [
        html.Div(
            dcc.Tabs(id='tabs',
                     value='1',
                     vertical=False,
                     children=[
                         dcc.Tab(label='QA', value='1', children=qa_content),
                         dcc.Tab(label='Activity',
                                 value='2',
                                 children=activity_content),
                         dcc.Tab(label='Stats',
                                 value='3',
                                 children=stats_content),
                         dcc.Tab(label='Reports',
                                 value='4',
                                 children=reports_content),
                     ]),
            #style={
            #    'width': '100%', 'display': 'flex',
            #    'align-items': 'center', 'justify-content': 'left'}
            style={
                'width': '90%',
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center'
            })
    ]

    footer_content = [
        html.Hr(),
        html.H5('F: Failed'),
        html.H5('P: Passed QA'),
        html.H5('Q: To be determined')
    ]

    # Make the main app layout
    main_content = html.Div([
        html.Div([html.H1('DAX Dashboard')]),
        html.Div(children=report_content, id='report-content'),
        html.Div(children=footer_content, id='footer-content')
    ])

    return main_content
コード例 #8
0
ファイル: webapp.py プロジェクト: MSLNZ/pr-omega-logger
def serve_layout():
    return html.Div([
        html.A(id='api-help-link',
               children='?',
               href=f'{request.url_root}help' if has_request_context() else '',
               target='_blank',
               title='View the API documentation',
               style={
                   'color': '#fff',
                   'background-color': '#f15A29',
                   'width': 16,
                   'height': 16,
                   'display': 'inline-block',
                   'border-radius': '100%',
                   'font-size': 16,
                   'text-align': 'center',
                   'text-decoration': 'none',
                   'box-shadow': 'inset -2px -2px 1px 0px rgba(0,0,0,0.25)',
                   'margin-left': '98%',
                   'margin-bottom': 4,
               }),
        dcc.Dropdown(
            id='omega-dropdown',
            options=dropdown_options,
            multi=True,
            placeholder='Select the OMEGA iServer(s)...',
        ),
        DatetimeRangePicker(id='datetime-range',
                            **datetime_range_picker_kwargs(cfg)),
        dcc.Tabs(
            id='tabs',
            value='temperature',
            children=[
                dcc.Tab(label='Current Readings', value='current-readings'),
                dcc.Tab(label='Temperature', value='temperature'),
                dcc.Tab(label='Humidity', value='humidity'),
                dcc.Tab(label='Dewpoint', value='dewpoint'),
            ],
            style={'display': 'inline-block'},
        ),
        html.Div(id='plot-viewer'),
        html.Div(id='current-readings-viewer'),
        dcc.Interval(
            id='current-readings-interval',
            interval=cfg.value('current_readings/interval', 10) * 1000,
        ),
    ])
コード例 #9
0
ファイル: components.py プロジェクト: mlco2/codecarbon
 def get_emissions_tab():
     return dcc.Tab(
         label="Emissions Equivalent",
         value="emissions_tab",
         id="global_emissions",
         children=[
             html.Div(
                 dbc.Col(
                     dcc.Graph(id="global_emissions_choropleth"),
                     style={"marginLeft": "-16%"},
                 ))
         ],
     )
コード例 #10
0
def patient_information():
    """ Return: Card with patient information """
    information = [
        dcc.Tab(label='About',
                value='what-is',
                children=html.Div(
                    className='control-tab',
                    children=[
                        html.H4(className='what-is',
                                children='Information about patient'),
                        html.A('Download data', id='my-link2'),
                        html.P(id="text", className="card-text"),
                    ]))
    ]
    return information
コード例 #11
0
ファイル: components.py プロジェクト: theNewFlesh/shekels
def get_dash_app(server, storage_type='memory'):
    # type: (flask.Flask, str) -> dash.Dash
    '''
    Generate Dash Flask app instance.

    Args:
        server (Flask): Flask instance.
        storage_type (str): Storage type (used for testing). Default: memory.

    Returns:
        Dash: Dash app instance.
    '''

    store = dcc.Store(id='store', storage_type=storage_type)

    icon = html.Img(id='icon', src='/assets/icon.svg')
    tabs = dcc.Tabs(
        id='tabs',
        className='tabs',
        value='plots',
        children=[
            dcc.Tab(className='tab', label='plots', value='plots'),
            dcc.Tab(className='tab', label='data', value='data'),
            dcc.Tab(className='tab', label='config', value='config'),
            dcc.Tab(className='tab', label='api', value='api'),
            dcc.Tab(className='tab', label='docs', value='docs'),
            dcc.Tab(className='tab', label='monitor', value='monitor'),
        ],
    )
    tabs = html.Div(id='tabs-container', children=[icon, tabs])

    content = dcc.Loading(
        id="content",
        className='content',
        type="dot",
        fullscreen=True,
    )

    # path to resources inside pip package
    assets = lbt.relative_path(__file__, "../resources")

    # path to resources inside repo
    if 'REPO_ENV' in os.environ.keys():
        assets = lbt.relative_path(__file__, "../../../resources")

    app = dash.Dash(
        name='Shekels',
        title='Shekels',
        server=server,
        external_stylesheets=['/static/style.css'],
        assets_folder=assets,
    )
    app.layout = html.Div(id='layout', children=[store, tabs, content])
    app.config['suppress_callback_exceptions'] = True

    return app
コード例 #12
0
ファイル: components.py プロジェクト: mlco2/codecarbon
 def get_energy_mix_tab():
     return dcc.Tab(
         label="Energy Mix",
         value="energy_mix_tab",
         id="global_energy_mix",
         children=[
             html.Div(
                 dbc.Col([
                     html.Br(),
                     html.H4("Select Energy Source"),
                     dcc.Dropdown(
                         id="energy_type",
                         options=[
                             {
                                 "label": "Fossil",
                                 "value": "fossil"
                             },
                             {
                                 "label": "Geothermal",
                                 "value": "geothermal"
                             },
                             {
                                 "label": "Hydroelectricity",
                                 "value": "hydroelectricity",
                             },
                             {
                                 "label": "Nuclear",
                                 "value": "nuclear"
                             },
                             {
                                 "label": "Solar",
                                 "value": "solar"
                             },
                             {
                                 "label": "Wind",
                                 "value": "wind"
                             },
                         ],
                         value="fossil",
                     ),
                     dcc.Graph(
                         id="global_energy_mix_choropleth",
                         style={"marginLeft": "-16%"},
                     ),
                 ]))
         ],
     )
コード例 #13
0
def get_graph_content():
    graph_content = []

    #for r in os.listdir(REPORTDIR):
    if not os.path.exists('assets'):
        os.mkdir('assets')
    else:
        _time = time.ctime(os.path.getmtime('assets'))
        _time = datetime.strptime(_time, "%a %b %d %H:%M:%S %Y")
        _txt = 'Updated {} at {}'.format(humanize.naturaltime(_time), _time)
        graph_content.append(html.P(
            _txt,
            style={
                'padding-top': '30px',
                'padding-bottom': '20px',
                'padding-left': '200px',
                'padding-right': ' 200px'}))

        report_list = os.listdir('assets')
        report_list = sorted(report_list)
        report_list = [x for x in report_list if x.endswith('_report.pdf')]
        for r in report_list:
            # Add a link to project PDF
            graph_content.append(
                html.Div(
                    html.A(r, download=r, href='assets/'+r),
                    style={
                        'padding-top': '10px',
                        'padding-bottom': '10px',
                        'padding-left': '50px'}))

    # Add some space
    graph_content.append(html.Br())

    # Wrap in a tab
    tab0 = dcc.Tab(
        label='Monthly',
        value='0',
        children=[html.Div(graph_content)],
        style={'width': '900px'})

    # Concat the tabs
    tabs = [tab0]

    # Return the tabs
    return tabs
コード例 #14
0
def get_graph_content(df):
    PIVOTS = ['PROJECT', 'CATEGORY', 'SOURCE']
    status2rgb = STATUS2RGB
    tabs_content = []

    # index we are pivoting on to count statuses
    for i, pindex in enumerate(PIVOTS):
        #print('making pivot', i, pindex)
        # Make a 1x1 figure
        fig = plotly.subplots.make_subplots(rows=1, cols=1)
        fig.update_layout(margin=dict(l=40, r=40, t=40, b=40))

        # Draw bar for each status, these will be displayed in order
        dfp = pd.pivot_table(
            df, index=pindex, values='LABEL', columns=['STATUS'],
            aggfunc='count', fill_value=0)

        for status, color in status2rgb.items():
            #print('making bar', status, color)
            ydata = sorted(dfp.index)
            if status not in dfp:
                xdata = [0] * len(dfp.index)
            else:
                xdata = dfp[status]

            fig.append_trace(go.Bar(
                x=ydata,
                y=xdata,
                name='{} ({})'.format(status, sum(xdata)),
                marker=dict(color=color),
                opacity=0.9), 1, 1)

        # Customize figure
        fig['layout'].update(barmode='stack', showlegend=True, width=900)

        # Build the tab
        label = 'By {}'.format(pindex)
        graph = html.Div(dcc.Graph(figure=fig), style={
            'width': '100%', 'display': 'inline-block'})
        tab = dcc.Tab(label=label, value=str(i + 1), children=[graph])

        # Append the tab
        tabs_content.append(tab)

    return tabs_content
コード例 #15
0
def generate_weekday_tab(day):
    if DEBUG:
        print("generate_weekday_tab")
    tab_style = {
        'height': '30px',
        'padding': '2px',
    }
    selected_tab_style = {
        'borderTop': '2px solid #064779',
        'height': '30px',
        'padding': '2px',
    }

    return dcc.Tab(label=day,
                   value='tab-'+day.lower()[:3],
                   style=tab_style,
                   selected_style=selected_tab_style,
                  )
コード例 #16
0
def dcc_slider_values(tab_label: str,
                      div_id: str,
                      slider_id: str,
                      slider_min,
                      slider_max,
                      slider_marks,
                      slider_value,
                      slider_step,
                      slider_updatemode: str,
                      div_style={'margin-top': 20},
                      make_slider_vertical: bool = False):
    return dcc.Tab(label=tab_label,
                   children=[
                       html.Div(id=div_id, style=div_style),
                       dcc.Slider(id=slider_id,
                                  min=slider_min,
                                  max=slider_max,
                                  marks=slider_marks,
                                  value=slider_value,
                                  step=slider_step,
                                  updatemode=slider_updatemode,
                                  vertical=make_slider_vertical)
                   ])
コード例 #17
0
def test_inin026_graphs_in_tabs_do_not_share_state(dash_duo):
    app = Dash(__name__, suppress_callback_exceptions=True)

    app.layout = html.Div([
        dcc.Tabs(
            id="tabs",
            children=[
                dcc.Tab(label="Tab 1", value="tab1", id="tab1"),
                dcc.Tab(label="Tab 2", value="tab2", id="tab2"),
            ],
            value="tab1",
        ),
        # Tab content
        html.Div(id="tab_content"),
    ])
    tab1_layout = [
        html.Div([
            dcc.Graph(
                id="graph1",
                figure={
                    "data": [{
                        "x": [1, 2, 3],
                        "y": [5, 10, 6],
                        "type": "bar"
                    }]
                },
            )
        ]),
        html.Pre(id="graph1_info"),
    ]

    tab2_layout = [
        html.Div([
            dcc.Graph(
                id="graph2",
                figure={
                    "data": [{
                        "x": [4, 3, 2],
                        "y": [5, 10, 6],
                        "type": "bar"
                    }]
                },
            )
        ]),
        html.Pre(id="graph2_info"),
    ]

    @app.callback(Output("graph1_info", "children"),
                  Input("graph1", "clickData"))
    def display_hover_data(hover_data):
        return json.dumps(hover_data)

    @app.callback(Output("graph2_info", "children"),
                  Input("graph2", "clickData"))
    def display_hover_data_2(hover_data):
        return json.dumps(hover_data)

    @app.callback(Output("tab_content", "children"), Input("tabs", "value"))
    def render_content(tab):
        return tab2_layout if tab == "tab2" else tab1_layout

    dash_duo.start_server(app)

    dash_duo.find_element("#graph1:not(.dash-graph--pending)").click()

    until(lambda: '"label": 2' in dash_duo.find_element("#graph1_info").text,
          timeout=3)

    dash_duo.find_element("#tab2").click()

    dash_duo.find_element("#graph2:not(.dash-graph--pending)").click()

    until(lambda: '"label": 3' in dash_duo.find_element("#graph2_info").text,
          timeout=3)
コード例 #18
0
ファイル: variantmap_app.py プロジェクト: cytham/variantmap
def layout():
    return html.Div(
        id='variantmap-body',
        className='app-body',
        children=[
            html.Div(
                id='variantmap-control-tabs',
                className='control-tabs',
                children=[
                    dcc.Tabs(
                        id='variantmap-tabs',
                        value='what-is',
                        children=[
                            # "What is" tab
                            dcc.Tab(
                                label='About',
                                value='what-is',
                                children=html.Div(
                                    className='control-tab',
                                    children=[
                                        html.H4(
                                            className='what-is',
                                            children='What is VariantMap?'),
                                        html.
                                        P('VariantMap is a genomic structural variant (SV) visualization '
                                          'technique that displays variants across multiple samples in a '
                                          'single heatmap. Each row represents a sample and each column '
                                          'represents an SV breakend in the sample cohort. The colors '
                                          'indicate the class of an SV present in a sample. The '
                                          'heatmap can be customized interactively to suit your analysis '
                                          'by changing various components in the "Customize" tab.'
                                          ),
                                        html.
                                        P('VariantMap requires a dataframe object that is generated by '
                                          'VariantBreak. Do note that only NanoVar VCF '
                                          'files are currently compatible to work with VariantBreak in creating the '
                                          'dataframe.')
                                    ])),
                            # Data tab
                            dcc.Tab(
                                label='Data',
                                value='data',
                                children=html.Div(
                                    className='control-tab',
                                    children=[
                                        # Dataset upload
                                        html.Div(
                                            'Upload dataset:',
                                            title=
                                            'Upload your own dataset below.',
                                            className='app-controls-name'),
                                        html.Div(
                                            id='variantmap-file-upload',
                                            title=
                                            'Upload your own VariantBreak generated HDF5 dataset here.',
                                            children=[
                                                dcc.Upload(
                                                    id='upload-data',
                                                    className='control-upload',
                                                    children=html.Div([
                                                        "Drag and drop your .h5 file or ",
                                                        html.A("select file.")
                                                    ]),
                                                    accept='.hdf5,.h5',
                                                    multiple=False)
                                            ]),
                                        html.Br(),
                                        # Label file upload
                                        html.Div(
                                            'Upload label file:',
                                            title=
                                            'This file is used to rename and sort samples.\nExample:\n#Default '
                                            'name<tab>Label\nS1<tab>SampleA\nS3<tab>SampleC\nS2<tab>SampleB',
                                            className='app-controls-name'),
                                        html.Div(
                                            id='variantmap-tsv-upload',
                                            title=
                                            'Upload a .tsv file to rename and sort samples.\nExample:\n#Default '
                                            'name<tab>Label\nS1<tab>SampleA\nS3<tab>SampleC\nS2<tab>SampleB',
                                            children=[
                                                dcc.Upload(
                                                    id='upload-tsv',
                                                    className='control-upload',
                                                    children=html.Div([
                                                        "Drag and drop your .tsv file or ",
                                                        html.A("select file.")
                                                    ]),
                                                    accept='.txt,.tsv,.csv',
                                                    multiple=False)
                                            ]),
                                        html.Br(),
                                        # Sample selection check boxes
                                        html.Div(
                                            id='output-data-info',
                                            className=
                                            'fullwidth-app-controls-name',
                                            children=[
                                                dcc.Checklist(
                                                    id="select-samples",
                                                    style={'display': 'none'}),
                                                html.Br(),
                                                html.Button(
                                                    id='submit-button-samples',
                                                    style={'display': 'none'})
                                            ])
                                    ])),
                            # Customize tab
                            dcc.Tab(
                                label='Customize',
                                value='customize',
                                children=html.Div(
                                    className='control-tab',
                                    children=[
                                        html.Div(
                                            id='customize-tab',
                                            className=
                                            'fullwidth-app-controls-name',
                                            children=[
                                                dcc.Dropdown(
                                                    id='sample_filt',
                                                    style={'display': 'none'}),
                                                dcc.Dropdown(
                                                    id='file_filt',
                                                    style={'display': 'none'}),
                                                dcc.Dropdown(
                                                    id='gene_names',
                                                    style={'display': 'none'}),
                                                dcc.Input(
                                                    id='input_index',
                                                    style={'display': 'none'}),
                                                dcc.Checklist(
                                                    id="select-genetype",
                                                    style={'display': 'none'}),
                                                dcc.Checklist(
                                                    id="select-feature",
                                                    style={'display': 'none'}),
                                                dcc.Checklist(
                                                    id="select-annotation",
                                                    style={'display': 'none'}),
                                                dcc.Input(
                                                    id='entries_size',
                                                    style={'display': 'none'}),
                                                html.Button(
                                                    id='submit-button',
                                                    style={'display': 'none'})
                                            ])
                                    ])),
                            # Variant info tab
                            dcc.Tab(
                                label='Variant info',
                                value='info',
                                children=html.Div(
                                    className='control-tab',
                                    children=[
                                        html.Div(
                                            id='info-tab',
                                            className=
                                            'fullwidth-app-controls-name',
                                            children=[
                                                html.Div(
                                                    'Click on variant to display its information'
                                                )
                                            ])
                                    ]))
                        ])
                ]),
            dcc.Loading(
                className='dashbio-loading',
                children=html.Div(
                    id='variantmap-wrapper',
                    children=[
                        # Error message box
                        html.Div(id='error-msg',
                                 style={
                                     'color': 'crimson',
                                     'text-align': 'center',
                                     'font-size': '18px'
                                 }),
                        # Plot VariantMap figure
                        html.Div(id='variantmap-fig',
                                 children=[
                                     html.Div(dcc.Graph(id='variantmap'),
                                              style={'display': 'none'})
                                 ]),
                        # Plot Slider
                        html.Div(id='batch-slider',
                                 children=[
                                     html.Div('',
                                              style={
                                                  'textAlign': 'center',
                                              }),
                                     html.Div(dcc.Slider(id='slider', ),
                                              style={'display': 'none'})
                                 ])
                    ])),
            # Create Store component to store JSON of dataframe and metadata
            dcc.Store(id='memory'),
            # To store variant counts
            dcc.Store(id='count-store'),
            # To store custom settings
            dcc.Store(id='custom-store'),
            # To store name dictionary
            dcc.Store(id='name_dict'),
            # To store sample labels
            dcc.Store(id='sample_labels'),
            # To store sample order
            dcc.Store(id='sample_order')
        ])
コード例 #19
0
    'value': 'Batch'
}, {
    'label': 'peak_label',
    'value': 'peak_label'
}, {
    'label': 'ms_file',
    'value': 'ms_file'
}]

_layout = html.Div([
    dcc.Tabs(id='ana-secondary-tab',
             value=_modules[0]._label,
             vertical=False,
             children=[
                 dcc.Tab(
                     value=key,
                     label=modules[key]._label,
                 ) for key in modules.keys()
             ]),
    dcc.Dropdown(id='ana-file-types',
                 options=[],
                 placeholder='Types of files to include',
                 multi=True),
    dcc.Dropdown(id='ana-peak-labels-include',
                 options=[],
                 placeholder='Include peak_labels',
                 multi=True),
    dcc.Dropdown(id='ana-peak-labels-exclude',
                 options=[],
                 placeholder='Exclude peak_labels',
                 multi=True),
    dcc.Dropdown(id='ana-ms-order',
コード例 #20
0
ファイル: gui.py プロジェクト: bud42/dax-dashboard
def get_graph_content(dfp, selected_groupby='PROJECT'):
    tabs_content = []
    tab_value = 0

    logging.debug('get_qa_figure')

    # Make a 1x1 figure
    fig = plotly.subplots.make_subplots(rows=1, cols=1)
    fig.update_layout(margin=dict(l=40, r=40, t=40, b=40))

    # Check for empty data
    if len(dfp) == 0:
        logging.debug('empty data, using empty figure')
        return [fig]

    # First we copy the dfp and then replace the values in each
    # scan/proc type column with a metastatus,
    # that gives us a high level status of the type for that session

    # TODO: should we just make a different pivot table here going back to
    # the original df? yes, later
    dfp_copy = dfp.copy()
    for col in dfp_copy.columns:
        if col in ('SESSION', 'PROJECT', 'DATE'):
            # don't mess with these columns
            # TODO: do we need this if we haven't reindexed yet?
            continue

        # Change each value from the multiple values in concatenated
        # characters to a single overall status
        dfp_copy[col] = dfp_copy[col].apply(get_metastatus)

    # The pivot table for the graph is a pivot of the pivot table, instead
    # of having a row per session, this pivot table has a row per
    # pivot_type, we can pivot by type to get counts of each status for each
    # scan/proc type, or we can pivot by project to get counts of sessions
    # for each project
    # The result will be a table with one row per TYPE (index=TYPE),
    # and we'll have a column for each STATUS (so columns=STATUS),
    # and we'll count how many sessions (values='SESSION') we find for each
    # cell
    # get a copy so it's defragmented
    dfp_copy = dfp_copy.reset_index().copy()

    # don't need subject
    dfp_copy = dfp_copy.drop(columns=['SUBJECT'])

    # use pandas melt function to unpivot our pivot table
    df = pd.melt(
        dfp_copy,
        id_vars=(
            'SESSION',
            'PROJECT',
            'DATE',
            'SITE',
            'SESSTYPE',
            'MODALITY'),
        value_name='STATUS')

    # We use fill_value to replace nan with 0
    dfpp = df.pivot_table(
        index='TYPE',
        columns='STATUS',
        values='SESSION',
        aggfunc='count',
        fill_value=0)

    # sort so scans are first, then assessor
    scan_type = []
    assr_type = []
    for cur_type in dfpp.index:
        # Use a regex to test if name ends with _v and a number, then assr
        if re.search('_v\d+$', cur_type):
            assr_type.append(cur_type)
        else:
            scan_type.append(cur_type)

    newindex = scan_type + assr_type
    dfpp = dfpp.reindex(index=newindex)

    # Draw bar for each status, these will be displayed in order
    # ydata should be the types, xdata should be count of status
    # for each type
    for cur_status, cur_color in QASTATUS2COLOR.items():
        ydata = dfpp.index
        if cur_status not in dfpp:
            xdata = [0] * len(dfpp.index)
        else:
            xdata = dfpp[cur_status]

        cur_name = '{} ({})'.format(cur_status, sum(xdata))

        fig.append_trace(
            go.Bar(
                x=ydata,
                y=xdata,
                name=cur_name,
                marker=dict(color=cur_color),
                opacity=0.9),
            1, 1)

    # Customize figure
    fig['layout'].update(barmode='stack', showlegend=True, width=900)

    # Build the tab
    label = 'By {}'.format('TYPE')
    graph = html.Div(dcc.Graph(figure=fig), style={
        'width': '100%', 'display': 'inline-block'})
    tab = dcc.Tab(label=label, value=str(tab_value), children=[graph])
    tabs_content.append(tab)
    tab_value += 1

    # We also want a tab for By Project, so we can ask e.g. how many
    # sessions for each project, and then ask
    # which projects have a T1 and a good FS6_v1
    # later combine with other pivot
    # table and loop on pivot type
    dfpp = df.pivot_table(
        index='PROJECT',
        values='SESSION',
        aggfunc=pd.Series.nunique,
        fill_value=0)

    fig = plotly.subplots.make_subplots(rows=1, cols=1)
    fig.update_layout(margin=dict(l=40, r=40, t=40, b=40))

    ydata = dfpp.index
    xdata = dfpp.SESSION

    cur_name = '{} ({})'.format('ALL', sum(xdata))
    cur_color = RGB_DKBLUE

    fig.append_trace(
        go.Bar(
            x=ydata,
            y=xdata,
            text=xdata,
            name=cur_name,
            marker=dict(color=cur_color),
            opacity=0.9),
        1, 1)

    # Customize figure
    fig['layout'].update(barmode='stack', showlegend=True, width=900)

    # Build the tab
    label = 'By {}'.format('PROJECT')
    graph = html.Div(dcc.Graph(figure=fig), style={
        'width': '100%', 'display': 'inline-block'})
    tab = dcc.Tab(label=label, value=str(tab_value), children=[graph])
    tabs_content.append(tab)
    tab_value += 1

    # Append the by-time graph (this was added later with separate function)
    dfs = df[['PROJECT', 'DATE', 'SESSION', 'SESSTYPE', 'SITE', 'MODALITY']].drop_duplicates()
    fig = sessionsbytime_figure(dfs, selected_groupby)
    label = 'By {}'.format('TIME')
    graph = html.Div(dcc.Graph(figure=fig), style={
        'width': '100%', 'display': 'inline-block'})
    tab = dcc.Tab(label=label, value=str(tab_value), children=[graph])
    tabs_content.append(tab)
    tab_value += 1

    # TODO: write a "graph in a tab" function to wrap each figure above
    # in a graph in a tab, b/c DRY

    # Return the tabs
    return tabs_content
コード例 #21
0
 html.Div(
     className='four columns',
     children=[
         dcc.Tabs(
             id='tabs',
             children=[
                 dcc.Tab(label='Control Panel',
                         children=[
                             drc.NamedDropdown(
                                 name='Layout',
                                 id='dropdown-layout',
                                 options=drc.DropdownOptionsList(
                                     'random', 'grid', 'circle',
                                     'concentric', 'breadthfirst', 'cose',
                                     'cose-bilkent', 'dagre', 'cola',
                                     'klay', 'spread', 'euler'),
                                 value='grid',
                                 clearable=False),
                             drc.NamedRadioItems(
                                 name='Expand',
                                 id='radio-expand',
                                 options=drc.DropdownOptionsList(
                                     'followers', 'following'),
                                 value='followers')
                         ]),
                 dcc.Tab(
                     label='JSON',
                     children=[
                         html.Div(style=styles['tab'],
                                  children=[
                                      html.P('Node Object JSON:'),
コード例 #22
0
ファイル: test_tabs_with_graphs.py プロジェクト: delsim/dash
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() == []
コード例 #23
0
ファイル: test_graph_varia.py プロジェクト: delsim/dash
def test_grva006_unmounted_graph_resize(dash_dcc, is_eager):
    app = Dash(__name__, eager_loading=is_eager)

    app.layout = html.Div(children=[
        dcc.Tabs(
            id="tabs",
            children=[
                dcc.Tab(
                    label="Tab one",
                    children=[
                        html.Div(
                            [
                                dcc.Graph(
                                    id="eg-graph-1",
                                    figure={
                                        "data": [
                                            {
                                                "x": [1, 2, 3],
                                                "y": [4, 1, 2],
                                                "type": "scattergl",
                                                "name": "SF",
                                            },
                                            {
                                                "x": [1, 2, 3],
                                                "y": [2, 4, 5],
                                                "type": "scattergl",
                                                "name": "Montréal",
                                            },
                                        ]
                                    },
                                )
                            ],
                            id="graph-tab-1",
                        )
                    ],
                ),
                dcc.Tab(
                    label="Tab two",
                    children=[
                        dcc.Graph(
                            id="eg-graph-2",
                            figure={
                                "data": [
                                    {
                                        "x": [1, 2, 3],
                                        "y": [1, 4, 1],
                                        "type": "scattergl",
                                        "name": "SF",
                                    },
                                    {
                                        "x": [1, 2, 3],
                                        "y": [1, 2, 3],
                                        "type": "scattergl",
                                        "name": "Montréal",
                                    },
                                ]
                            },
                        )
                    ],
                    id="graph-tab-2",
                ),
            ],
        )
    ])

    dash_dcc.start_server(app)

    try:
        dash_dcc.wait_for_element("#eg-graph-1")
    except Exception as e:
        print(
            dash_dcc.wait_for_element("#_dash-app-content").get_attribute(
                "innerHTML"))
        raise e

    WebDriverWait(dash_dcc.driver,
                  10).until(EC.element_to_be_clickable((By.ID, "graph-tab-2")))

    tab_two = dash_dcc.wait_for_element("#graph-tab-2")

    tab_two.click()

    # save the current window size
    window_size = dash_dcc.driver.get_window_size()

    # resize
    dash_dcc.driver.set_window_size(800, 600)

    # set back to original size
    dash_dcc.driver.set_window_size(window_size["width"],
                                    window_size["height"])

    assert dash_dcc.get_logs() == []
コード例 #24
0
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
コード例 #25
0
}
TAB_SELECTED_STYLE = {
    'borderTop': '1px solid #d6d6d6',
    'borderBottom': '1px solid #d6d6d6',
    'backgroundColor': '#119DFF',
    'color': 'white',
    'padding': '6px'
}

app.layout = html.Div([
    dcc.Tabs(id="tabs-flow-dash",
             value="tab-flows",
             children=[
                 dcc.Tab(label="Flow",
                         value="tab-flows",
                         style=TAB_STYLE,
                         selected_style=TAB_SELECTED_STYLE,
                         children=generate_tab_flow()),
                 dcc.Tab(label="Other",
                         value="tab-other",
                         style=TAB_STYLE,
                         selected_style=TAB_SELECTED_STYLE,
                         children=generate_tab_other()),
             ],
             style=TABS_STYLES),
    html.Div(id="tabs-content")
])


def prettifyBytes(bytes_received):
    size_names = ['B', 'KB', 'MB', 'GB', 'TB']
コード例 #26
0
ファイル: index.py プロジェクト: pernaletec/diogenet_py
                    value=[4, 6]),
    html.H6('Download travel edges graph data', className="mt-5 mb-3"),
    dbc.Button("Download Data",
               id="btn_csv_map",
               style={'backgroundColor': '#716450'},
               className="ml-3"),
    dcc.Download(id="download-dataframe-csv-map"),
]

tabs = dcc.Tabs(id='tabs_map',
                value='map_maps',
                parent_className='custom-tabs',
                className='custom-tabs-container',
                children=[
                    dcc.Tab(label='Map',
                            value='map_maps',
                            className='custom-tab',
                            selected_className='custom-tab--selected'),
                    dcc.Tab(label='Metrics',
                            value='map_metrics',
                            className='custom-tab',
                            selected_className='custom-tab--selected'),
                    dcc.Tab(label='Graph',
                            value='map_graphs',
                            className='custom-tab',
                            selected_className='custom-tab--selected'),
                ])

row = html.Div([
    dbc.Row(navbar),
    dbc.Row([
        dbc.Col(html.Div(sidebar_content),
コード例 #27
0
def test_cbsc004_callback_using_unloaded_async_component(dash_duo):
    app = Dash()
    app.layout = html.Div(
        [
            dcc.Tabs(
                [
                    dcc.Tab("boo!"),
                    dcc.Tab(
                        dash_table.DataTable(
                            id="table",
                            columns=[{"id": "a", "name": "A"}],
                            data=[{"a": "b"}],
                        )
                    ),
                ]
            ),
            html.Button("Update Input", id="btn"),
            html.Div("Hello", id="output"),
            html.Div(id="output2"),
        ]
    )

    @app.callback(
        Output("output", "children"),
        [Input("btn", "n_clicks")],
        [State("table", "data")],
    )
    def update_out(n_clicks, data):
        return json.dumps(data) + " - " + str(n_clicks)

    @app.callback(
        Output("output2", "children"),
        [Input("btn", "n_clicks")],
        [State("table", "derived_viewport_data")],
    )
    def update_out2(n_clicks, data):
        return json.dumps(data) + " - " + str(n_clicks)

    dash_duo.start_server(app)

    dash_duo.wait_for_text_to_equal("#output", '[{"a": "b"}] - None')
    dash_duo.wait_for_text_to_equal("#output2", "null - None")

    dash_duo.find_element("#btn").click()
    dash_duo.wait_for_text_to_equal("#output", '[{"a": "b"}] - 1')
    dash_duo.wait_for_text_to_equal("#output2", "null - 1")

    dash_duo.find_element(".tab:not(.tab--selected)").click()
    dash_duo.wait_for_text_to_equal("#table th", "A")
    # table props are in state so no change yet
    dash_duo.wait_for_text_to_equal("#output2", "null - 1")

    # repeat a few times, since one of the failure modes I saw during dev was
    # intermittent - but predictably so?
    for i in range(2, 10):
        expected = '[{"a": "b"}] - ' + str(i)
        dash_duo.find_element("#btn").click()
        dash_duo.wait_for_text_to_equal("#output", expected)
        # now derived props are available
        dash_duo.wait_for_text_to_equal("#output2", expected)

    assert dash_duo.get_logs() == []
コード例 #28
0
ファイル: layout.py プロジェクト: Olbert/Thesis
def create_layout(app):
    # Actual layout of the app
    return html.Div(
        className="row",
        style={
            "max-width": "100%",
            "font-size": "1.5rem",
            "padding": "0px 0px"
        },
        children=[
            # Header
            html.Div(
                className="row header",
                id="app-header",
                style={"background-color": "#f9f9f9"},
                children=[
                    html.Div(
                        [
                            html.Img(
                                src=app.get_asset_url("bonn-logo.png"),
                                className="logo",
                                id="bonn-image",
                            )
                        ],
                        className="three columns header_img",
                    ),
                    html.Div(
                        [
                            html.H3(
                                "Visualizing the effects of domain shift on CNN based image segmentation",
                                className="header_title",
                                id="app-title",
                            )
                        ],
                        className="nine columns header_title_container",
                    ),
                ],
            ),

            # Body
            dcc.Store(id='long_term_memory'),
            dcc.Store(id='reductor_memory'),
            dcc.Store(id='map-memory', data=(0, 0)),
            dcc.Store(id='side_click'),
            dcc.Store(id='model_path-memory'),
            dcc.Store(id='database_domains-memory'),
            dcc.Store(id='label_domains-memory'),
            dcc.Store(id='page-memory'),
            html.Div([
                dcc.Tabs(
                    id="tabs-styled-with-inline",
                    value='tab-0',
                    children=[
                        dcc.Tab(label='Tool setup',
                                value='tab-0',
                                style=tab_style,
                                selected_style=tab_selected_style),
                        dcc.Tab(label='Dimentionality reduction',
                                value='tab-1',
                                style=tab_style,
                                selected_style=tab_selected_style),
                        dcc.Tab(label='Feature map explorer',
                                value='tab-2',
                                style=tab_style,
                                selected_style=tab_selected_style),
                        # dcc.Tab(label='Autoencoder?',             value='tab-3', style=tab_style, selected_style=tab_selected_style),
                        dcc.Tab(label='About',
                                value='tab-4',
                                style=tab_style,
                                selected_style=tab_selected_style),
                    ],
                    style=tabs_styles),
                html.Div(id='tabs-content-inline')
            ]),
            html.Div(id='user-cache',
                     style={'display': 'none'},
                     children=json.dumps(initial_layout)),
            html.Div(id='invisible_text', style={'visible': 'False'}),
        ],
    )
コード例 #29
0
def platter_app():
    app = Dash(__name__)

    app.layout = html.Div([
        html.Div(id="waitfor"),
        html.Label("Upload"),
        dcc.Upload(),
        html.Label("Horizontal Tabs"),
        dcc.Tabs(
            id="tabs",
            children=[
                dcc.Tab(
                    label="Tab one",
                    className="test",
                    style={"border": "1px solid magenta"},
                    children=[html.Div(["Test"])],
                ),
                dcc.Tab(
                    label="Tab two",
                    children=[
                        html.Div([
                            html.H1("This is the content in tab 2"),
                            html.P("A graph here would be nice!"),
                        ])
                    ],
                    id="tab-one",
                ),
                dcc.Tab(
                    label="Tab three",
                    children=[
                        html.Div([html.H1("This is the content in tab 3")])
                    ],
                ),
            ],
            style={"fontFamily": "system-ui"},
            content_style={
                "border": "1px solid #d6d6d6",
                "padding": "44px"
            },
            parent_style={
                "maxWidth": "1000px",
                "margin": "0 auto"
            },
        ),
        html.Label("Vertical Tabs"),
        dcc.Tabs(
            id="tabs1",
            vertical=True,
            children=[
                dcc.Tab(label="Tab one", children=[html.Div(["Test"])]),
                dcc.Tab(
                    label="Tab two",
                    children=[
                        html.Div([
                            html.H1("This is the content in tab 2"),
                            html.P("A graph here would be nice!"),
                        ])
                    ],
                ),
                dcc.Tab(
                    label="Tab three",
                    children=[
                        html.Div([html.H1("This is the content in tab 3")])
                    ],
                ),
            ],
        ),
        html.Label("Dropdown"),
        dcc.Dropdown(options=OPTIONS, value="MTL", id="dropdown"),
        html.Label("Multi-Select Dropdown"),
        dcc.Dropdown(options=OPTIONS, value=["MTL", "SF"], multi=True),
        html.Label("Radio Items"),
        dcc.RadioItems(options=OPTIONS, value="MTL"),
        html.Label("Checkboxes"),
        dcc.Checklist(options=OPTIONS, value=["MTL", "SF"]),
        html.Label("Text Input"),
        dcc.Input(value="", placeholder="type here", id="textinput"),
        html.Label("Disabled Text Input"),
        dcc.Input(
            value="disabled",
            type="text",
            id="disabled-textinput",
            disabled=True,
        ),
        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,
        ),
        html.Label("Graph"),
        dcc.Graph(
            id="graph",
            figure={
                "data": [{
                    "x": [1, 2, 3],
                    "y": [4, 1, 4]
                }],
                "layout": {
                    "title": "北京"
                },
            },
        ),
        html.Div([
            html.Label("DatePickerSingle"),
            dcc.DatePickerSingle(id="date-picker-single",
                                 date=datetime(1997, 5, 10)),
            html.Div(
                [
                    html.Label("DatePickerSingle - empty input"),
                    dcc.DatePickerSingle(),
                ],
                id="dt-single-no-date-value",
            ),
            html.Div(
                [
                    html.Label(
                        "DatePickerSingle - initial visible month (May 97)"),
                    dcc.DatePickerSingle(
                        initial_visible_month=datetime(1997, 5, 10)),
                ],
                id="dt-single-no-date-value-init-month",
            ),
        ]),
        html.Div([
            html.Label("DatePickerRange"),
            dcc.DatePickerRange(
                id="date-picker-range",
                start_date_id="startDate",
                end_date_id="endDate",
                start_date=datetime(1997, 5, 3),
                end_date_placeholder_text="Select a date!",
            ),
            html.Div(
                [
                    html.Label("DatePickerRange - empty input"),
                    dcc.DatePickerRange(
                        start_date_id="startDate",
                        end_date_id="endDate",
                        start_date_placeholder_text="Start date",
                        end_date_placeholder_text="End date",
                    ),
                ],
                id="dt-range-no-date-values",
            ),
            html.Div(
                [
                    html.Label(
                        "DatePickerRange - initial visible month (May 97)"),
                    dcc.DatePickerRange(
                        start_date_id="startDate",
                        end_date_id="endDate",
                        start_date_placeholder_text="Start date",
                        end_date_placeholder_text="End date",
                        initial_visible_month=datetime(1997, 5, 10),
                    ),
                ],
                id="dt-range-no-date-values-init-month",
            ),
        ]),
        html.Label("TextArea"),
        dcc.Textarea(placeholder="Enter a value... 北京",
                     style={"width": "100%"}),
        html.Label("Markdown"),
        dcc.Markdown("""
            #### Dash and Markdown

            Dash supports [Markdown](https://rexxars.github.io/react-markdown/).

            Markdown is a simple way to write and format text.
            It includes a syntax for things like **bold text** and *italics*,
            [links](https://rexxars.github.io/react-markdown/), inline `code` snippets, lists,
            quotes, and more.

            1. Links are auto-rendered: https://dash.plotly.com.
            2. This uses ~commonmark~ GitHub flavored markdown.

            Tables are also supported:

            | First Header  | Second Header |
            | ------------- | ------------- |
            | Content Cell  | Content Cell  |
            | Content Cell  | Content Cell  |

            北京
        """.replace("    ", "")),
        dcc.Markdown(["# Line one", "## Line two"]),
        dcc.Markdown(),
        dcc.Markdown("""
            ```py
            import python
            print(3)
            ```"""),
        dcc.Markdown(["```py", "import python", "print(3)", "```"]),
        dcc.Markdown(),
    ])

    yield app
コード例 #30
0
ファイル: test_tabs_with_graphs.py プロジェクト: delsim/dash
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() == []