Beispiel #1
0
def render_indicators(df):
    rdays = df['mobility_limitation'].dropna().cumsum().iloc[-1]
    icu_cap = ((df['available_icu_units'] / df['total_icu_units']) < 0.1).sum()
    dead = df['dead'].dropna().iloc[-1]

    deck = []
    deck.append(
        dbc.Card(
            dbc.CardBody([
                html.H6(_('Restriction Day Index')),
                html.P('%d' % rdays, className="display-4 text-primary mb-1"),
                html.Small(
                    _('''The cumulative sum of daily percentages of mobility restrictions. The index can be used as a rough indicator of harmful psychological, social and economic effects. A higher index means more severe effects.'''
                      )),
            ])))
    deck.append(
        dbc.Card(
            dbc.CardBody([
                html.H6(_('Days ICU Capacity Exceeded')),
                html.P('%d' % icu_cap,
                       className="display-4 text-primary mb-1"),
                html.Small(
                    str(
                        _("Number of days that ICU units had less than 10%% of capacity left."
                          )).replace('%%', '%')),
            ])))
    deck.append(
        dbc.Card(
            dbc.CardBody([
                html.H6(_('Fatalities')),
                html.P('%d' % dead, className="display-4 text-primary mb-1"),
                html.Small(
                    _("Total number of deaths at the end of simulation.")),
            ])))
    return dbc.CardDeck(deck, className='mb-4')
Beispiel #2
0
 def layout(self):
     return html.Div(
         [
             dbc.Button(self.button_text, id=self.name+'modal-open', size=self.button_size, outline=self.button_outline),
             dbc.Modal([
                 dbc.ModalHeader(self.title),
                 dcc.Graph(id=self.name+'-modal-graph', style={"max-height": "none", "height": "80%"}),
                 dbc.ModalFooter([   
                     html.Div([
                         html.Div([
                             html.Div([
                                 dbc.Button(html.Small("Description"), 
                                        id=self.name+'-show-description',
                                        color='link', className="text-muted ml-auto"),
                                 dbc.Fade([
                                         html.Small(self.description, className="text-muted")],
                                         id=self.name+'-fade',
                                         is_in=True,
                                         appear=True), 
                             ], style=dict(display="none" if not self.description else None))
                         ], className="text-left"),  
                         html.Div([
                             dbc.Button("Close", id=self.name+'-modal-close', className="mr-auto")            
                         ], className="text-right", style=dict(float='right')),   
                         
                     ], style={"display":"flex"}),             
                 ], className="justify-content-between")       
             ], id=self.name+'-modal', style={"max-width": "none", "width": "80%"}) 
         ], style={"display":"flex", "justify-content":"flex-end"})
Beispiel #3
0
def metric_card(metric_name, metric_value, n_columns=1):
    """Generate UI components for displaying a single metric."""
    word_to_number = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve"
    ]
    return html.Div(children=[
        html.Small(f"{metric_name}\n"),
        html.Small(html.B(round(metric_value, METRIC_PRECISION)))
    ],
                    className=f"{word_to_number[int(12/n_columns)]} columns")
Beispiel #4
0
def get_lyric_snippet(song_data):
    lyric_row = []
    lyric_snippet = [
        snippet for snippet in song_data["lyric_snippet"][:100].split("|")
        if snippet
    ]
    for i, lyric in enumerate(lyric_snippet):
        if i < len(lyric_snippet) - 1:
            lyric_row += [html.Small(html.Em(lyric)), html.Br()]
        else:
            lyric_row.append(html.Small(html.Em(lyric + "...")))
    return lyric_row
