Ejemplo n.º 1
0
 def display_output(react_value, flow_value):
     return html.Div([
         "You have entered {} and {}".format(react_value, flow_value),
         html.Hr(),
         html.Label("Flow Component Docstring"),
         html.Pre(dash_flow_example.ExampleFlowComponent.__doc__),
         html.Hr(),
         html.Label("React PropTypes Component Docstring"),
         html.Pre(dash_flow_example.ExampleReactComponent.__doc__),
         html.Div(id="waitfor"),
     ])
Ejemplo n.º 2
0
 def content(_):
     return html.Div([
         html.Div(42, id="above-in"),
         html.Div(id="above-dummy"),
         html.Hr(),
         html.Div(0, id="above-out"),
         html.Div(0, id="below-out"),
         html.Hr(),
         html.Div(id="below-dummy"),
         html.Div(44, id="below-in"),
     ])
Ejemplo n.º 3
0
def test_inin006_flow_component(dash_duo):
    app = Dash()

    app.layout = html.Div([
        dash_flow_example.ExampleReactComponent(id="react",
                                                value="my-value",
                                                label="react component"),
        dash_flow_example.ExampleFlowComponent(id="flow",
                                               value="my-value",
                                               label="flow component"),
        html.Hr(),
        html.Div(id="output"),
    ])

    @app.callback(Output("output", "children"),
                  [Input("react", "value"),
                   Input("flow", "value")])
    def display_output(react_value, flow_value):
        return html.Div([
            "You have entered {} and {}".format(react_value, flow_value),
            html.Hr(),
            html.Label("Flow Component Docstring"),
            html.Pre(dash_flow_example.ExampleFlowComponent.__doc__),
            html.Hr(),
            html.Label("React PropTypes Component Docstring"),
            html.Pre(dash_flow_example.ExampleReactComponent.__doc__),
            html.Div(id="waitfor"),
        ])

    dash_duo.start_server(app)
    dash_duo.wait_for_element("#waitfor")
    dash_duo.percy_snapshot(name="flowtype")
def test_dbpo003_popover_legacy(dash_duo):
    app = Dash(external_stylesheets=[themes.BOOTSTRAP])

    app.layout = html.Div(
        [
            html.Div("No Target Here", id="not-a-target"),
            html.Hr(),
            Popover(
                [PopoverHeader("Test Header"),
                 PopoverBody("Test content")],
                id="popover",
                target="popover-target",
                trigger="legacy",
            ),
            html.Div("Target", id="popover-target"),
        ],
        className="container p-5 w-50",
    )

    dash_duo.start_server(app)

    dash_duo.wait_for_element_by_id("popover-target").click()
    dash_duo.wait_for_text_to_equal(".popover-body", "Test content", timeout=4)

    # Try clicking on the popover - shouldn't dismiss
    dash_duo.wait_for_element_by_id("popover").click()
    dash_duo.wait_for_text_to_equal(".popover-body", "Test content", timeout=4)

    # Try clicking outside the popover - should dismiss
    dash_duo.wait_for_element_by_id("not-a-target").click()
    wait.until(
        lambda: len(dash_duo.find_elements("#popover")) == 0,
        timeout=4,
    )
Ejemplo n.º 5
0
def display_plot_data_tb(display_check, jsonized_df_export, test_passed):
    if display_check == ['display']:
        if test_passed is True:
            dataset = json.loads(jsonized_df_export[0])
            df_to_export = pd.read_json(dataset, orient='split')
            df_tb_div_list = [
                html.Hr(),
                dt.DataTable(
                    id=app_id_dict['df_export_tb'],
                    data=df_to_export.to_dict('records'),
                    columns=[{
                        'name': each_col,
                        'id': each_col
                    } for each_col in df_to_export.columns],
                    export_format='csv',
                    style_data_conditional=[striped_rows],
                    fixed_rows={
                        'headers': True,
                        'data': 0
                    },
                    style_table={
                        'maxHeight': '300',
                        'overflowY': 'scroll',
                    },
                )
            ]
            return [df_tb_div_list]
        else:
            return [None]
    else:
        return [None]
Ejemplo n.º 6
0
def ninput_app():
    app = Dash(__name__)
    app.layout = html.Div([
        dcc.Input(
            id="input_false",
            type="number",
            debounce=False,
            placeholder="debounce=False",
        ),
        html.Div(id="div_false"),
        html.Hr(id="silent-break-line"),
        dcc.Input(
            id="input_true",
            type="number",
            debounce=True,
            placeholder="debounce=True",
        ),
        html.Div(id="div_true"),
    ])

    @app.callback(
        [Output("div_false", "children"),
         Output("div_true", "children")],
        [Input("input_false", "value"),
         Input("input_true", "value")],
    )
    def render(fval, tval):
        return fval, tval

    yield app
Ejemplo n.º 7
0
def init_dashboard(server):
    dash_app = dash.Dash(
        server=server,
        routes_pathname_prefix="/",
        external_stylesheets=[dbc.themes.SUPERHERO],
    )
    
    dash_app.title = 'Covid-19 Dashboard'
    
    #lo Create Layout
    dash_app.layout = dbc.Container(
        [
            html.H1("USA Covid-19 Dashboard"),
            html.P(children=['Last updated: ',last_update], style={'text-align': 'right'}),
            html.Hr(),
            dbc.Tabs(
                [
                    dbc.Tab(label="Overview", tab_id="tab-1"),
                    dbc.Tab(label="Testing", tab_id="tab-3"),
                    dbc.Tab(label="Hospitalizations", tab_id="tab-4"),
                    dbc.Tab(label="Deaths", tab_id="tab-5"),
                    dbc.Tab(label="Vaccination", tab_id="tab-2"),
                    dbc.Tab(label="About", tab_id="tab-6"),
                    ],
                id = 'tabs',
                active_tab = 'tab-1',
                ),
            html.Div(id="tab-content", className="p-4"),
            html.Br(),
            html.Div(id="drop_figure"),
            ]
        )
    init_callbacks(dash_app)
    
    return dash_app.server
