Ejemplo n.º 1
0
def poledir(d, i, r):
    if d and i and r:
        x, y, z = dir_to_xyz(d, i, r)
        x, y, z = round(x, 1), round(y, 1), round(z, 1)
        return (dbc.ListGroup([
            dbc.Row([
                dbc.Col([
                    dbc.ListGroupItemText("X",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(x),
                ],
                        width=4),
                dbc.Col([
                    dbc.ListGroupItemText("Y",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(y),
                ],
                        width=4),
                dbc.Col([
                    dbc.ListGroupItemText("Z",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(z),
                ],
                        width=4),
            ])
        ]))
Ejemplo n.º 2
0
def poledir(x, y, z):
    if x and y and z:
        dec, inc, mag = xyz_to_dir(x, y, z, "MAG")
        return (dbc.ListGroup([
            dbc.Row([
                dbc.Col([
                    dbc.ListGroupItemText("Declination",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(dec),
                ],
                        width=4),
                dbc.Col([
                    dbc.ListGroupItemText("Inclination",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(inc),
                ],
                        width=4),
                dbc.Col([
                    dbc.ListGroupItemText("Magnitude",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(mag),
                ],
                        width=4),
            ])
        ]))
Ejemplo n.º 3
0
def display_source_providers(*providers: SourceProvider):
    return dbc.Card([
        dbc.CardBody([
            html.H4([html.I(className="fas fa-link"), " ",
                     gettext("Sources")],
                    className="card-title"),
            html.H6(gettext(
                "The following data sources were used to produce this page:"),
                    className="card-subtitle")
        ]),
        dbc.ListGroup(
            [
                dbc.ListGroupItem(str(p.name) +
                                  ("" if not p.desc else f" ({p.desc})"),
                                  href=p.link,
                                  action=True) for p in providers
            ] + [
                dbc.ListGroupItem(gettext(
                    "The processed data, along with the software used to process it, is available on GitHub."
                ),
                                  href=
                                  "https://github.com/pschaus/covidbe-opendata",
                                  action=True,
                                  color="primary")
            ],
            flush=True,
        )
    ],
                    className="my-3")
Ejemplo n.º 4
0
def get_port_view(name, port):
    return [
        dbc.Row(html.H3(name), align='center', justify='center'),
        dbc.Row(dbc.ListGroup([
            dbc.ListGroupItem([
                dbc.ListGroupItemHeading(f'{port["Returns"]:.2%}'),
                dbc.ListGroupItemText('RETURNS')
            ]),
            dbc.ListGroupItem([
                dbc.ListGroupItemHeading(f'{port["Volatility"]:.4f}'),
                dbc.ListGroupItemText("VOLATILITY")
            ]),
            dbc.ListGroupItem([
                dbc.ListGroupItemHeading(f'{port["Sharpe Ratio"]:.4f}'),
                dbc.ListGroupItemText("SHARPE RATIO")
            ]),
        ],
                              horizontal=True),
                align='center',
                justify='center'),
        dbc.Row(dbc.ListGroup([
            dbc.ListGroupItem([
                dbc.ListGroupItemHeading(f'{weight:.2%}'),
                dbc.ListGroupItemText(symbol)
            ]) for symbol, weight in port['Expected Weights'].items()
        ],
                              horizontal=True),
                align='center',
                justify='center'),
        html.Hr()
    ]
Ejemplo n.º 5
0
def init_dashboard(server):
    """Create a Plotly Dash dashboard."""
    dash_app = dash.Dash(
        server=server,
        routes_pathname_prefix="/dashapp/",
        external_stylesheets=[dbc.themes.MATERIA],
    )
    dash_app.layout = dbc.Container(
        dbc.Row(
            dbc.Col(
                [
                    html.
                    H4("Change the value in the text box to see callbacks in action!"
                       ),
                    html.Div([
                        dbc.Input(
                            id="my-input",
                            value="initial value",
                            type="text",
                            autoFocus=True,
                        ),
                    ]),
                    html.Br(),
                    dbc.Card(id="my-output", body=True),
                    dbc.ListGroup(
                        [
                            dbc.ListGroupItem(
                                dbc.NavLink(
                                    "Home", href="/", external_link=True)),
                            dbc.ListGroupItem(
                                dbc.NavLink("About",
                                            href="/about",
                                            external_link=True)),
                            dbc.ListGroupItem(
                                dbc.NavLink("Internal Link — Dash App 2",
                                            href="/dashapp2")),
                            dbc.ListGroupItem(
                                dbc.NavLink(
                                    "External Link — Dash App 2",
                                    href="/dashapp2",
                                    external_link=True,
                                )),
                        ],
                        className="mt-4",
                    ),
                ],
                className="mt-5",
            )))

    @dash_app.callback(
        Output(component_id="my-output", component_property="children"),
        Input(component_id="my-input", component_property="value"),
    )
    def update_output_div(input_value):
        return f"Output: {input_value}"

    return dash_app.server
Ejemplo n.º 6
0
def daily_stats_mobile(state="US") -> List[dbc.Row]:
    """Returns a top bar as a list of Plotly dash components displaying tested, confirmed , and death cases for the top row.
    TODO: move to internal API.

    :param none: none
    :return cols: A list of plotly dash boostrap components Card objects displaying tested, confirmed, deaths.
    :rtype: list of plotly dash bootstrap coomponent Col objects.
    """
    # 1. Fetch Stats
    # print(f"daily_stats_mobile for state {STATES_COORD[state]['stateAbbr']}")
    stats = get_daily_stats_mobile(STATES_COORD[state]['stateAbbr'])

    # print("Mobile Site ---> ", stats)
    # 2. Dynamically generate list of dbc Cols. Each Col contains a single Card. Each card displays
    # items and values of the stats pulled from the API.
    cards = []
    for key, value in stats.items():
        if key == "Tested":
            card = dbc.ListGroupItem(
                [
                    html.P(" .", className=f"mobile-top-bar-perc-change-{key.lower()}"),
                    html.H1(value, className=f"mobile-top-bar-value-{key.lower()}"),
                    html.P(f"{key}", className="mobile-card-text"),
                ],
                className=f"mobile-top-bar-card-{key.lower()}",
            )
        elif key == "Death Rate":
            card = dbc.ListGroupItem(
                [
                    html.P(
                        f" {float(value[1]):+0.2f}% change",
                        className=f"mobile-top-bar-perc-change-{key.lower()}",
                    ),
                    html.H1(f"{value[0]}%", className=f"mobile-top-bar-value-{key.lower()}"),
                    html.P(f"{key}", className="mobile-card-text"),
                ],
                className=f"mobile-top-bar-card-{key.lower()}",
            )
        else:
            card = dbc.ListGroupItem(
                [
                    html.P(
                        f"+ {value[1]} new",
                        className=f"mobile-top-bar-perc-change-{key.lower()}",
                    ),
                    html.H1(value[0], className=f"mobile-top-bar-value-{key.lower()}"),
                    html.P(f"{key}", className="mobile-card-text"),
                ],
                className=f"mobile-top-bar-card-{key.lower()}",
            )
            
        cards.append(card)

    cards = dbc.ListGroup(cards)
    return cards
Ejemplo n.º 7
0
def state_info(state, data):
    if not state:
        return dbc.Col("")

    state_info, state_current = data.get_state_data(state)
    state_grade = data.get_state_grade(state)
    last_update = data.state_last_update(state)

    return [
        dbc.Col([graph_tabs(id="state-graph")]),
        dbc.Col(
            dbc.Card([
                dbc.CardHeader(
                    dbc.Row([
                        dbc.Col(html.H3(state_info['name'])),
                        dbc.Col(grade_card(state_grade), align='center')
                    ],
                            justify='between')),
                dbc.CardBody([
                    dbc.Row(
                        dbc.Col([
                            html.H5("Current Totals"),
                            html.Small(f"Last updated - {last_update}"),
                            build_table(state_current, id='state-data')
                        ])),
                    dbc.Row([
                        dbc.Col([
                            html.H5("State Links"),
                            dbc.ListGroup([
                                dbc.ListGroupItem(
                                    "Covid Site",
                                    href=state_info['covid19Site'],
                                    target="_blank"),
                                dbc.ListGroupItem(
                                    "Secondary Covid Site",
                                    href=state_info['covid19SiteSecondary'],
                                    target="_blank"),
                                dbc.ListGroupItem(
                                    "Twitter",
                                    href=
                                    f"https://twitter.com/{state_info['twitter']}",
                                    target="_blank")
                            ])
                        ],
                                width=4),
                        dbc.Col([
                            html.H5("Data notes"),
                            dcc.Markdown(state_info.get('notes', ""))
                        ])
                    ])
                ])
            ]))
    ]
Ejemplo n.º 8
0
    def make_activity_info_header(activity: Activity):
        metrics = ActivityMetrics(activity=activity, config={'ftp': 290})
        if activity.type == 'Run' or 'Walk':
            return html.Div([])

        line1 = dbc.ListGroup(
            [
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading(activity.name,
                                             style={'font-size': '0.7rem'}),
                    dbc.ListGroupItemText(activity.date),
                    dbc.ListGroupItemText(""),
                ],
                                  style={
                                      'font-size': '0.6rem',
                                      'line-height': '0.1em'
                                  }),
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading("Power",
                                             style={'font-size': '0.7rem'}),
                    dbc.ListGroupItemText(f"{metrics.average_power}"),
                    dbc.ListGroupItemText(f"{metrics.normalized}"),
                    dbc.ListGroupItemText(f"{metrics.work}"),
                ],
                                  style={
                                      'font-size': '0.6rem',
                                      'line-height': '0.1em'
                                  }),
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading("HR",
                                             style={'font-size': '0.7rem'}),
                    dbc.ListGroupItemText(f"{metrics.average_hr}"),
                    dbc.ListGroupItemText(f"{metrics.max_hr}"),
                ],
                                  style={
                                      'font-size': '0.6rem',
                                      'line-height': '0.1em'
                                  }),
            ],
            horizontal=True,
            className="mb-1",
            style={'font-size': '0.8rem'},
        )

        line2 = dbc.ListGroup([])

        list_group = html.Div([
            line1,
            line2,
        ])
        return list_group