Beispiel #5
0
def getSimilarPanel(uid):
    results = user_get_similar(uid)
    temp = None
    if len(results) > 0:
        temp = html.Div(children=[
            html.A([
                html.Span('Top{}.'.format(index + 1),
                          style={'marginRight': 'auto'}),
                html.Strong(user['nickname'],
                            style={
                                'textOverflow': 'ellipsis',
                                'overflow': 'hidden',
                                'width': '50%',
                                'whiteSpace': 'nowrap'
                            }),
                html.Small('相似度: {}'.format(round(float(user['degree']), 3)),
                           style={'marginLeft': 'auto'}),
            ],
                   className='panel-block',
                   **{
                       'data-uid': user['user_id'],
                       'data-nickname': user['nickname']
                   }) for index, user in enumerate(results)
        ])
    return temp
Beispiel #6
0
def create_graphs_layout(suffix=''):
    return dbc.Col([dcc.Loading(
        children=[
            dbc.Row(children=[dbc.Col(children=[html.H6(_('Intervention distribution')),
                                                dcc.Graph(id=f'indicator-graphic2{suffix}',
                                                          className='row')],
                                      style={'marginTop': '20px', 'flex': 1}),
                              dbc.Col(children=[html.H6(_('Flight exclusions')),
                                                dcc.Graph(id=f'indicator-graphic1{suffix}',
                                                          className='row')],
                                      style={'marginTop': '20px', 'flex': 1}),

                              # dbc.Col(children=[html.H6(_('Intervention distribution')),
                              #                   sankey.Sankey(
                              #                       id=f'flows-graphic{suffix}',
                              #                       width=500, height=500, ),
                              #                   ], style={'marginTop': '20px', 'flex': 1},
                              #         className='row')
                              ],
                    style={'marginTop': '20px', 'paddingRight': '20px', 'paddingLeft': '20px'}),
            dbc.Row(children=[
                dbc.Col(children=[html.H6(_('Time to arrival histogram when a drone is sent')),
                                  dcc.Graph(id=f'indicator-graphic3{suffix}', className='row')],
                        style={'marginTop': '20px', 'flex': 1}),
                dbc.Col(children=[html.H6(_('Comparison of times to arrival for all incidents')),
                                  html.Small(html.I(_('Hover over the graph to get more info'))),
                                  dcc.Graph(id=f'indicator-graphic4{suffix}', className='row')],
                        style={'marginTop': '20px', 'flex': 1})],
                    style={'marginTop': '20px', 'paddingRight': '20px', 'paddingLeft': '20px'})],
        style={'paddingRight': '20px', 'paddingLeft': '20px'})])
Beispiel #7
0
def tip_card(tip, domain):
    try:
        dtotal, dcompleted, dpercent = 0, 0, 0
        for deliverable in tip['Deliverables']:
            dtotal += 1
            if deliverable['State']['Name'] == 'Completed':
                dcompleted += 1
        dpercent = dcompleted / dtotal * 100
    except KeyError:
        pass
    except ZeroDivisionError:
        dpercent = 0
    return html.Div(
        className='row align-items-center',
        children=[
            html.Div(className='col-auto',
                     children=[circle_graph(dpercent, size=50, fontsize=12)]),
            html.Div(className='col-auto',
                     children=[indicate(tip['TrackStatus']['Name'])]),
            html.Div(
                className='col',
                children=[
                    html.B(tip['Name']),
                    html.Small(
                        className='d-block item-except text-sm text-muted',
                        children=[tip['ProjectManager']['Name']]),
                    html.Div(children=[
                        "{} deliverables of {} completed".format(
                            dcompleted, dtotal),
                    ]),
                    html.Span(className='badge bg-info', children=[domain]),
                ]),
        ],
        style={'padding': '10px'})
Beispiel #8
0
def Footer(fixed=False):
    if fixed:
        style = {
            'position': 'fixed',
            'background': 'gray',
            'width': '100%',
            'bottom': '0px'
        }
    else:
        style = {}

    return html.Div([
        html.Br(),
        html.Br(),
        html.Br(),
        dbc.Navbar([
            dbc.Row(dbc.Col([
                html.Small('Hosted by', className='mr-3'),
                html.A(html.Img(src='/assets/ccp4-online_logo.png',
                                height='35hv'),
                       href=UrlIndex.CCP4_ONLINE.value)
            ],
                            width=12),
                    className='text-center container-fluid')
        ],
                   className='footer py-3',
                   style=style)
    ])