Ejemplo n.º 8
0
 def layout(self) -> html.Div:
     return html.Div(
         style={"marginLeft": "10px", "height": "90vh"},
         children=[
             html.Div(
                 children=[
                     html.Label(
                         "Tornado Plot",
                         style={
                             "textAlign": "center",
                             "font-weight": "bold",
                         },
                     ),
                     wcc.RadioItems(
                         vertical=False,
                         id=self.ids("plot-or-table"),
                         options=[
                             {"label": "Show bars", "value": "bars"},
                             {
                                 "label": "Show table",
                                 "value": "table",
                             },
                         ],
                         value="bars",
                     ),
                 ],
             ),
             html.Div(
                 style={"overflowY": "auto", "height": "60vh"},
                 children=[
                     html.Div(
                         id=self.ids("graph-wrapper"),
                         style={},
                         children=wcc.Graph(
                             id=self.ids("tornado-graph"),
                             config={"displayModeBar": False},
                         ),
                     ),
                     html.Div(
                         id=self.ids("table-wrapper"),
                         style={"display": "none"},
                         children=dash_table.DataTable(
                             id=self.ids("tornado-table"),
                             style_cell={
                                 "whiteSpace": "normal",
                                 "height": "auto",
                             },
                         ),
                     ),
                 ],
             ),
             html.Hr(style={"marginTop": "10px"}),
             self.settings_layout,
             dcc.Store(id=self.ids("storage"), storage_type="session"),
             dcc.Store(id=self.ids("click-store"), storage_type="session"),
             dcc.Store(id=self.ids("high-low-storage"), storage_type="session"),
             dcc.Store(id=self.ids("client-height-pixels"), storage_type="session"),
         ],
     )
Ejemplo n.º 9
0
def render_page_content(pathname):
    if pathname[1:] in COMPRESSOR_TAGS:
        return page_layout()
    # If the user tries to reach a different page, return a 404 message
    return dbc.Jumbotron(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ]
    )
Ejemplo n.º 10
0
    def render_page_content(pathname):
        if pathname in ["", "/", "/dash", "/dash/table"]:
            return table.layout
        elif pathname == "/dash/map":
            return map.layout

        # If the user tries to reach a different page, return a 404 message
        return dbc.Jumbotron([
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ])
Ejemplo n.º 11
0
def get_app_layout():
    return dbc.Container([
        dcc.Store(id='selected-data-left'),
        dcc.Store(id='selected-data-right'),
        dcc.Store(id='session-id', data=str(uuid.uuid4())),
        dcc.Store(id='filter-trigger', data=0),
        dcc.Store(id='left-hide-trigger', data=0),
        dcc.Store(id='file-loaded-trigger', data=0),
        dcc.Store(id='dummy-export-scatter2d-left'),
        dcc.Store(id='dummy-export-scatter2d-right'),
        dcc.Store(id='dummy-export-histogram'),
        dcc.Store(id='dummy-export-violin'),
        dcc.Store(id='dummy-export-parallel'),
        dcc.Store(id='dummy-export-heatmap'),
        dcc.Store(id='dummy-export-data'),

        html.Div(
            [
                html.Div(html.Img(
                    src=app.get_asset_url('sensorview_logo.svg'),
                    id='sensorview-image',
                    style={
                        'height': '100px',
                        'width': 'auto',
                    },
                ), className="text-center"),
                html.H1(app.title, className="text-center"),
                html.Hr(className="my-2"),
                html.P(
                    'Sensor Data Visualization', className="text-center"
                ),
            ],
            className="bg-light rounded-3 my-2 p-3",
        ),

        dbc.Row([
            dbc.Col(
                dbc.CardGroup([
                    testcase_card,
                    datafile_card
                ])
            )], className='mb-3'),

        tabs,

        dcc.Markdown(
            'Designed and developed by **Zhengyu Peng** \
                | Powered by [Dash](https://plotly.com/dash/),\
                [Redis](https://redis.io/),\
                [Celery](https://docs.celeryproject.org/en/stable/),\
                [Docker](https://www.docker.com/)'),
    ], fluid=True, className="dbc_light")
Ejemplo n.º 12
0
def LabeledSection(label, children):
    """Returns a Div row that contains a label title in the left column ('label')
    and other content in the right column.  'children' should be a list of HTML
    elements and Dash Components to render in the right column.
    """
    return html.Div(children=[
        html.Hr(),
        html.Div(className='row',
                 children=[
                     html.P(label, className='two columns section-title'),
                     html.Div(className='ten columns', children=children)
                 ])
    ])
Ejemplo n.º 13
0
def load_data_by_type(filetype, contents):
    children = []
    _type, payload = contents.split(",")
    if filetype in {"csv", "xlsx", "xls"}:
        children = [load_table(filetype, payload)]
    elif filetype in {"png", "svg"}:
        children = [html.Img(src=contents)]

    children += [
        html.Hr(),
        html.Div("Raw Content", id="raw-title"),
        html.Pre(payload, style=pre_style),
    ]
    return html.Div(children)
Ejemplo n.º 14
0
def render_page_content(pathname):
    """Updates page content on url change or navbar click, returns a 404 if url not found in PAGES"""

    try:
        return next(filter(lambda x: x['url'] == pathname, PAGES))['container']
    except StopIteration:
        return dbc.Container(
            [
                html.H1("404: Not found", className='text-danger display-3'),
                html.Hr(className='my-2'),
                html.P(f''),
            ],
            className='p-3 rounded-3'
        )
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
def render_page_content(pathname):
    if pathname == "/":
        return html.P("This is the home page!")
    elif pathname == "/calendar":
        return html.P("This is your calendar... not much in the diary...")
    elif pathname == "/messages":
        return html.P("Here are all your messages")
    # If the user tries to reach a different page, return a 404 message
    return html.Div(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ],
        className="p-3 bg-light rounded-3",
    )