Ejemplo n.º 9
0
def display_click_data(clickData):
    #print(1)
    url_text = ""
    url_link = ""
    jobs_text = ""
    jobs_link = ""
    contact_text = ""
    contact_link = ""
    if not clickData:
        return ""
    item_id = clickData["points"][0]["id"]
    item_name = clickData["points"][0]["label"]
    item_desc = clickData["points"][0]["customdata"]
    listGroup = ""

    #print(companies_dict[item_name])
    if len(companies_dict[item_name]) > 2:
        url_text = companies_dict[item_name]
        url_link = companies_dict[item_name]
        jobs_text = "Jobs at " + item_name
        jobs_link = "https://jobs.urban.us/?q=" + item_name
        contact_text = "Get in touch with us about " + item_name
        contact_link = "https://share.hsforms.com/1SNKBwhDaTjGHU5BAO2cFZQ10due?what_would_you_like_to_discuss_=" "" + item_name
        listGroup = dbc.ListGroup([
            dbc.ListGroupItem(html.A(url_text, target='_blank',
                                     href=url_link)),
            dbc.ListGroupItem(
                html.A(jobs_text, target='_blank', href=jobs_link)),
            dbc.ListGroupItem(
                html.A(contact_text, target='_blank', href=contact_link)),
        ])

    return_card = dbc.Card(
        [
            dbc.CardBody([
                html.H4(item_name, className="card-title"),
                html.P(
                    item_desc,
                    className="card-text",
                ),
                html.Br(),
                listGroup,
            ]),
        ],
        body=True,
    )

    #print(item_name)
    #print(clickData)

    return return_card