Beispiel #9
0
def render_book(book_data, extra_html):
    """Creates an html representation of a book.
    """
    extra_html = extra_html if extra_html else html.Div()

    authors = book_data['authors'].split(',')
    if len(authors) > 1:
        authors = f'{authors[0]} et al.'

    title = book_data['title']
    if len(title) > 50:
        title = f'{title[:50]}...'

    book_layout = html.Div(
        className='col-sm-2 d-flex flex-column align-items-center',
        children=[
            html.A(href=get_goodreads_url(book_data['goodreads_book_id']),
                   children=[
                       html.Img(src=book_data['image_url']),
                   ]),
            html.Div(title=book_data['authors'],
                     children=html.Small(authors, style={'color': '#999999'})),
            html.Div(title=book_data['title'], children=html.Strong(title)),
            extra_html
        ],
        style={
            'padding': '20',
            'text-align': 'center'
        })

    return book_layout
def national_stats(data, update):
    return html.Div([
        html.H3("United States National Stats"),
        html.P(html.Small(f"Last update: {update}")),
        html.H4("Current Totals"),
        build_table(data)
    ])
Beispiel #11
0
def discrete_background_color_bins(df, n_bins=5, columns='all'):
    import colorlover
    bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
    if columns == 'all':
        if 'id' in df:
            df_numeric_columns = df.select_dtypes('number').drop(['id'],
                                                                 axis=1)
        else:
            df_numeric_columns = df.select_dtypes('number')
    else:
        df_numeric_columns = df[columns]
    df_max = df_numeric_columns.max().max()
    df_min = df_numeric_columns.min().min()
    ranges = [((df_max - 0.0) * i) + 0.0 for i in bounds]
    ranges_negative = [((0.0 - df_min) * i) + df_min for i in bounds]

    styles = []
    legend = []
    for i in range(1, len(bounds)):
        min_bound = ranges[i - 1]
        max_bound = ranges[i]
        backgroundColor = colorlover.scales[str(n_bins)]['seq']['Greens'][i -
                                                                          1]
        backgroundColorNegative = colorlover.scales[str(
            n_bins)]['seq']['Reds'][i - 1]
        color = 'white' if i > len(bounds) / 2. else 'inherit'

        for column in df_numeric_columns:
            styles.append({
                'if': {
                    'filter_query': ('{{{column}}} >= {min_bound}' +
                                     (' && {{{column}}} < {max_bound}' if
                                      (i < len(bounds) - 1) else '')).format(
                                          column=column,
                                          min_bound=min_bound,
                                          max_bound=max_bound),
                    'column_id':
                    column
                },
                'backgroundColor': backgroundColor,
                'color': color
            })
        legend.append(
            html.Div(style={
                'display': 'inline-block',
                'width': '60px'
            },
                     children=[
                         html.Div(
                             style={
                                 'backgroundColor': backgroundColor,
                                 'borderLeft': '1px rgb(50, 50, 50) solid',
                                 'height': '10px'
                             }),
                         html.Small(round(min_bound, 2),
                                    style={'paddingLeft': '2px'})
                     ]))

    return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))
def get_sysinfo():
    info = psutil.virtual_memory()

    return [
        html.Small('{:.3f}GB Memory Used ({}%)'.format(info[3] / (1024**3),
                                                       info[2]),
                   className='text-muted'),
    ]
Beispiel #13
0
def Chapter(name, href=None, caption=None):
    linkComponent = html.A if href.startswith('http') else dcc.Link
    return html.Div([
        html.Li(linkComponent(name, href=href, style={'paddingLeft': 0})),
        html.Small(dcc.Markdown(s(caption or '')), style={
            'display': 'block',
            'marginTop': '-10px' if caption else ''
        }) if caption else None
    ])