Ejemplo n.º 17
0
 def set_content(n1):
     return [
         html.Div([
             html.Div(
                 [
                     html.Div(id={
                         "i": i,
                         "j": j
                     }) for i in range(((n1 or 0) + j) % 4)
                 ],
                 className="content{}".format(j),
             ),
             html.Div(id={"j": j}, className="output{}".format(j)),
             html.Hr(),
         ]) for j in range(4)
     ]
Ejemplo n.º 18
0
def render_page_content(pathname):
    if pathname == "/":
        return html.P("This is the content of the home page!")
    elif pathname == "/page-1":
        return html.P("This is the content of page 1. Yay!")
    elif pathname == "/page-2":
        return html.P("Oh cool, this is page 2!")
    # If the user tries to reach a different page, return a 404 message
    return html.Div(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ],
        className="p-3 bg-light rounded-3",
    )
Ejemplo n.º 19
0
def getSidebar():
    html.Div(
        [
            html.H2("Trace Interop", className="display-4"),
            html.Hr(),
            html.P("CI/CD Testing", className="lead"),
            dbc.Nav(
                [
                    dbc.NavLink("Home", href="#overview"),
                    dbc.NavLink("Summary", href="#summary"),
                    dbc.NavLink("Results", href="#results"),
                    dbc.NavLink("Details", href="#details"),
                ],
                vertical=True,
                pills=True,
            ),
        ],
        style=SIDEBAR_STYLE,
    )
Ejemplo n.º 20
0
def parse_contents(contents, filename, date):
	"""
	parses csv oor xls
	"""
	content_type, content_string = contents.split(',')

	decoded = base64.b64decode(content_string)
	try:
		if 'csv' in filename:
			# Assume that the user uploaded a CSV file
			df = pd.read_csv(
				io.StringIO(decoded.decode('utf-8')))
		elif 'xls' in filename:
			# Assume that the user uploaded an excel file
			df = pd.read_excel(io.BytesIO(decoded))
	except Exception as e:
		print(e)
		return html.Div([
			'There was an error processing this file.'
		])

	return html.Div([
		html.H5(f'Loaded file: {filename}'),
		#html.H6(datetime.datetime.fromtimestamp(date)),
		html.H6('First Few Rows are:'),
		dash_table.DataTable(
			data=df.head().to_dict('records'),
			columns=[{'name': i, 'id': i} for i in df.columns]
		),

		html.Hr(),  # horizontal line

		# For debugging, display the raw contents provided by the web browser
		#html.Div('Raw Content'),
		#html.Pre(contents[0:200] + '...', style={
		#	'whiteSpace': 'pre-wrap',
		#	'wordBreak': 'break-all'
		#})
	])
Ejemplo n.º 21
0
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

all_options = {
    'America': ['New York City', 'San Francisco', 'Cincinnati'],
    'Canada': [u'Montréal', 'Toronto', 'Ottawa']
}
app.layout = html.Div([
    dcc.RadioItems(id='countries-radio',
                   options=[{
                       'label': k,
                       'value': k
                   } for k in all_options.keys()],
                   value='America'),
    html.Hr(),
    dcc.RadioItems(id='cities-radio'),
    html.Hr(),
    html.Div(id='display-selected-values')
])


# set the available options for the cities based on the country
@app.callback(Output('cities-radio', 'options'),
              Input('countries-radio', 'value'))
def set_cities_options(selected_country):
    return [{'label': i, 'value': i} for i in all_options[selected_country]]