Ejemplo n.º 10
0
def tab_right_countries(dropdown):
    if len(dropdown) == 0:
        for country in top_4:
            dropdown.append(country)

    return html.Div([
        html.Ul([
            html.Li([
                html.Div([
                        dbc.ListGroupItem([
                            dbc.ListGroupItemHeading(f'{country}:'),
                            html.Hr(),
                            dbc.ListGroupItemText(f'Confirmed cases: {df_tab_right.iloc[0][country]:,}'),
                            dbc.ListGroupItemText(f'Deaths: {df_tab_right.iloc[1][country]:,}'),
                            list_item('Mortality rate: ', float('%.2f'%(df_tab_right.iloc[2][country]*100)), '%'),
                            dbc.ListGroupItemText(f'Infection rate: {df_tab_right.iloc[3][country]*100:.2f}%'),
                            dbc.ListGroupItemText(f'Share out of global confirmed cases: {df_tab_right.iloc[4][country]*100:.4f}%'),
                            list_item('Share out of global deaths: ', float('%.4f'%(df_tab_right.iloc[5][country]*100)), '%'),
                            dbc.ListGroupItemText(f'Date of 1st confirmed case: {df_tab_right.iloc[6][country]}'),
                            list_item('Date of 1st confirmed death: ', df_tab_right.iloc[7][country], ''),
                            list_item('Policy Index: ', df_tab_right.iloc[8][country], ''),
                            dbc.ListGroupItemText(f'Population in 2019: {df_tab_right.iloc[9][country]:,}'),
                            ], className="items") for country in dropdown
                ],
                className='media-body border-0'
                ),
            ],
            className='media border-0'
            ),   
        ],
        className='list-unstyled'
        ),
    ],
    className="tabr overflow-auto"
    )