Beispiel #14
0
def target_selector(tag):
    options = [{**target, 'disabled': False} for target in TARGET_OPTIONS]
    return html.Div([
        dcc.Checklist(id=f'{tag}-target-selection',
                      options=options,
                      labelStyle={'display': 'inline-block'},
                      style={'display': 'inline-block'},
                      value=AVAILABLE_TARGETS),
        html.P([html.Small(f'select models for {tag}')]),
    ])
Beispiel #15
0
def key_metric_card(id, title, default_value='', subtext=''):
    return html.Div([
        html.Div([html.H4(title, className='my-0 font-weight-normal')],
                 className='card-header'),
        html.Div([
            html.H1([default_value], className='card-title', id=id),
            html.Small(subtext, className='text-muted')
        ],
                 className='card-body')
    ],
                    className="card mb-4 shadow-sm")
 def serve_layout():
     return html.Div([
         navbar(),
         nodes_stat(),
         map_block(),
         dbc.Container(
             [
                 dbc.Row([
                     dbc.Col(
                         countries_chart(),
                         width=4,
                         xs=12,
                         md=6,
                         lg=4,
                         className='mt-4'
                     ),
                     dbc.Col(
                         ases_chart(),
                         width=4,
                         xs=12,
                         md=6,
                         lg=4,
                         className='mt-4'
                     ),
                     dbc.Col(
                         history_chart(),
                         width=4,
                         xs=12,
                         lg=4,
                         className='mt-4'
                     )
                 ]),
                 dbc.Row([
                     dbc.Col(
                         versions_chart(),
                         width=12,
                         className='mt-4'
                     ),
                 ])
             ],
             fluid=FLUID,
             className='mb-4'
         ),
         html.Footer(
             dbc.Container(
                 dbc.Row(
                     dbc.Col(
                         html.Small("Roman Kablukov © 2020")
                     )
                 )
             ),
             className="p-3 mb-2 bg-light text-dark"
         )
     ])
Beispiel #17
0
def intermediate_link(selected, owner, res, land, prop, postcode):
    refDict = {
        "Free_Lease_Hold_Ind": owner,
        "Property_State": postcode,
        "Property_Type": prop,
        "Residential_Type": res,
        "Landed_Type": land
    }

    if postcode == None:
        refDict["Property_State"] = 47301

    #convert to state
    tempDF = masterDF.copy()
    tempDF = tempDF.loc[tempDF["Postcode"] == refDict["Property_State"]].head()
    print(tempDF.head())
    refDict["Property_State"] = tempDF.iloc[0]["Property_State"]

    #create predicted pie chart
    labels = ["SnP < OMV", "SnP = OMV", "SnP > OMV"]
    values = getNewNN(refDict)
    colors = ['#636EFA', '#EF553B', '#00CC96']

    fig = go.Figure(data=[
        go.Bar(y=labels,
               x=values,
               marker_color=colors,
               orientation="h",
               width=[0.35, 0.35, 0.35])
    ])
    fig.update_layout(
        template="plotly_dark",
        paper_bgcolor="#303030",
        plot_bgcolor="#303030",
        margin={
            "r": 0,
            "t": 0,
            "l": 0,
            "b": 0
        },
        width=400,
        height=200,
        showlegend=False,
    )

    fig.update_traces(textposition="inside")
    fig.update_xaxes(title_text="Confidence")

    return refDict[selected], [
        html.H5("Predicted Confidence Level"),
        html.Br(),
        dcc.Graph(figure=fig),
        html.Small("Model Accuracy: 78.6%")
    ]
Beispiel #18
0
def recipient_contents(g, all_funders):
    if g["recipientOrganization"][0]["id"] in all_funders:
        return [
            html.Strong(g["recipientOrganization"][0]["name"]),
            html.Br(),
            html.Small(
                "*This organisation is also a funder so this grant may be intended for re-distribution as grants"
            ),
        ]
    else:
        return [g["recipientOrganization"][0]["name"]]