# set the default city to be the first city available for that country
@app.callback(Output('cities-radio', 'value'), Input('cities-radio',
Ejemplo n.º 22
0
         ),
     ],
     className="row",
     style={"columnCount": 2},
 ),
 html.Div(
     [
         "Input symbol for counterfactual:",
         dcc.Input(id="sim-input", type="text"),
         html.Button(id="sim-submit", children="Submit", n_clicks=0),
     ],
     id="sim-selector-container",
     hidden=True,
     style={"text-align": "left"},
 ),
 html.Hr(style={"margin-bottom": 0, "margin-top": 0}),
 html.Div(
     [
         html.Div(
             [
                 dcc.DatePickerRange(
                     id="date-selector",
                     start_date=datetime.today(),
                     end_date=datetime.today(),
                     display_format="MMM Do, YYYY",
                 ),
                 html.Div(id="value", children="Value box"),
             ],
             className="six columns",
             style={"text-align": "left"},
         ),
Ejemplo n.º 23
0
def get_404(pathname):
    return html.Div([
        html.H1("404: Not found", className="text-danger"),
        html.Hr(),
        html.P(f"The pathname {pathname} was not recognised...")
    ])
Ejemplo n.º 24
0
import dash_bootstrap_components as dbc
from dash import html

nav_contents = [
    dbc.NavItem(dbc.NavLink("Active", href="#", active=True)),
    dbc.NavItem(dbc.NavLink("A much longer link label", href="#")),
    dbc.NavItem(dbc.NavLink("Link", href="#")),
]

nav1 = dbc.Nav(nav_contents, pills=True, fill=True)

nav2 = dbc.Nav(nav_contents, pills=True, justified=True)

navs = html.Div([nav1, html.Hr(), nav2])
Ejemplo n.º 25
0
def todo_app(content_callback=False):
    app = dash.Dash(__name__)

    content = html.Div([
        html.Div("Dash To-Do list"),
        dcc.Input(id="new-item"),
        html.Button("Add", id="add"),
        html.Button("Clear Done", id="clear-done"),
        html.Div(id="list-container"),
        html.Hr(),
        html.Div(id="totals"),
    ])

    if content_callback:
        app.layout = html.Div([html.Div(id="content"), dcc.Location(id="url")])

        @app.callback(Output("content", "children"),
                      [Input("url", "pathname")])
        def display_content(_):
            return content

    else:
        app.layout = content

    style_todo = {"display": "inline", "margin": "10px"}
    style_done = {"textDecoration": "line-through", "color": "#888"}
    style_done.update(style_todo)

    app.list_calls = Value("i", 0)
    app.style_calls = Value("i", 0)
    app.preceding_calls = Value("i", 0)
    app.total_calls = Value("i", 0)

    @app.callback(
        Output("list-container", "children"),
        Output("new-item", "value"),
        Input("add", "n_clicks"),
        Input("new-item", "n_submit"),
        Input("clear-done", "n_clicks"),
        State("new-item", "value"),
        State({"item": ALL}, "children"),
        State({
            "item": ALL,
            "action": "done"
        }, "value"),
    )
    def edit_list(add, add2, clear, new_item, items, items_done):
        app.list_calls.value += 1
        triggered = [t["prop_id"] for t in dash.callback_context.triggered]
        adding = len([
            1 for i in triggered if i in ("add.n_clicks", "new-item.n_submit")
        ])
        clearing = len([1 for i in triggered if i == "clear-done.n_clicks"])
        new_spec = [(text, done) for text, done in zip(items, items_done)
                    if not (clearing and done)]
        if adding:
            new_spec.append((new_item, []))

        # Check callback context use of grouping
        assert not dash.callback_context.using_args_grouping
        assert not dash.callback_context.using_outputs_grouping

        new_list = [
            html.Div(
                [
                    dcc.Checklist(
                        id={
                            "item": i,
                            "action": "done"
                        },
                        options=[{
                            "label": "",
                            "value": "done"
                        }],
                        value=done,
                        style={"display": "inline"},
                    ),
                    html.Div(text,
                             id={"item": i},
                             style=style_done if done else style_todo),
                    html.Div(id={
                        "item": i,
                        "preceding": True
                    },
                             style=style_todo),
                ],
                style={"clear": "both"},
            ) for i, (text, done) in enumerate(new_spec)
        ]
        return [new_list, "" if adding else new_item]

    @app.callback(
        Output({"item": MATCH}, "style"),
        Input({
            "item": MATCH,
            "action": "done"
        }, "value"),
    )
    def mark_done(done):
        app.style_calls.value += 1
        return style_done if done else style_todo

    @app.callback(
        Output({
            "item": MATCH,
            "preceding": True
        }, "children"),
        Input({
            "item": ALLSMALLER,
            "action": "done"
        }, "value"),
        Input({
            "item": MATCH,
            "action": "done"
        }, "value"),
    )
    def show_preceding(done_before, this_done):
        app.preceding_calls.value += 1
        if this_done:
            return ""
        all_before = len(done_before)
        done_before = len([1 for d in done_before if d])
        out = "{} of {} preceding items are done".format(
            done_before, all_before)
        if all_before == done_before:
            out += " DO THIS NEXT!"
        return out

    @app.callback(Output("totals", "children"),
                  Input({
                      "item": ALL,
                      "action": "done"
                  }, "value"))
    def show_totals(done):
        app.total_calls.value += 1
        count_all = len(done)
        count_done = len([d for d in done if d])
        result = "{} of {} items completed".format(count_done, count_all)
        if count_all:
            result += " - {}%".format(int(100 * count_done / count_all))
        return result

    return app
Ejemplo n.º 26
0
def get_map_map(tab, dataset_selection, traveler, centrality_index, label_size,
                node_size):

    map_graph = diogenetGraph("map", dataset_selection, dataset_selection,
                              'locations_data.csv', 'travels_blacklist.csv')

    if tab == "map_maps":
        data = None
        mapa = None

        map_graph.current_centrality_index = centrality_index
        if traveler == "All" or traveler == []:
            map_graph.edges_filter = []
        else:
            for m_filter in traveler:
                map_graph.set_edges_filter(m_filter)
            map_graph.create_subgraph()

        data = map_graph.get_map_data(min_weight=node_size[0],
                                      max_weight=node_size[1])
        df = pd.DataFrame(data)

        #Folium base map configurations
        url = 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}'
        attribution = '&copy; <a href="https://developers.arcgis.com/">ArcGIS</a> '

        base_map = folium.Map(location=[35, 30],
                              min_zoom=4,
                              max_zoom=7,
                              zoom_start=6,
                              tiles=None,
                              attr=attribution)

        folium.TileLayer(
            tiles=url,
            show=True,
            attr=attribution,
            min_zoom=3,
            max_zoom=8,
            name="USGS - The National Map",
        ).add_to(base_map)

        markers_source = folium.FeatureGroup(name='Source').add_to(base_map)
        markers_target = folium.FeatureGroup(name='Target').add_to(base_map)

        for i in range(len(df['Source'])):
            #source marker
            popup_source = folium.Popup(str(
                "{} \n (lat = {:.1f}, \n lon={:.1f})".format(
                    df['Source'][i], df["SourceLatitude"][i],
                    df["SourceLongitude"][i])),
                                        parse_html=True,
                                        max_width=450)
            tooltip_source = "{} (lat = {:.1f}, lon={:.1f})".format(
                df['Source'][i], df["SourceLatitude"][i],
                df["SourceLongitude"][i])

            markers_source.add_child(
                folium.CircleMarker(location=(float(df["SourceLatitude"][i]),
                                              float(df["SourceLongitude"][i])),
                                    popup=popup_source,
                                    tooltip=tooltip_source,
                                    fill=True,
                                    color=df["SourceColor"][i],
                                    fill_color=df["SourceColor"][i],
                                    radius=int(df["SourceSize"][i] * 1.3)))

            #target marker
            popup_target = folium.Popup(str(
                "{} \n (lat = {:.1f}, \n lon={:.1f})".format(
                    df['Destination'][i], df["DestLatitude"][i],
                    df["DestLongitude"][i])),
                                        parse_html=True,
                                        max_width=450)
            tooltip_target = "{} (lat = {:.1f}, lon={:.1f})".format(
                df['Destination'][i], df["DestLatitude"][i],
                df["DestLongitude"][i])

            markers_target.add_child(
                folium.CircleMarker(location=(float(df["DestLatitude"][i]),
                                              float(df["DestLongitude"][i])),
                                    popup=popup_target,
                                    tooltip=tooltip_target,
                                    fill=True,
                                    color=df["DestinationColor"][i],
                                    fill_color=df["DestinationColor"][i],
                                    radius=int(df["DestinationSize"][i] *
                                               1.3)))

            # travel info line
            folium.PolyLine(
                [[df["SourceLatitude"][i], df["SourceLongitude"][i]],
                 [df["DestLatitude"][i], df["DestLongitude"][i]]],
                popup=folium.Popup(str("{} travel from {} to  {}".format(
                    df['Philosopher'][i], df["Source"][i],
                    df["Destination"][i])),
                                   parse_html=True,
                                   max_width=450),
                tooltip="{} travel from {} to  {}".format(
                    df['Philosopher'][i], df["Source"][i],
                    df["Destination"][i]),
                color='#ced4da',
                weight=1.5,
            ).add_to(base_map)

        suffix = ".html"
        temp_file_name = next(tempfile._get_candidate_names()) + suffix
        full_filename = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '.', 'assets',
                         temp_file_name))

        #saving folium .html file
        folium.LayerControl().add_to(base_map)
        base_map.save(full_filename)
        return [
            html.Iframe(src=app.get_asset_url(f'{temp_file_name}'),
                        style={
                            "height": "100%",
                            "width": "100%"
                        })
        ]

    if tab == "map_metrics":

        if traveler == "All":
            all_travelers = sorted(list(set(map_graph.get_edges_names())))
            map_graph.edges_filter = []
            for m_filter in all_travelers:
                map_graph.set_edges_filter(m_filter)
            map_graph.create_subgraph()
        elif traveler == []:
            all_travelers = sorted(list(set(map_graph.get_edges_names())))
            map_graph.edges_filter = []
            for m_filter in all_travelers:
                map_graph.set_edges_filter(m_filter)
            map_graph.create_subgraph()
        else:
            map_graph.edges_filter = []
            for m_filter in traveler:
                map_graph.set_edges_filter(m_filter)
            map_graph.create_subgraph()

        def round_list_values(list_in):
            return [round(value, 4) for value in list_in]

        calculated_network_betweenness = list(
            pd.DataFrame.from_dict(
                nx.betweenness_centrality(
                    map_graph.networkx_subgraph).items())[1])
        calculated_network_degree = list(
            pd.DataFrame.from_dict(
                nx.degree_centrality(map_graph.networkx_subgraph).items())[1])
        calculated_network_closeness = list(
            pd.DataFrame.from_dict(
                nx.closeness_centrality(
                    map_graph.networkx_subgraph).items())[1])
        calculated_network_eigenvector = list(
            pd.DataFrame.from_dict(
                nx.eigenvector_centrality(
                    map_graph.networkx_subgraph).items())[1])

        calculated_degree = [
            round(value) for value in map_graph.calculate_degree()
        ]
        calculated_betweenness = round_list_values(
            map_graph.calculate_betweenness())
        calculated_closeness = round_list_values(
            map_graph.calculate_closeness())
        calculated_eigenvector = round_list_values(
            map_graph.calculate_eigenvector())

        dict_map_data_tables = {
            "City": map_graph.get_vertex_names(),
            "Degree": round_list_values(calculated_network_degree),
            "Betweeness": round_list_values(calculated_network_eigenvector),
            "Closeness": round_list_values(calculated_network_closeness),
            "Eigenvector": round_list_values(calculated_network_eigenvector),
        }

        df_map_data_tables = pd.DataFrame(dict_map_data_tables)

        dt_map = dash_table.DataTable(id='table-map',
                                      columns=[{
                                          "name": i,
                                          "id": i,
                                          'deletable': True
                                      } for i in df_map_data_tables.columns],
                                      style_data_conditional=[{
                                          'if': {
                                              'row_index': 'odd'
                                          },
                                          'backgroundColor':
                                          'rgb(220, 220, 220)',
                                      }],
                                      style_cell={'textAlign': 'center'},
                                      style_header={'textAlign': 'center'},
                                      page_current=0,
                                      page_size=20,
                                      page_action='custom',
                                      sort_mode='single',
                                      sort_by=[{
                                          'column_id': 'Degree',
                                          'direction': 'asc'
                                      }])

        foot_note = html.Div(children=[
            html.Span('Metrics obtained using the algorithms of '),
            html.A('Networkx',
                   href='https://networkx.org/documentation/stable/',
                   target='_blank')
        ])
        return [
            html.H6('Centrality Scores', className="mt-1 mb-2"),
            html.Hr(className='py-0'), dt_map, foot_note
        ]

    if tab == "map_graphs":

        map_graph.current_centrality_index = centrality_index

        graph_layout = "fr"
        pvis_graph = None

        if traveler == "All" or traveler == []:
            #map_graph.edges_filter = []
            pvis_graph = map_graph.get_pyvis(
                min_weight=node_size[0],
                max_weight=node_size[1],
                min_label_size=label_size[0],
                max_label_size=label_size[1],
                layout=graph_layout,
            )
        else:
            for m_filter in traveler:
                map_graph.set_edges_filter(m_filter)
            map_graph.create_subgraph()
            pvis_graph = map_graph.get_pyvis()

        if pvis_graph:
            suffix = ".html"
            temp_file_name = next(tempfile._get_candidate_names()) + suffix
            full_filename = os.path.abspath(
                os.path.join(os.path.dirname(__file__), '.', 'assets',
                             temp_file_name))

            pvis_graph.write_html(full_filename)
            return [
                html.Iframe(src=app.get_asset_url(f'{temp_file_name}'),
                            style={
                                "height": "100%",
                                "width": "100%"
                            })
            ]
