예제 #1
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']))
        ])
    ])
예제 #2
0
 def uploaded_dataset_list(self, *datasets):
     #
     # TODO: active can be set to True for highligthing selected File (however for the moment we limit to one
     #  component)
     # TODO: write  a callback for each entry
     #
     all_datasets = [dbc.ListGroup(self.dataset_list(*datasets))]
     return all_datasets
예제 #3
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
예제 #4
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
예제 #5
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]}  {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
예제 #6
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
예제 #7
0
def news_feed(state=None) -> dbc.ListGroup:
    """Displays news feed on the right hand side of the display. Adjust the NewsAPI time
    time to Eastern Time (w/ DST).
    
    TODO: Add callbacks to fetch local state news, if none get entire US news
    
    :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    
    """

    news_requests = requests.get(NEWS_API_URL)
    json_data = news_requests.json()["articles"]
    df = pd.DataFrame(json_data)
    df = pd.DataFrame(df[["title", "url", "publishedAt"]])
    # Infer datetime
    df["publishedAt"] = pd.to_datetime(df["publishedAt"],
                                       infer_datetime_format=True)
    # Assuming timedelta of 5 hours based on what i compared from CNN articles from API.
    df["publishedAt"] = df["publishedAt"] - pd.Timedelta("5 hours")
    """
    # Format date time way you want to display, https://strftime.org/
    """
    def dt_fmt(val):
        return val.strftime("%a %d, %Y, %I: %M %p ET")

    # Apply pandas function to format news published date
    df["publishedAt"] = df["publishedAt"].apply(dt_fmt)
    max_rows = 50
    list_group = dbc.ListGroup(
        [
            # dbc.Card(
            #     dbc.CardHeader([html.I(className="fas fa-newspaper mr-1"), "News Feed"])
            # )
        ] + [
            dbc.ListGroupItem(
                [
                    html.H6(
                        f"{df.iloc[i]['title'].split(' - ')[0]}.",
                        className="news-txt-headline",
                    ),
                    html.P(
                        f"by {df.iloc[i]['title'].split(' - ')[1]}  {df.iloc[i]['publishedAt']}",
                        className="news-txt-by-dt",
                    ),
                ],
                className="news-item",
                href=df.iloc[i]["url"],
                target="_blank",
            ) for i in range(min(len(df), max_rows))
        ],
        flush=True,
    )

    return list_group
예제 #8
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
예제 #9
0
 def render(title, courses: CourseList):
     element = dbc.Card([
         dbc.CardBody([
             html.H4(title, className="card-title text-white mb-0"),
         ]),
         dbc.ListGroup([CourseInput.render(course[0], course[1])
                        for course in courses], flush=True)
     ], color="primary text-primary mt-3")
     return element
예제 #10
0
def macro_component():
    """
    The main macro panel
    :return:
    """

    title = "Macro Data"

    output_row = dbc.Row(
        dbc.Tabs(
            id="macro-tab-selector",
            active_tab="ust-curve",
            children=[
                dbc.Tab(label="US Treasury Curve",
                        tab_id="ust-curve",
                        children=[subpanel.usd_treasury_curve()]),
                dbc.Tab(
                    label="USD Swap Curve",
                    tab_id="usd-swap-curve",
                    children=[
                        subpanel.usd_swap_curve(),
                        dbc.Col([
                            html.A(
                                dbc.Button("Data Citations",
                                           className="mr-1",
                                           id="usd-swap-citations-button"))
                        ],
                                width=4),
                        dbc.Popover(
                            [
                                dbc.PopoverHeader("USD Swap Citations"),
                                dbc.PopoverBody([
                                    dbc.ListGroup([
                                        dbc.ListGroupItem([
                                            dbc.ListGroupItemHeading(
                                                f"ICE USD Swap {yr} Yr"),
                                            dbc.ListGroupItemText(
                                                dl.macro.get_usd_swap_citation(
                                                    yr))
                                        ]) for yr in dl.macro.maturities
                                    ])
                                ])
                            ],
                            id="usd-swap-citations",
                            is_open=False,
                            target="usd-swap-citations-button",
                        )
                    ]),
                dbc.Tab(label="Coming Soon...",
                        tab_id="coming-soon",
                        disabled=True)
            ]))

    obj = panel_template(title, output_row)

    return obj
예제 #11
0
    def make_activity_info_header(activity: Activity):
        if activity.type == ('Run' or 'Walk'):
            return html.Div([])
        metrics = ActivityMetrics(activity=activity, config={'ftp': 290})
        line1 = dbc.ListGroup(
            [
                dbc.ListGroupItem([
                    dbc.ListGroupItem(activity.name,
                                      style={'font-size': '0.7rem'}),
                    dbc.ListGroupItem(activity.date),
                    dbc.ListGroupItem(""),
                ],
                                  style={
                                      'font-size': '0.6rem',
                                      'line-height': '0.1em'
                                  }),
                dbc.ListGroupItem([
                    dbc.ListGroupItem("Power", style={'font-size': '0.7rem'}),
                    dbc.ListGroupItem(f"{metrics.average_power}"),
                    dbc.ListGroupItem(f"{metrics.normalized}"),
                    dbc.ListGroupItem(f"{metrics.work}"),
                ],
                                  style={
                                      'font-size': '0.6rem',
                                      'line-height': '0.1em'
                                  }),
                dbc.ListGroupItem([
                    dbc.ListGroupItem("HR", style={'font-size': '0.7rem'}),
                    dbc.ListGroupItem(f"{metrics.average_hr}"),
                    dbc.ListGroupItem(f"{metrics.max_hr}"),
                ],
                                  style={
                                      'font-size': '0.6rem',
                                      'line-height': '0.1em'
                                  }),
            ],
            flush=True,
            horizontal=True,
            className="mb-1",
            style={'font-size': '0.8rem'},
        )

        # line2 = dbc.ListGroup(
        #     [
        #
        #     ],
        #     flush=True,
        # )

        list_group = html.Div(
            [
                line1,
                # line2,
            ], )
        return list_group
예제 #12
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
예제 #13
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', ""))
                        ])
                    ])
                ])
            ]))
    ]