Beispiel #19
0
def dataset_metrics_section(section_name, metrics):
    """Generate the UI content for displaying arbitrary number of metrics associated with
    an arbitrary number of datasets (train, test, validation, etc.)"""
    cards = []
    for metric, metric_value in metrics.items():
        card = metric_card(metric, metric_value, len(metrics))
        cards.append(card)

    return html.Div(
        [html.B(html.Small(section_name)),
         html.Div(cards, className="row")])
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', ""))
                        ])
                    ])
                ])
            ]))
    ]
def discrete_background_color_bins(df, styles, n_bins, lscale, columns):
    bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
    df_numeric_columns = df[columns]
    df_max = max(0, df_numeric_columns.max().max())
    df_min = min(0, df_numeric_columns.min().min())
    ranges = np.linspace(df_min, df_max, n_bins+1)
    neg = len(list(filter(lambda x: (x < 0), ranges)))
    pos = len(ranges) - neg
    legend = []
    for i in range(1, len(bounds)):
        min_bound = ranges[i - 1]
        max_bound = ranges[i]
        scale = "Greens" if min_bound >= 0 else "Reds"
        colorindex = neg - i if min_bound < 0 else i - 1
        backgroundColor = colorlover.scales[str(
            n_bins)]['seq'][scale][colorindex]
        color = 'white' if (i < neg/2 or i > neg + pos/2) else 'inherit'

        for column in df_numeric_columns:
            styles.append({
                'if': {
                    'filter_query': (
                        '{{{column}}} >= {min_bound}' +
                        (' && {{{column}}} < {max_bound}' if (
                            i < len(bounds) - 1) else '')
                    ).format(column=column,
                             min_bound=min_bound,
                             max_bound=max_bound),
                    'column_id': column
                },
                'backgroundColor': backgroundColor,
                'color': color
            })
        legend.append(
            html.Div(
                style={
                    'display': 'inline-block',
                    'width': f'{100//(1+n_bins)}%'
                },
                children=[
                    html.Div(
                        style={
                            'backgroundColor': backgroundColor,
                            'borderLeft': '1px rgb(50, 50, 50) solid',
                            'height': '10px'
                        }
                    ),
                    html.Small(f"{int(min_bound)//lscale}",
                               style={'paddingLeft': '2px'})
                ])
        )

    return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))
Beispiel #22
0
def serve_layout():
    return dbc.Container([
        dbc.Row([
            dbc.Col([
                dbc.Row([
                    dbc.Col(html.H1("Covid-19 Metrics")),
                    dbc.Col(html.A(
                        "Github",
                        href="https://github.com/mstellon/covid19-us-metrics",
                        target="_blank"),
                            style={"text-align": "right"})
                ],
                        justify='between'),
                html.Hr(),
                dcc.Markdown(intro)
            ])
        ]),
        dbc.Row(
            dbc.Col([
                components.national_stats(data.get_national_stats(),
                                          data.national_last_update)
            ])),
        dbc.Row([
            dbc.Col([
                html.H3("Past and Projected Data"),
                html.P("Click legend to turn data elements on or off"),
                html.Div(components.graph_tabs(id="national-graph"))
            ]),
        ]),
        dbc.Row([
            dbc.Col([
                html.H5("Top States"),
                components.state_list_per_cap(data.top_by_cap(10))
            ],
                    width=4),
            dbc.Col(components.state_map(data.current_by_state()), width=8)
        ]),
        dbc.Row(dbc.Col(html.Hr())),
        dbc.Row([
            dbc.Col([
                html.H3("State Level detail"),
                html.Small("Click on map above or use drop-down")
            ]),
            dbc.Col(
                dcc.Dropdown(id='state-dropdown',
                             options=data.state_dropdown,
                             placeholder='Select a State'))
        ]),
        dbc.Row(id='state'),
        dbc.Row(dbc.Col(html.Hr())),
    ])