Ejemplo n.º 27
0
def render_page_content(pathname):
    if pathname in ["/", "/page-1"]:
        return html.Div([
                dbc.Container([
                            html.H4("About the Data and the App", className="display-about"),
                            html.P(
                                "Getting insights from the docs",
                                className="lead",
                            ),
                            html.Hr(className="my-2"),
                            dcc.Markdown(
                                '''
                                Pellentesque posuere pellentesque imperde laoreet’s Velit leading pulvinar velit a hendrerit Donec non pellentesque jus businesses tincidunt. Suspendisse at maximus turpis, non loborsrt.

                                    Dolor sit amet consectetur elit sed do eiusmod tempor incididunt labore et dolore
                                    magna aliqua enim ad minim veniam quis nostrud exercitation ulac laboris aliquip
                                    ex ea commodo consequat duis aute irure.dolor in repre henderit in voluptate velit
                                    esse cillum dolore eu fugiat nulla pariatur excep teur sint cupidatat non proident.

                                Pellentesque posuere pellentesque imperde laoreet’s Velit leading pulvinar velit a hendrerit Donec non pellentesque jus businesses tincidunt. Suspendisse at maximus turpis, non loborsrt.

                                * consectetur elit sed do eius
                                * consectetur elit sed
                                * consectetur elit sed do
                                '''
                                ),
                        ])
        ])
    elif pathname == "/page-2":
        if 'data' in globals():
            del data
        data = load_data()
        return html.Div([
                html.H3('Text Data', style={'font-weight': 'bold'}),
                html.P('Preprocessed: stopwords removed; words in original form; without numbers; predefined phrase linked by "_"'),
                dash_table.DataTable(
                    id='table',
                    # columns=[{"name": i, "id": i} for i in textdata.columns],
                    # data=textdata.to_dict('records'),

                    columns=[{"name": i, "id": i} for i in data[['FileID','Text','text']].columns],
                    data=data[['FileID','Text','text']].to_dict('records'),

                    editable=False,
                    filter_action="native",
                    sort_action="native",
                    sort_mode="multi",
                    column_selectable=False,
                    row_selectable=False,
                    row_deletable=False,
                    selected_columns=[],
                    selected_rows=[],
                    page_action="native",
                    page_current= 0,
                    page_size= 20,
                    # style_cell_conditional=[
                    #     {'if': {'column_id': 'Member'},
                    #      'width': '100px'},
                    # ]
                    style_data={
                        'whiteSpace': 'normal',
                        'height': 'auto'
                    },
                    style_cell={
                        # 'height': 'auto',
                        'minWidth': '20px', 'maxWidth': '300px',
                        # 'whiteSpace': 'normal',
                        'textAlign': 'left',
                        'verticalAlign': 'top',
                        'fontSize':12,
                    },
                )
            ])

    elif pathname in ["/page-3"]:

        return html.Div([
                        # Chart 1
                        dbc.Row([
                            dbc.Col([
                                html.H3('Summary Statistics of Documents', style={'font-weight': 'bold'}),
                                html.P(
                                    id="description",
                                    children=dcc.Markdown(
                                      children=(
                                        '''
                                        Member submisions, and Chair and Secretariat summaries/notes.
                                        ''')
                                    )
                                ),
                                html.Br(),
                                html.H6('Number of documents by year', style={'font-weight': 'bold'}),
                            ], lg=10),
                        ]),
                        dbc.Row([
                            dbc.Col([
                                html.Label('Select Pillar:'),
                                dcc.Dropdown(
                                    id='stat-year-dropdown-pillar',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_pillar.items()],
                                    multi=False,
                                    value= 'All',
                                ),
                            ], lg=4),
                            dbc.Col([
                                html.Label('Select Proponent:'),
                                dcc.Dropdown(
                                    id='stat-year-dropdown-proponent',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_proponent.items()],
                                    multi=False,
                                    value= 'All Members & Groups',
                                ),
                            ], lg=4)
                        ]),
                        dbc.Row([
                            dbc.Col([
                                dcc.Graph(
                                    id='stat-plot-year-pillar-proponent'
                                ),
                            ], lg=10),
                        ]),

                        # Chart 2
                        dbc.Row([
                            dbc.Col([
                                html.Label('Select topic:'),
                                dcc.Dropdown(
                                    id='stat-year-dropdown-topic',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_topic.items()],
                                    multi=False,
                                    value= 'All',
                                ),
                            ], lg=4),
                            dbc.Col([
                                html.Label('Select Proponent:'),
                                dcc.Dropdown(
                                    id='stat-year-dropdown-proponent2',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_proponent.items()],
                                    multi=False,
                                    value= 'All Members & Groups',
                                ),
                            ], lg=4)
                        ]),
                        dbc.Row([
                            dbc.Col([
                                dcc.Graph(
                                    id='stat-plot-year-topic-proponent'
                                ),
                            ], lg=10),
                        ]),


                        # Chart 3
                        dbc.Row([
                            dbc.Col([
                                html.H6('Number of documents by proponent', style={'font-weight': 'bold'}),
                                html.Label('Select Year:'),
                                dcc.Dropdown(
                                    id='stat-3-dropdown-year',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_year.items()],
                                    multi=False,
                                    value= 'All',
                                ),
                            ], lg=4),
                            # dbc.Col([
                            #     html.Label('Select Proponent:'),
                            #     dcc.Dropdown(
                            #         id='stat-year-dropdown-proponent2',
                            #         options=[{'label': v, 'value': k}
                            #                     for k, v in dict_proponent.items()],
                            #         multi=False,
                            #         value= 'All Members & Groups',
                            #     ),
                            # ], lg=4)
                        ]),
                        dbc.Row([
                            dbc.Col([
                                dcc.Graph(
                                    id='stat-3-proponent'
                                ),
                            ], lg=10),
                        ]),


                        # Chart 4
                        dbc.Row([
                            dbc.Col([
                                html.Br(),
                                html.Br(),
                                html.H6('Number of documents by topic', style={'font-weight': 'bold'}),
                                html.Label('Select Year:'),
                                dcc.Dropdown(
                                    id='stat-4-dropdown-year',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_year.items()],
                                    multi=False,
                                    value= 'All',
                                ),
                            ], lg=4),
                            # dbc.Col([
                            #     html.Label('Select Proponent:'),
                            #     dcc.Dropdown(
                            #         id='stat-year-dropdown-proponent2',
                            #         options=[{'label': v, 'value': k}
                            #                     for k, v in dict_proponent.items()],
                            #         multi=False,
                            #         value= 'All Members & Groups',
                            #     ),
                            # ], lg=4)
                        ]),
                        dbc.Row([
                            dbc.Col([
                                dcc.Graph(
                                    id='stat-4-topic'
                                ),
                            ], lg=10),
                        ]),





                    ])

    elif pathname in ["/page-4"]:
        # if 'data' in globals():
        #     del data
        # data = load_data()
        return html.Div([
                        dbc.Row([
                            # dbc.Col(lg=1),
                            dbc.Col([
                                html.H3('Similarity within topics', style={'font-weight': 'bold'}),
                                # html.H5('Updata on 14 June 2020'),
                                html.P(
                                    id="description",
                                    children=dcc.Markdown(
                                      children=(
                                        '''
                                        Similarity between two docs in a topic.
                                        ''')
                                    )
                                ),
                                html.Br(),
                                # html.H6('Number of Proposals by year', style={'font-weight': 'bold'}),
                                # dcc.Dropdown(
                                #     id='my-dropdown',
                                #     options=[{'label': v, 'value': k}
                                #                 for k, v in dict_pillar.items()],
                                #     multi=False,
                                #     value= [0,1,2,3,4,5,6,7,8,9],
                                # ),
                            ], lg=10),
                        ]),
                        dbc.Row([
                            dbc.Col([
                                html.Label('Select Topic:'),
                                dcc.Dropdown(
                                    id='plot-year-dropdown-pillar1',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_topic.items()],
                                    multi=False,
                                    value= 'COT',
                                ),
                            ], lg=4),
                            # dbc.Col([
                            #     html.Label('Select Proponent:'),
                            #     dcc.Dropdown(
                            #         id='plot-year-dropdown-proponent1',
                            #         options=[{'label': v, 'value': k}
                            #                     for k, v in dict_proponent.items()],
                            #         multi=False,
                            #         value= 'All',
                            #     ),
                            # ], lg=4)
                        ]),
                        dbc.Row([
                            # dbc.Col(lg=1),
                            # dbc.Col([
                            #     dcc.Graph(
                            #         id='top_topics'
                            #     ),
                            # ], lg=3),
                            dbc.Col([
                                dcc.Graph(
                                    id='plot_year1'
                                ),
                            ], lg=10),
                        ]),
                    ])


    elif pathname in ["/page-5"]:
        # return html.H5("Content to be added page 2.")
        return html.Div([
                        dbc.Row([
                            # dbc.Col(lg=1),
                            dbc.Col([
                                html.H3('WordCloud by topic', style={'font-weight': 'bold'}),
                                # html.H5('Updata on 14 June 2020'),
                                html.P(
                                    id="description",
                                    children=dcc.Markdown(
                                      children=(
                                        '''
                                        Word frequency in a topic.
                                        ''')
                                    )
                                ),
                                html.Br(),
                            ], lg=10),
                        ]),
                        dbc.Row([
                            dbc.Col([
                                html.Label('Select Topic:'),
                                dcc.Dropdown(
                                    id='plot-year-dropdown-pillar2',
                                    options=[{'label': v, 'value': k}
                                                for k, v in dict_topic.items()],
                                    multi=False,
                                    value= 'COT',
                                ),
                            ], lg=4),
                        ]),
                        dbc.Row([
                            dbc.Col([
                                dcc.Graph(
                                    id='plot_year2'
                                ),
                            ], lg=10),
                        ]),
                    ])


    elif pathname in ["/page-6"]:
        return html.Div([
                        # html.H1('Title'),
                        html.H3('Networks: proposal proponents & document cross reference', style={'font-weight': 'bold'}),
                        html.Embed(src = "assets/network_proponent.html", width=850, height=850),
                        html.Embed(src = "assets/network_crossreference.html", width=850, height=850)
                        ])


    elif pathname in ["/page-7"]:
        return html.Div([
                        dbc.Row([
                            dbc.Col([
                                    html.H3('Term Frequency', style={'font-weight': 'bold'}),
                                    html.P(
                                        id="description",
                                        children=dcc.Markdown(
                                          children=(
                                            '''
                                            Term frequency across time
                                            ''')
                                        )
                                    ),

                            ]),

                            ]),
                        dbc.Row([
                                dbc.Col([
                                        dbc.Input(id='term-freq-input', value='tariff ams', type='text'),
                                        dbc.Button(id='term-freq-button', type='submit', children='Submit', className="mr-2"),
                                        html.P(id='term-freq-invalid'),
                                        ], lg=6),
                                ]),
                        dbc.Row([
                                dbc.Col([
                                        dcc.Graph(
                                            id='term-freq-plot'
                                            ),
                                        # dbc.Button(id='term-freq-button', type='submit', children='Submit', className="mr-2"),
                                        ], lg=10),
                                ])
                        ])
    elif pathname in ["/page-8"]:
        return html.Div([
                        dbc.Row([
                            dbc.Col([
                                    html.H3('TF-IDF keywords', style={'font-weight': 'bold'}),
                                    html.P(
                                        id="description2",
                                        children=dcc.Markdown(
                                          children=(
                                            '''
                                            Keywords based on TF-IDF. Select documents
                                            ''')
                                        )
                                    ),
                            ]),

                            ]),
                        dbc.Row([
                                dbc.Col([
                                        html.P(id='tfidf-invalid'),
                                        dcc.Dropdown(id='tfidf-dropdown',
                                                     multi=True,
                                                     value=['AIE-1', 'AIE-2','AIE-3','AIE-4','AIE-5'],
                                                     placeholder='Select members',
                                                     options=[{'label': country, 'value': country}
                                                              for country in allfileid]),
                                        ],lg=10),
                                ]),
                        dbc.Row([
                                dbc.Col([
                                        dcc.Graph(
                                            id='tfidf-plot'
                                            ),
                                        ], lg=10),
                                ])
                        ])


    # If the user tries to reach a different page, return a 404 message
    return dbc.Container(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ]
    )