Ejemplo n.º 11
0
    def display_selected_data(selectedData):
        if selectedData is None:
            return []

        result = []
        for point in selectedData['points']:
            idx = point['customdata'][0]
            df_item = df_t.loc[idx]

            result.append(
                dbc.ListGroupItem([
                    html.H5(df_item.route),
                    html.Ul([
                        html.Li([
                            html.Label('Start:'),
                            ' {} s'.format(df_item.start.total_seconds())
                        ]),
                        html.Li([
                            html.Label('Duration:'),
                            ' {} s'.format(df_item.duration.total_seconds())
                        ])
                    ]),
                    html.H6('Data'),
                    html.Pre(json.dumps(json.loads(df_item.data), indent=2))
                ]))
        return result
Ejemplo n.º 12
0
def make_link_with_modal(title, content):
    """
     This makes a link that opens a modal for content
     note: The modal callback is located in the app_galery.py
     content example:
        To display text, use dcc.Markdown("my text")
        To display a codebox:
          html.Div(html.Pre(html.Code(" enter code here" )), style=codebox,)

    """
    return dbc.ListGroupItem([
        dbc.Button(
            title,
            id={
                "type": "modal_btn",
                "index": title
            },
            color="link",
            className="text-left pl-0",
        ),
        dbc.Modal(
            dbc.ModalBody(content),
            id={
                "type": "modal",
                "index": title
            },
            scrollable=True,
            size="lg",
        ),
    ])
Ejemplo n.º 13
0
def states_recovered_stats(state=None) -> dbc.ListGroup:
    """    
    :params state: display news feed for a particular state. If None, display news feed for the whole US

    :return list_group: A bootstramp ListGroup containing ListGroupItem returns news feeds.
    :rtype: dbc.ListGroup    
    """
    list_group = dbc.ListGroup(
        [
            dbc.ListGroupItem(
                [
                    html.P(
                        [
                            html.Span(
                                f"{row['recovered']}",
                                className="states-stats-recovered-list-num",
                            ),
                            html.Span(
                                f"   {row['state']}",
                                className="states-stats-recovered-list-state",
                            ),
                        ],
                        className="states-stats-recovered-list-txt",
                    ),
                ],
                className="states-stats-recovered-list-item",
            ) for row in data
        ],
        flush=True,
        className="states-stats-recovered-listgroup",
    )

    return list_group