def nodes_stat():
    n_nodes, n_api, n_full_nodes = load_stat()
    api_node = random_api_node()

    stat_block = dbc.Container(
        dbc.Row([
            dbc.Col(
                html.Div([html.Small("Nodes"), html.Br(), html.Span(n_nodes)]),
                width=3,
                xs=4,
                lg=3
            ),
            dbc.Col(
                html.Div([html.Small("Api Nodes"),
                          html.Br(), html.Span(n_api)]),
                width=3,
                xs=4,
                lg=3
            ),
            dbc.Col(
                html.Div([html.Small("Full Api Nodes"),
                          html.Br(), html.Span(n_full_nodes)]),
                width=3,
                xs=4,
                lg=3
            ),
            dbc.Col(
                html.Div([html.Small("Random Api Node Url"), html.Br(),
                          html.Span(html.A(api_node, href=api_node))]),
                width=3,
                xs=12,
                lg=3
            ),
        ]),
        fluid=FLUID,
        className='mt-4 mb-4'
    )
    return stat_block
def create_sidepanel():
    sidepanel = html.Div(
        [
            html.H4(['Nutzung Stationen', html.Small(' (Version 1)', className='text-muted')]),
            dcc.Markdown('_Datengrundlage_: **5000 zufällige Stichproben aus dem Monat Oktober 2019**'),
            dcc.Markdown('''
            In der Karte werden die Stationen in Form eines Kreises angezeigt.
            
            * Die Fläche des Kreises zeigt dabei an wie viele Fahrten von dieser Station aus gestartet wurden.
            * Die Farbe des Kreises zeigt an wie viele Fahrten von dieser Station aus gestartet wurden. Anhand des
            Farbbalkens rechts neben der Karte, kann die ungefähre Anzahl Fahrten abgelesen werden.
            
            Fährt man mit der Maus über die Sation, erscheint der Stationsname.
            
            Mit Hilfe der unten verfügbaren Filter, lassen sich bestimmte Merkmale filtern.
            '''),
            dbc.Card(
                [
                    dbc.CardHeader('Filterauswahl'),
                    dbc.CardBody(
                        [
                            html.H5('Benutzerart', className='card-title'),
                            dcc.Dropdown(
                                id='tc-dropdown-user-type',
                                options=[
                                    dict(label=i18n['Subscriber'], value='Subscriber'),
                                    dict(label=i18n['Customer'], value='Customer')
                                ],
                                multi=True,
                                className='mb-3'
                            ),
                            html.H5('Geschlecht', className='card-title'),
                            dcc.Dropdown(
                                id='tc-dropdown-gender',
                                options=[
                                    dict(label=i18n['0'], value='0'),
                                    dict(label=i18n['1'], value='1'),
                                    dict(label=i18n['2'], value='2')
                                ],
                                multi=True
                            ),
                        ]
                    )
                ],
                className='mb-3'
            ),
        ]
    )

    return sidepanel
Beispiel #25
0
def create_content():
    content = html.Div(
        children=[
            html.Div(
                id="input-container",
                children=[
                    html.Div(
                        children=[
                            #html.Label("Player Name", htmlFor="aliases"),
                            html.Small("Please enter name of the main player in the replays", className="form-text, text-muted"),
                            dcc.Input(id='aliases', value='', type='text', placeholder='',className="form-control"),
                        ],
                        className="form-group",
                    ),
                    dcc.Upload(
                        id='replayUpload',
                        children=html.Div([
                            'Drag and Drop or ', html.A('Select Replays')
                        ]),
                        accept='.w3g',
                        style={
                            'height': '60px',
                            'lineHeight': '60px',
                            'borderWidth': '1px',
                            'borderStyle': 'dashed',
                            'borderRadius': '5px',
                            'textAlign': 'center',
                            'margin': '10px'
                        },
                        # Allow multiple files to be uploaded
                        multiple=True,
                        disabled=True,
                    ),
                    # html.Div(
                    #     id="confirm-content",
                    #     children=[
                    #         dcc.Markdown(id="upload-confirm-markdown"),
                    #         html.Button('Submit', id="upload-confirm-button"),
                    #     ],
                    # ),
                ],
                style={"margin-bottom": 20},
            ),
            html.Div(id='stats-container')
        ],
        id="content",
        style={"width": "100%", "height": "100%"},
    )
    return content