예제 #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).
    
    TODO: Add callbacks to fetch local state news, if none get entire US news
    
    :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    
    """
    if state == "US":
        json_data = requests.get(NCOV19_API + "news").json()
    else:
        payload = {
            "state": STATES_COORD[state]["stateAbbr"],
            "topic": "coronavirus"
        }
        payload = json.dumps(payload)
        json_data = requests.post(NCOV19_API + "news", data=payload).json()
    if json_data["success"] == True:
        json_data = json_data["message"]
        df = pd.read_json(json_data)
        df = pd.DataFrame(df[["title", "url", "published"]])

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

    else:
        list_group = []

    return list_group
예제 #15
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
예제 #16
0
def display_rebalance_output(n_clicks, text_area: str, results):
    if not n_clicks:
        raise PreventUpdate
    if not text_area:
        raise PreventUpdate
    if not results:
        raise PreventUpdate
    try:
        portfolio = json.loads(text_area)
    except (Exception):
        return dbc.Alert("Invalid JSON format", color="danger"),
    min_vol = results[MIN_VOL]['Expected Weights']
    max_sharpe = results[MAX_SHARPE]['Expected Weights']
    symbols = portfolio.keys()
    with open('config.json', 'r') as file:
        config = json.load(file)['crypto']
    api_key = config['crypto_compare_api_key']
    url = 'https://min-api.cryptocompare.com/data/pricemulti'
    params = {"fsyms": ','.join(symbols), "tsyms": "USD", "api_key": api_key}
    exchange_rate = requests.get(url, params=params).json()
    usd_price = {key: value['USD'] for key, value in exchange_rate.items()}
    display_result = {}
    results = pd.DataFrame({"a": portfolio, 'usd_price': usd_price})
    results['holding'] = results['a'] * results['usd_price']
    results['w'] = results['holding'] / results['holding'].sum()
    total_asset_value = results['holding'].sum()
    for entry in [('Maximmum Sharpe Ratio', max_sharpe),
                  ('Minimmum Volatitly', min_vol)]:
        results['ew'] = pd.Series(entry[1])
        results['ew_r'] = results['ew'] - results['w']
        results['ew_usd'] = results['ew_r'] * \
            results['holding'].sum()
        results['ew_a'] = results['ew_usd'] / results['usd_price']
        display_result[entry[0]] = results['ew_a'].to_dict()
    return [html.H4(f'Total Asset Value: ${total_asset_value:.4f}'),
            html.Hr()] +\
        [dbc.Row(dbc.Col([
            html.H5(name),
            dbc.ListGroup([
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading(f"{value:.5f} {key}"),
                    dbc.ListGroupItemText(f"{value*usd_price[key]:=.2f} USD"),
                ]) for key, value in ew.items()
            ], horizontal=True),
            html.Hr()
        ]),
            align='center', justify='center'
        ) for name, ew in display_result.items()] +\
        [dbc.Label("* positive value is for buy" +
                   " and negative value is for sell")]
예제 #17
0
def make_emission_nav(current_page):
    df = predict_emissions()
    target_year = get_variable('target_year')

    ts = df.sort_index().drop(columns='Forecast', level=0).loc[target_year]

    items = []

    current_sector = current_page.emission_sector if current_page and current_page.emission_sector else None
    # Sort sectors based on the target year emissions
    sector_emissions = ts.sum(level=0).sort_values(ascending=False)

    def render_sector(s, sector_path, level):
        sector_emissions = s.sum(level=0).sort_values(ascending=False)
        for subsector_name, emissions in sector_emissions.iteritems():
            if not subsector_name:
                continue
            subsector_path = tuple([*sector_path, subsector_name])

            next_metadata = SECTORS
            for sp in subsector_path:
                metadata = next_metadata[sp]
                next_metadata = metadata.get('subsectors', {})

            if current_sector == subsector_path:
                active = True
            else:
                active = False

            page = get_page_for_emission_sector(*subsector_path)
            item = _make_nav_item(metadata['name'],
                                  emissions,
                                  level,
                                  page,
                                  active=active)
            items.append(item)

            ss = s[subsector_name]
            if isinstance(ss, pd.Series):
                render_sector(ss, subsector_path, level + 1)

    render_sector(ts, tuple(), 0)

    items.append(
        _make_nav_item('Yhteensä', sector_emissions.sum(), 0, None, bold=True))

    return html.Div([
        html.H6('Päästöt vuonna %s' % target_year),
        dbc.ListGroup(children=items)
    ])
예제 #18
0
def PaletteList():
    return dbc.Row(dbc.ListGroup([
        PaletteItem(idx=1, name='Contact Density'),
        PaletteItem(idx=2, name='Conservation'),
        PaletteItem(idx=3, name='Custom files'),
        PaletteItem(idx=4, name='Disorder'),
        PaletteItem(idx=5, name='Membrane Topology'),
        PaletteItem(idx=6, name='MSA Coverage'),
        PaletteItem(idx=7, name='Secondary Structure'),
        PaletteItem(idx=8, name='Hydrophobicity'),
        PaletteItem(idx=9, name='Heatmap'),
    ],
                                 style={'width': '75%'}),
                   justify='center',
                   align='center')
예제 #19
0
def update_userid(value):
    reviews = get_reviewed_restaurants(value)
    n = len(reviews)
    recs = get_n_preds(value, n)
    htmls = [
        dbc.ListGroupItem(reviews[i][0] + ': ' + reviews[i][1])
        for i in range(n)
    ]
    urls = [
        'http://www.google.com/maps/place/' + str(recs[i][2]) + ',' +
        str(recs[i][3]) for i in range(n)
    ]
    preds = [
        dbc.ListGroupItem([
            recs[i][0] + ': ' + str(round(recs[i][1], 2)) + ' ',
            html.A('(map)', href=urls[i])
        ]) for i in range(n)
    ]
    return [
        html.Div(children=[
            dbc.Card(
                dbc.CardBody([
                    html.H4("{0} User Reviews".format(value)),
                    dbc.ListGroup(htmls)
                ]), )
        ],
                 className="col-md-6"),
        html.Div(children=[
            dbc.Card(
                dbc.CardBody([
                    html.H4('Recommendations {0} User'.format(value)),
                    dbc.ListGroup(preds)
                ]), )
        ],
                 className="col-md-6")
    ]
예제 #20
0
def make_transaction_group(df: pd.DataFrame):
    """Create a group of transactions"""
    list_items = []
    for idx, transaction in df.iterrows():
        list_items.append(
            dbc.ListGroupItem(
                [
                    dbc.ListGroupItemHeading(html.H6(transaction.payee)),
                    dbc.ListGroupItemText([
                        html.P(transaction.display_name),
                        html.P(f"$ {transaction.total}")
                    ]),
                ],
                action=True,
            ))
    return dbc.ListGroup(list_items)
예제 #21
0
def _update_project_options(n_clicks):
    """Use the Rubicon client to load the available projects."""
    app._rubicon_model.update_projects()

    return dbc.ListGroup(children=[
        dbc.ListGroupItem(
            id={
                "type": "project-selection--project",
                "index": project["value"]
            },
            className="project-selection--project",
            children=project["value"],
            n_clicks=0,
            action=True,
        ) for project in app._rubicon_model.project_options
    ])
예제 #22
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
예제 #23
0
def TutorialList():
    return dbc.Row(
        dbc.ListGroup(
            [
                TutorialItem(idx=1, name='Creating your first plot'),
                TutorialItem(
                    idx=2,
                    name='Compare a contact prediction with a PDB file'),
                TutorialItem(idx=3,
                             name='Storing, loading and sharing a session'),
                TutorialItem(idx=4,
                             name='Residue-Residue distance predictions'),
                # TutorialItem(idx=5, name='Video tutorial')
            ],
            style={'width': '75%'}),
        justify='center',
        align='center')
예제 #24
0
def news_feed(state=None) -> dbc.ListGroup:
    """Displays news feed on the right hand side of the display. Adjust the NewsAPI time
    time to Eastern Time (w/ DST).
    
    TODO: Add callbacks to fetch local state news, if none get entire US news
    
    :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    
    """

    json_data = requests.get(NCOV19_API + "news").json()
    if json_data["success"] == True:
        json_data = json_data["message"]
        df = pd.read_json(json_data)
        df = pd.DataFrame(df[["title", "url", "publishedAt"]])

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

    else:
        print("getting executed for no reason")
        list_group = []

    return list_group
예제 #25
0
def news_feed(country):

    newsapi = NewsApiClient(api_key='6c7bb4a85ec049b3b9459379a35a36fa')
    q = 'corona'
    json_data = newsapi.get_top_headlines(q=q, language='en', country='us')
    # country_name_code_dict.get(str(country)
    data = pd.DataFrame(json_data['articles'])

    source = data['source'][0].get('name')
    source = []
    for i in range(data.shape[0]):
        news = data['source'][i].get('name')
        source.append(news)
    news_data = pd.DataFrame(data[["title", "url"]])
    news_data['source'] = source

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

    return list_group
예제 #26
0
파일: pmcalc.py 프로젝트: I194/PMTools_plt
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"
                # ),
                )
예제 #27
0
파일: app.py 프로젝트: okyere/dash_tutorial
def generate_list(tellers):

    teller_list = []
    for i in tellers:

            credit = get_teller_credits(i)
            debit = get_teller_debits(i)

            teller_list.append(
                    dbc.Row(dbc.ListGroup([
                           dbc.ListGroupItem(i),
                           dbc.ListGroupItem("Credit: {}".format(credit)),
                           dbc.ListGroupItem("Debit: {}".format(debit)),
                        ]))
                
             )
    
    return teller_list
예제 #28
0
def get_link_list(link_list, name):

    list_group = dbc.ListGroup(children=[])

    if len(link_list)==0:
        list_group.children.append(
                dbc.ListGroupItem(
                    "No " + name + " available" )
            )
        return list_group
    else:
        for i in range(len(link_list)):
            list_group.children.append(
                dbc.ListGroupItem(
                    name + " #" +  str(i+1), href=link_list[i], target='_blank'
                )
            )
    return list_group
예제 #29
0
        def _show_metadata_from_graphs(passed_data: dict,
                                       duration_data: dict) -> tuple:
            """
            """

            if not (passed_data or duration_data):
                raise PreventUpdate

            metadata = no_update
            open_canvas = False
            title = "Job Statistics"
            trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
            if trigger_id == "graph-passed":
                graph_data = passed_data["points"][0].get("hovertext", "")
            elif trigger_id == "graph-duration":
                graph_data = duration_data["points"][0].get("text", "")
            if graph_data:
                metadata = [
                    dbc.Card(
                        class_name="gy-2 p-0",
                        children=[
                            dbc.CardHeader(children=[
                                dcc.Clipboard(
                                    target_id="metadata",
                                    title="Copy",
                                    style={"display": "inline-block"}), title
                            ]),
                            dbc.CardBody(
                                id="metadata",
                                class_name="p-0",
                                children=[
                                    dbc.ListGroup(children=[
                                        dbc.ListGroupItem([
                                            dbc.Badge(x.split(":")[0]),
                                            x.split(": ")[1]
                                        ]) for x in graph_data.split("<br>")
                                    ],
                                                  flush=True),
                                ])
                        ])
                ]
                open_canvas = True

            return metadata, open_canvas
예제 #30
0
        def update_meta_data_list(series_data_dict, **kwargs):

            model_name = kwargs["model_selector"]

            model_description = series_data_dict["all_forecasts"][model_name][
                "model_description"]
            if model_description == model_name:
                model_description = ""

            model_cv_score = series_data_dict["all_forecasts"][model_name][
                "cv_score"]

            return dbc.ListGroup([
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading("Model Details"),
                    dbc.ListGroupItemText([
                        html.P(model_name),
                        html.P(model_description),
                        html.P("CV score: %f" % model_cv_score),
                    ]),
                ]),
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading("Forecast Updated At"),
                    dbc.ListGroupItemText(
                        series_data_dict["forecasted_at"].strftime(
                            "%Y-%m-%d %H:%M:%S")),
                ]),
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading("Data Collected At"),
                    dbc.ListGroupItemText(
                        series_data_dict["downloaded_dict"]
                        ["downloaded_at"].strftime("%Y-%m-%d %H:%M:%S")),
                ]),
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading("Data Source"),
                    dbc.ListGroupItemText([
                        html.A(
                            series_data_dict["data_source_dict"]["url"],
                            href=series_data_dict["data_source_dict"]["url"],
                        )
                    ]),
                ]),
            ])