Ejemplo n.º 14
0
def news_feed(state="US") -> dbc.ListGroup:
    """Displays news feed on the right hand side of the display. Adjust the
    NewsAPI time time to Eastern Time (w/ DST).

    :params state: display news feed for a particular state. If None, display
    news feed for the whole US

    :return list_group: A bootstramp ListGroup containing ListGroupItem returns
    news feeds.
    :rtype: dbc.ListGroup
    """
    URL = config.NCOV19_API + config.NEWS
    if state == "US":
        response = requests.get(URL)
    else:
        payload = {"state": state, "topic": "coronavirus"}
        payload = json.dumps(payload)
        response = requests.post(config.NCOV19_API + config.NEWS, data=payload)

    if response.status_code == 200:
        json_data = response.json()
        json_data = json_data["message"]
        df = pd.DataFrame.from_records(json_data)
        df = pd.DataFrame(df[["title", "url", "published"]])

        max_rows = 50
        list_group = dbc.ListGroup(
            [
                dbc.ListGroupItem(
                    [
                        html.Div(
                            [
                                html.H6(
                                    f"{df.iloc[i]['title'].split(' - ')[0]}.",
                                    className="news-txt-headline",
                                ),
                                html.P(
                                    f"{df.iloc[i]['title'].split(' - ')[1]}"
                                    f"  {df.iloc[i]['published']}",
                                    className="news-txt-by-dt",
                                ),
                            ],
                            className="news-item-container",
                        )
                    ],
                    className="news-item",
                    href=df.iloc[i]["url"],
                    target="_blank",
                ) for i in range(min(len(df), max_rows))
            ],
            flush=True,
        )

        del response, json_data, df
        gc.collect()

    else:
        list_group = []

    return list_group
Ejemplo n.º 15
0
def StatusItem(idx, name, status_badge):
    style = {
        'border-bottom': '1px solid',
        'border-left': '1px solid',
        'border-right': '1px solid'
    }
    if idx == 1:
        style['border-top'] = '1px solid'

    return dbc.ListGroupItem([
        dbc.Row([
            dbc.Col(html.H5(name,
                            style={
                                'vertical-align': 'middle',
                                'margin-top': 8
                            }),
                    style={
                        'align-items': 'center',
                        'justify-content': 'left',
                        'display': 'flex'
                    },
                    width=9),
            dbc.Col(status_badge,
                    style={
                        'align-items': 'center',
                        'justify-content': 'right',
                        'display': 'flex'
                    })
        ],
                justify='around',
                align='around')
    ],
                             style=style)
Ejemplo n.º 16
0
def states_deaths_stats() -> dbc.ListGroup:
    """    
    :params state: display news feed for a particular state. If None, display news feed
        for the whole US

    :return list_group: A bootstramp ListGroup containing ListGroupItem returns news feeds.
    :rtype: dbc.ListGroup    
    """
    list_group = dbc.ListGroup(
        [
            dbc.ListGroupItem(
                [
                    html.P(
                        [
                            html.Span(
                                f"{value}", className="states-stats-deaths-list-num",
                            ),
                            html.Span(
                                f"   {key}", className="states-stats-deaths-list-state",
                            ),
                        ],
                        className="states-stats-deaths-list-txt",
                    ),
                ],
                id=f"states-death-{key}",
                className="states-stats-deaths-list-item",
            )
            for key, value in death.items()
        ],
        flush=True,
        className="states-stats-death-listgroup",
    )

    return list_group
def on_links_data(
    links_timestamp,
    links_debug_timestamp,
    links,
    links_with_score,
    dataset_name,
    cmap_type,
):
    """When the local storage "links-memory" changes,
    Update the list view "list-links-view", that is a list of all selected links.
    For debug, the `links_with_score` will store additional values `q_ij` and `log q_ij`
    `links-memory-debug` local storage will be updated when we find the best perp.
    """
    if links_timestamp is None:
        raise PreventUpdate

    merged_links = _merge_links(links, (links_with_score or []))
    list_links_view = [
        dbc.ListGroupItem(
            id=str(link),
            children=_create_link_item(idx + 1, link, dataset_name, cmap_type),
            n_clicks_timestamp=0,
            action=True,
        )
        for idx, link in reversed(list(enumerate(merged_links)))
    ]

    txt_debug = json.dumps(merged_links, indent=2)
    return txt_debug, list_links_view