Beispiel #26
0
    def preview_data(contents, filename, last_modified):
        if not filename:
            return html.P("The preview of your data will appear here")

        try:
            decoded = base64.b64decode(contents.split("base64,")[1])
            df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
            df = df.head()
            return [
                html.Small("Only the first 5 rows are shown"),
                BatchTable.render(df),
                dbc.Button("Process data",
                            outline=True, color="primary", id="process-button", className="mt-3 mb-5")
            ]
        except Exception as e:
            return dbc.Alert("There is an error in uploading your data", color="danger")
Beispiel #27
0
def Chapter(name, href=None, caption=None):
    linkComponent = html.A if href.startswith('http') else dcc.Link
    return html.Div(className='toc--chapter',
                    children=[
                        html.Li(
                            linkComponent(name,
                                          href=relpath(href),
                                          id=href,
                                          className='toc--chapter-link'), ),
                        html.Small(className='toc--chapter-content',
                                   children=Markdown(caption or ''),
                                   style={
                                       'display': 'block',
                                       'marginTop': '-10px' if caption else ''
                                   }) if caption else None
                    ])
Beispiel #28
0
 def render():
     element = dbc.Card([
         dbc.CardBody([
             html.H4("Software Engineering", className="card-title"),
             html.Small("Recommended", id="se-recommended",
                        className="card-subtitle"),
         ]),
         dbc.CardFooter([
             "Predicted Performance: ",
             html.Span("-", id="se-performance"),
         ], className="border-0")
     ],
         id="se-header",
         color="secondary",
         className="text-primary"
     )
     return element
 def render():
     element = dbc.Card([
         dbc.CardBody([
             html.H4("Third Choice", className="card-title"),
             html.Small("Recommended",
                        id="third-recommended",
                        className="card-subtitle"),
         ]),
         dbc.CardFooter([
             "Predicted Success Probability: ",
             html.Span("-", id="third-proba"),
         ],
                        className="border-0")
     ],
                        id="third-header",
                        color="secondary",
                        className="text-primary")
     return element
Beispiel #30
0
def generate_cards():
    logger.debug("generate cards")
    club_services = app_controller.get_club_service_list(CLUB_NAME)
    if not club_services:
        return html.Div("No club service!")
    logger.debug(club_services)
    cards = []
    for service in club_services:
        card =  html.Div(className="card col-sm-4", children=[
            dcc.Link(href="/service/book/{}".format(service.id), children=[
                html.Div(service.name, className="card-header"),
                html.Img(className="card-img-top",
                        src=filestore.get_service_img_link(service.id, MAJOR_IMG),
                        alt=service.name),
                html.Div(className="card-body", children=[
                    html.P(service.description, className="card-text")
                ]),
                html.Div(className="card-footer", children=[
                    html.Small(service.last_update_time, className="text-muted")
                ])
            ])
        ])
        cards.append(card)

    row_list = []
    count = len(cards)
    logger.debug("number of cards {}".format(count))
    idx = 0
    while idx < count:
        r1 = cards[idx]
        r2 = cards[idx + 1]  if (idx + 1) < count else None
        r3 = cards[idx + 2]  if (idx + 2) < count else None
        row_child = []
        if r1:
            row_child.append(r1)
        if r2:
            row_child.append(r2)
        if r3:
            row_child.append(r3)
        row_list.append(html.Div(className="row", children=row_child))
        idx += 3

    logger.debug("end generate")
    return html.Div(children=row_list)