Ejemplo n.º 28
0
                    dbc.NavLink("Data", href="/page-2", id="page-2-link"),
                    dbc.NavLink("Similarity", href="/page-4", id="page-4-link"),
                    dbc.NavLink("WordCloud", href="/page-5", id="page-5-link"),
                    dbc.NavLink("Networks", href="/page-6", id="page-6-link"),
                    dbc.NavLink("Term Freq", href="/page-7", id="page-7-link"),
                    dbc.NavLink("Key TF-IDF", href="/page-8", id="page-8-link"),
                    dbc.NavLink("About", href="/page-1", id="page-1-link"),
                ],
                vertical=True,
                pills=False,
            ),
            id="collapse",
            # id="sidebar",
        ),

        html.Div([  html.Hr(),
                    html.P(
                        "Version 20211208",
                        # className="lead",
                    ),
                ],
            id="blurb-bottom",
            ),
    ],
    id="sidebar",
)

content = html.Div(id="page-content")
app.layout = html.Div([dcc.Location(id="url"), sidebar, content])

# this callback uses the current pathname to set the active state of the
Ejemplo n.º 29
0
import time

app = dash.Dash(__name__, plugins=[dl.plugins.pages])

navbar = html.Div(
    [
        html.Div(dcc.Link(page["name"], href=page["path"]))
        for page in dash.page_registry.values()
    ],
    style={
        "backgroundColor": "whitesmoke",
        "padding": 10
    },
)