Ejemplo n.º 18
0
    def show_news_list(self, zipcode="21029", radius=70):
        colors = ['primary', 'secondary', 'success', 'warning', 'danger', 'info']
        color_cycle = cycle(colors)
        try:
            news_list = self.get_local_news_by_zipcode(zipcode, radius)
        except BaseException as ex:
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            news_list = []

        try:
            # return html.Ol([
            #     html.Li([
            #         html.A(x['title'], href=x['url'], target='_blank'),
            #         html.Div(x['publishedAt'], style={'size': 1, 'color': "blue"})
            #     ])
            #     for x in news_list])
            return dbc.ListGroup(
                [
                    dbc.ListGroupItem(
                        [
                            dbc.ListGroupItemHeading(html.H5(x['title'])),
                            dbc.ListGroupItemText(html.H6(x['publishedAt'])),
                        ],
                        href=x['url'], target='_blank', color=next(color_cycle)
                    ) for x in news_list
                ]
            )

        except BaseException:
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            return html.Ol("API call limit")
Ejemplo n.º 19
0
def _make_nav_item(sector_name,
                   emissions,
                   indent,
                   page,
                   bold=False,
                   active=False):
    attrs = {}
    if page is None:
        attrs['disabled'] = True
    else:
        attrs['disabled'] = False
        attrs['href'] = page.path
    style = {}
    if indent:
        style = {'marginLeft': '%drem' % 2 * indent}
    if bold:
        style = {'fontWeight': 'bold'}

    if active:
        attrs['active'] = True

    item = dbc.ListGroupItem([
        html.Span(sector_name, style=style),
        dbc.Badge(
            "%.0f kt" % emissions, color="light", className="ml-1 float-right")
    ],
                             action=True,
                             **attrs)
    return item
Ejemplo n.º 20
0
def daily_stats_mobile() -> List[dbc.Row]:
    """Returns a top bar as a list of Plotly dash components displaying tested, confirmed , and death cases for the top row.
    TODO: move to internal API.

    :param none: none
    :return cols: A list of plotly dash boostrap components Card objects displaying tested, confirmed, deaths.
    :rtype: list of plotly dash bootstrap coomponent Col objects.
    """
    # 1. Fetch Stats
    stats = get_daily_stats()
    # print("Mobile Site ---> ", stats)
    # 2. Dynamically generate list of dbc Cols. Each Col contains a single Card. Each card displays
    # items and values of the stats pulled from the API.
    cards = []
    for key, value in stats.items():
        if key not in ["Tested", "Recovered"]:
            card = dbc.ListGroupItem(
                [
                    html.P(
                        f"+ {value[1]} in past 24h",
                        className=f"mobile-top-bar-perc-change-{key.lower()}",
                    ),
                    html.H1(value[0],
                            className=f"mobile-top-bar-value-{key.lower()}"),
                    html.P(f"{key}", className="mobile-card-text"),
                ],
                className=f"mobile-top-bar-card-{key.lower()}",
            )

        else:
            # card = dbc.Row(
            card = dbc.ListGroupItem(
                [
                    html.P(
                        " .",
                        className=f"mobile-top-bar-perc-change-{key.lower()}"),
                    html.H1(value,
                            className=f"mobile-top-bar-value-{key.lower()}"),
                    html.P(f"{key}", className="mobile-card-text"),
                ],
                className=f"mobile-top-bar-card-{key.lower()}",
            )

        cards.append(card)

    cards = dbc.ListGroup(cards)
    return cards
Ejemplo n.º 21
0
 def dataset_list(self, *datasets):
     return [
         dbc.ListGroupItem([
             dbc.Checkbox(id=f"dataset-checkbox-{i}",
                          style={'float': 'right'},
                          checked=True), *self.dataset_itemlist(ds)
         ]) for i, ds in enumerate(datasets)
     ]