app.layout = html.Div([navbar, html.Hr(), dl.plugins.page_container], )


@app.long_callback(
    output=Output("paragraph_id", "children"),
    inputs=Input("button_id", "n_clicks"),
    manager=long_callback_manager,
    prevent_initial_call=True,
)
def callback(n_clicks):
    time.sleep(2.0)
    return [f"Clicked {n_clicks} times"]


if __name__ == "__main__":
    app.run_server(debug=True)
Ejemplo n.º 30
0
def test_cbmo003_multi_all(dash_duo):
    app = dash.Dash(__name__)

    app.layout = html.Div(children=[
        html.Button("items", id="items"),
        html.Button("values", id="values"),
        html.Div(id="content1"),
        html.Hr(),
        html.Div(id="content2"),
        html.Hr(),
        html.Div("Output init", id="output"),
    ])

    @app.callback(
        [Output("content1", "children"),
         Output("content2", "children")],
        [Input("items", "n_clicks")],
    )
    def content(n1):
        c1 = [html.Div(id={"i": i}) for i in range(((n1 or 0) + 2) % 4)]
        c2 = [html.Div(id={"j": j}) for j in range((n1 or 0) % 3)]
        return c1, c2

    @app.callback(
        [Output({"i": ALL}, "children"),
         Output({"j": ALL}, "children")],
        [Input("values", "n_clicks")],
    )
    def content_inner(n2):
        # this variant does NOT get called with empty ALL
        # the second callback handles outputting 0 in that case.
        # if it were to be called throw an error so we'll see it in get_logs
        n1i = len(dash.callback_context.outputs_list[0])
        n1j = len(dash.callback_context.outputs_list[1])
        if not n1i + n1j:
            raise ValueError("should not be called with no outputs!")
        return [n2 or 0] * n1i, [(n2 or 0) + 2] * n1j

    @app.callback(
        Output("output", "children"),
        [Input({"i": ALL}, "children"),
         Input({"j": ALL}, "children")],
    )
    def out2(ci, cj):
        return sum(ci) + sum(cj)

    dash_duo.start_server(app)

    dash_duo.wait_for_text_to_equal("#content1", "0\n0")
    dash_duo.wait_for_text_to_equal("#content2", "")
    dash_duo.wait_for_text_to_equal("#output", "0")

    actions = [
        ["#values", "1\n1", "", "2"],
        ["#items", "1\n1\n1", "3", "6"],
        ["#values", "2\n2\n2", "4", "10"],
        ["#items", "", "4\n4", "8"],
        ["#values", "", "5\n5", "10"],
        ["#items", "3", "", "3"],
        ["#values", "4", "", "4"],
        ["#items", "4\n4", "6", "14"],
        ["#values", "5\n5", "7", "17"],
        ["#items", "5\n5\n5", "7\n7", "29"],
        ["#values", "6\n6\n6", "8\n8", "34"],
        # all empty! we'll see an error logged if the callback was fired
        ["#items", "", "", "0"],
        ["#values", "", "", "0"],
        ["#items", "7", "9", "16"],
    ]
    for selector, content1, content2, output in actions:
        dash_duo.find_element(selector).click()
        dash_duo.wait_for_text_to_equal("#content1", content1)
        dash_duo.wait_for_text_to_equal("#content2", content2)
        dash_duo.wait_for_text_to_equal("#output", output)

    assert not dash_duo.get_logs()