Ejemplo n.º 22
0
def filelist_modal_list(
    database_name: str, collection_name: str
) -> Union[List[dbc.ListGroupItem], str]:
    """Return list of files for the filelist modal."""
    filelist = db.get_filelist(collection_name, database_name)
    if filelist:
        return [dbc.ListGroupItem(x) for x in filelist]
    return "None"
 def render(id, name):
     element = dbc.ListGroupItem(
         [
             name,
             ScoreInput.render(id),
         ],
         className="d-flex justify-content-between align-items-center")
     return element
Ejemplo n.º 24
0
def make_list_item(song,unique_id):
    name = song.name
    artist = song.artist
    external_url = song.url
    uri = song.uri
    heading = dbc.ListGroupItemText("{} - {}".format(name, artist))

    return dbc.ListGroupItem(heading,id=unique_id, key=str(uri))
Ejemplo n.º 25
0
def kanban_list(
    _value, _status
):  # _value is(urgent,imp,normal) and _status is (to do,progress,done)
    return dbc.ListGroup([
        dbc.ListGroupItem(children=[
            task_card(i, _value, _status) for i in range(len(df['to_do_task']))
        ])
    ])
Ejemplo n.º 26
0
def load_vehicles_list(n, **kwargs):
    return dbc.ListGroup([
        dbc.ListGroupItem(
            id=f'{spec.id}',
            children=[spec.plate_number],
            n_clicks=0,
        ) for spec in Specification.objects.all()
    ])
Ejemplo n.º 27
0
def states_deaths_stats(state="US") -> dbc.ListGroup:
    """    
    :params state: display news feed for a particular state. If None, display news feed
        for the whole US

    :return list_group: A bootstramp ListGroup containing ListGroupItem returns news feeds.
    :rtype: dbc.ListGroup    
    """

    try:
        URL = config.NCOV19_API + config.COUNTY
        response = requests.get(URL).json()
        data = response["message"]

        data = pd.DataFrame.from_records(data)
        data["state_name"] = data["state_name"].str.title()

        if state == "US":
            deaths = data.groupby(["state_name"])["deaths"].sum()
            deaths = confirmed.sort_values(ascending=False).to_dict()
        else:
            deaths = data[data["state_name"] == state]
            confirmed = df[["County Name", "Confirmed"]]
            confirmed = dict(
                confirmed.sort_values(by="Confirmed",
                                      ascending=False).to_records(index=False))

        del response, data
    except:
        print("[ERROR] states_confirmed_stats error accessing ncov19.us API")

    list_group = dbc.ListGroup(
        [
            dbc.ListGroupItem(
                [
                    html.P(
                        [
                            html.Span(
                                f"{value:,d}",
                                className="states-stats-deaths-list-num",
                            ),
                            html.Span(
                                f"   {key}",
                                className="states-stats-deaths-list-state",
                            ),
                        ],
                        className="states-stats-deaths-list-txt",
                    ),
                ],
                id=f"states-death-{key}",
                className="states-stats-deaths-list-item",
            ) for key, value in death.items()
        ],
        flush=True,
        className="states-stats-death-listgroup",
    )

    return list_group
Ejemplo n.º 28
0
def twitter_feed(state=None) -> List[dbc.Card]:
    """Displays twitter feed on the left hand side of the display.

    TODO: 
    TODO: Add callbacks based on state

    :params state: display twitter feed for a particular state. If None, display twitter feed
        for the whole US.

    :return cards: A list of dash boostrap Card components, where each cahrd contains tweets for twitter feed.
    :rtype: list
    """
    if state is None:
        doc = tm.get_tweet_by_state("US")

    cards = [
        # dbc.Card(
        #     dbc.CardHeader([html.I(className="fab fa-twitter mr-1"), "Twitter Feed"])
        # )
    ]

    username = doc["username"]
    full_name = doc["full_name"]
    tweets = doc["tweets"]

    # 2020-03-19 triage. lots of empty list at the end of tweets, filtering them out
    tweets = [*filter(None, tweets)]
    tweets = sorted(tweets, key=lambda i: i["created_at"], reverse=True)
    # print(tweets)
    cards += [
        # dbc.Card(
        #     dbc.CardBody(
        dbc.ListGroupItem(
            [
                html.A(
                    html.P(tweet["full_text"][:100] + "...", ),
                    href=
                    f"https://twitter.com/{username}/status/{tweet['tweet_id']}",
                    target="_blank",
                ),
                html.P(
                    [
                        html.Strong(f"- {full_name} (@{username})"),
                        html.P(
                            f"{tweet['created_at'].strftime('%a %d, %Y at %I: %M %p')}",
                            className="tweet-dt",
                        ),
                    ],
                    className="tweets-txt-by-dt",
                ),
            ],
            className="tweet-item",
            # ),
        ) for tweet in tweets
    ]
    list_group = dbc.ListGroup(cards, flush=True)
    # return cards
    return list_group
Ejemplo n.º 29
0
def twitter_feed(state=None) -> List[dbc.Card]:
    """Displays twitter feed on the left hand side of the display.
    
    TODO: Add callbacks based on state

    :params state: display twitter feed for a particular state. If None, display twitter feed
        for the whole US.

    :return cards: A list of dash boostrap Card components, where each card contains tweets for twitter feed.
    :rtype: list
    """

    response = requests.get(NCOV19_API + "twitter").json()
    if response["success"] == True:
        data = response["message"]
        username = data["username"]
        full_name = data["full_name"]
        tweets = data["tweets"]
    else:
        username = "******"
        full_name = "John Cena"
        tweets = [{
            "tweet_id": "0",
            "full_text": "John Cena to Corona Virus : You Can't See Me !",
            "created_at": "2020-03-25T22:05:24",
        }]

    # 2020-03-19 triage. lots of empty list at the end of tweets, filtering them out
    # tweet["full_text"][:100]
    cards = [
        dbc.ListGroupItem(
            [
                html.A(
                    html.P(
                        tweet["full_text"][:100] + "...",
                        className="tweet-text",
                    ),
                    href=
                    f"https://twitter.com/{username}/status/{tweet['tweet_id']}",
                    target="_blank",
                ),
                html.P(
                    [
                        # html.Strong(f"- {full_name} (@{username})"),
                        html.P(
                            f"- @{username} {parse(tweet['created_at']).strftime('%a %d, %Y at %I: %M %p')}",
                            className="tweet-dt",
                        ),
                    ],
                    className="tweets-txt-by-dt",
                ),
            ],
            className="tweet-item",
        ) for tweet in tweets
    ]
    list_group = dbc.ListGroup(cards, flush=True)

    return list_group
Ejemplo n.º 30
0
def poledir(lat, lon, dec, inc, a95):
    if lat and lon and dec and inc and a95:
        PLat, PLon, dp, dm, PaleoLat = paleo_pole(lat, lon, dec, inc, a95)
        return (dbc.ListGroup([
            dbc.Row([
                dbc.Col([
                    dbc.ListGroupItemText("PLat",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(PLat),
                ],
                        width=3),
                dbc.Col([
                    dbc.ListGroupItemText("PLon",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(PLon),
                ],
                        width=3),
                dbc.Col([
                    dbc.ListGroupItemText("dp/dm",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(str(dp) + "/" + str(dm)),
                ],
                        width=3),
                dbc.Col([
                    dbc.ListGroupItemText("PaleoLat",
                                          style={
                                              "margin-bottom": "-2px",
                                          }),
                    dbc.ListGroupItem(PaleoLat),
                ],
                        width=3)
            ])
        ])
                # html.P(
                #     "PLat: " + str(PLat) + " PLon: " + str(PLon) +
                #     " dp/dm: " + str(dp)+"/"+str(dm) + " PaleoLat: " + str(PaleoLat),
                #     className="text-center"
                # ),
                )