Exemple #1
0
    def account_dropdown(self, spa):

        children = self.menu_items(spa)

        if spa.login_manager.isAdmin():
            users_link = dbc.DropdownMenuItem("Users",
                                              href=spa.url_for('admin.users'))
            children.append(users_link)

        children.append(html.Div(className='dropdown-divider'))
        children.append(
            dbc.DropdownMenuItem(
                [html.I(className='fa fa-sign-in'), ' Sign out'],
                href=spa.url_for('admin.logout')))

        menu = dbc.DropdownMenu(children=children,
                                nav=True,
                                in_navbar=True,
                                label="My Account",
                                right=True)

        icon = html.I(className="fa fa fa-user",
                      style={
                          'position': 'relative',
                          'left': '4px'
                      })

        return html.Div(['', icon, menu],
                        style={'padding': '0'},
                        className='d-flex align-items-center nav-link')
Exemple #2
0
def make_summary_table(dff):
    """Make html table to show cagr and  best and worst periods"""

    table_class = "h5 text-body text-nowrap"
    cash = html.Span([html.I(className="fa fa-money-bill-alt"), " Cash"],
                     className=table_class)
    bonds = html.Span([html.I(className="fa fa-handshake"), " Bonds"],
                      className=table_class)
    stocks = html.Span([html.I(className="fa fa-industry"), " Stocks"],
                       className=table_class)
    inflation = html.Span([html.I(className="fa fa-ambulance"), " Inflation"],
                          className=table_class)

    start_yr = dff["Year"].iat[0]
    end_yr = dff["Year"].iat[-1]

    df_table = pd.DataFrame({
        "": [cash, bonds, stocks, inflation],
        f"Rate of Return (CAGR) from {start_yr} to {end_yr}": [
            cagr(dff["all_cash"]),
            cagr(dff["all_bonds"]),
            cagr(dff["all_stocks"]),
            cagr(dff["inflation_only"]),
        ],
        f"Worst 1 Year Return": [
            worst(dff, "3-mon T.Bill"),
            worst(dff, "10yr T.Bond"),
            worst(dff, "S&P 500"),
            "",
        ],
    })
    return dbc.Table.from_dataframe(df_table, bordered=True, hover=True)
Exemple #3
0
def current_readings_viewer(tab, n_intervals):
    if tab != 'current-readings':
        return

    n = n_intervals or 0  # n_intervals is initially None
    n += 1

    children = []
    margin_right = cfg.value('current_readings/margin_right', '16px')
    for serial, data in now().json.items():
        b = f'{serial} [{data["report_number"]}] - {data["alias"]} @ {data["datetime"][11:]}'
        children.append(html.B(b))
        if data['error']:
            children.append(html.P(data['error']))
        elif 'temperature2' in data:
            for sensor in ['1', '2']:
                p = []
                for key in 'temperature' + sensor, 'humidity' + sensor, 'dewpoint' + sensor:
                    p.append(html.I(key + ':', style={'color': 'grey'}))
                    p.append(
                        html.Span(f'{data[key]:.2f}',
                                  style={'margin-right': margin_right}))
                children.append(html.P(p))
        else:
            p = []
            for key in ['temperature', 'humidity', 'dewpoint']:
                p.append(html.I(key + ':', style={'color': 'grey'}))
                p.append(
                    html.Span(f'{data[key]:.2f}',
                              style={'margin-right': margin_right}))
            children.append(html.P(p))
    return html.Div(
        children=children,
        style={'fontSize': cfg.value('current_readings/font_size', '24px')})
Exemple #4
0
def get_country_table(df, year):
    return html.Div([
        html.H3('Needs -  Data from {0}'.format(year)),
        html.Table([
            html.Tr([
                html.Th([col], style={'text-align': 'center'}) for col in [
                    '',
                    html.I(className="fas fa-percent fa-lg"),
                    html.I(className="fas fa-child fa-lg"),
                    html.I(className="fas fa-box fa-lg")
                ]
            ])
        ] + [
            html.Tr([
                html.Th(col['title']),
                html.Td(df[col['type']]),
                html.
                Td(functions.format_number_col(df[col['type'] + '_children'])),
                html.Td(get_needs_kg(df, col['type']))
            ],
                    style={'color': col['color']}) for col in [
                        {
                            'title': 'Severe Wasting',
                            'type': 'severe_wasting',
                            'color': SEVERE_WASTING_COLOR
                        },
                        {
                            'title': 'Moderate Wasting',
                            'type': 'moderate_wasting',
                            'color': MODERATE_WASTING_COLOR
                        },
                        {
                            'title': 'Overall Wasting',
                            'type': 'wasting',
                            'color': WASTING_COLOR
                        },
                        {
                            'title': 'Stunting',
                            'type': 'stunting',
                            'color': STUNTING_COLOR
                        },
                        {
                            'title': 'Overweight',
                            'type': 'overweight',
                            'color': OVERWEIGHT_COLOR
                        },
                        {
                            'title': 'Underweight',
                            'type': 'underweight',
                            'color': UNDERWEIGHT_COLOR
                        },
                    ]
        ]),
        html.Div(children=[
            html.P('Source : ' + df['source'].astype(str)),
            html.P('By : ' + df['report_author'].astype(str))
        ],
                 style={'font-size': 'x-small'})
    ],
                    style={'font-size': 'small'})
Exemple #5
0
 def __init__(self, kind="download", fill="s", *args, **kwargs):
     """
     Font-awesome icon. Good options for kind are "info-circle",
     "question-circle", "book", "code".
     """
     _update_css_class(kwargs, "icon")
     if "fontastic" not in kind:
         # fontawesome styles (pre-distributed icons, e.g. download)
         super().__init__(html.I(className=f"fa{fill} fa-{kind}"), *args,
                          **kwargs)
     else:
         # fontastic styles (custom icons, e.g. the MP app icons)
         super().__init__(html.I(className=kind), *args, **kwargs)
def make_label(label, id, help_text, trailing_item=None):
    """This function returns a HTML Paragraph that contains a text
    label ('label'), possibly a help icon with pop-up help ('help_text'), and possibly
    another HTML component ('trailing_item').  The 'id' is used to assign
    an id of 'label-{id}' to the Span holding the label.
    """
    label_items = [html.Span(label, id=f'label-{id}')]
    if len(help_text.strip()):
        label_items.append(html.I(className="fas fa-question-circle"))
    if trailing_item:
        label_items.append(trailing_item)
    return html.P(children=label_items, title=help_text)
Exemple #7
0
    def layout(self, spa):
        login_required = self.login_required

        if login_required and not spa.user_logged_in():
            return None

        if self.icon:
            if self.id:
                return dbc.NavItem(
                    dbc.NavLink(
                        [html.I(className=self.icon), ' ' + self.title],
                        id=self.id,
                        href=self.href))
            else:
                return dbc.NavItem(
                    dbc.NavLink(
                        [html.I(className=self.icon), ' ' + self.title],
                        href=self.href))
        else:
            if self.id:
                return dbc.NavItem(
                    dbc.NavLink(self.title, href=self.href, id=self.id))
            else:
                return dbc.NavItem(dbc.NavLink(self.title, href=self.href))
Exemple #8
0
def make_subheading(label, link):
    slug = label.replace(" ", "")

    heading = html.H2(
        html.Span([
            label,
            html.A(
                html.I(className="fas fa-book fa-xs ms-2"),
                href=f"{DBC_DOCS}{link}",
                target="_blank",
                id=f"tooltip_target_{slug}",
            ),
        ], ), )

    return html.Div(
        [
            heading,
            dbc.Tooltip(f"See {label} documentation",
                        target=f"tooltip_target_{slug}"),
        ],
        className="mt-3",
    )
Exemple #9
0
def html_icon(icon="play_circle_filled", text="Start", alignment="left"):
    return [html.I(icon, className="material-icons " + alignment), text]
Exemple #10
0
def button(icon, text, button_type="btn-primary"):
    return html.Div([
        html.Button(html.I(className=f'fa {icon} fa-sm'), title=text, className=f"btn {button_type}")
    ], className="btn-group", role='group')
Exemple #11
0
 def signin_link(self):
     return dbc.NavItem(
         dbc.NavLink([html.I(className='fa fa-sign-in'), ' Sign in'],
                     href='/admin/login'))
Exemple #12
0
    'marginLeft': '12px',
    'fontSize': '16px',
    'letterSpacing': '4px',
    'font-weight': '400',
    'padding': '12px'
}

navbar = dbc.Navbar(children=[
    html.Div(
        [
            dbc.NavLink("Map", style=STYLE_A_ITEM),
            dbc.NavLink("Traveler", style=STYLE_A_ITEM),
        ],
        className="d-flex",
    ),
    dbc.NavLink([html.I(className="bi bi-house-fill me-2 text-white")],
                href="https://diogenet.ucsd.edu/",
                style=STYLE_A_ITEM,
                target="blank")
],
                    color="#ffffff",
                    className="d-flex justify-content-between",
                    style={
                        'color': '#ffffff',
                        'border-bottom': '1px black solid'
                    },
                    id='navbar-map')

sidebar_content = [
    html.H5('Dataset selection', className="mt-3 mb-3"),
    dcc.Dropdown(id='dataset_selection_map',
import dash_bootstrap_components as dbc
from dash import html

alerts = html.Div(
    [
        dbc.Alert(
            [
                html.I(className="bi bi-info-circle-fill me-2"),
                "An example info alert with an icon",
            ],
            color="info",
            className="d-flex align-items-center",
        ),
        dbc.Alert(
            [
                html.I(className="bi bi-check-circle-fill me-2"),
                "An example success alert with an icon",
            ],
            color="success",
            className="d-flex align-items-center",
        ),
        dbc.Alert(
            [
                html.I(className="bi bi-exclamation-triangle-fill me-2"),
                "An example warning alert with an icon",
            ],
            color="warning",
            className="d-flex align-items-center",
        ),
        dbc.Alert(
            [
def fa(className):
    """A convenience component for adding Font Awesome icons"""
    return html.I(className=className)
Exemple #15
0
def process_fmu(fmu_filename):

    basename, _ = os.path.splitext(fmu_filename)
    pickle_filename = basename + '.p'
    fmu_hash = os.path.basename(basename)

    try:
        model_description = read_model_description(fmu_filename,
                                                   validate=False)
    except Exception as e:
        alert = dbc.Alert([
            html.I(className='fas fa-times me-3'),
            f"Failed to read model description. {e}"
        ],
                          id='alert',
                          color='danger',
                          className='mt-3')
        with open(pickle_filename, 'wb') as f:
            pickle.dump([alert], f)
        return

    platforms = supported_platforms(fmu_filename)

    with zipfile.ZipFile(fmu_filename, 'r') as zf:
        nl = filter(lambda n: not n.endswith('/'), zf.namelist())

    fmi_types = []

    if model_description.modelExchange:
        fmi_types.append('Model Exchange')

    if model_description.coSimulation:
        fmi_types.append('Co-Simulation')

    def na(attr):
        value = getattr(model_description, attr)
        if value:
            return value
        else:
            return html.Span('n/a', className='text-muted')

    rows = [
        dbc.Row([
            dbc.Col(html.Span("FMI Version"), width=4),
            dbc.Col(html.Span(model_description.fmiVersion), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col("FMI Type", width=4),
            dbc.Col(', '.join(fmi_types), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col("Model Name", width=4),
            dbc.Col(model_description.modelName, width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col("Platforms", width=4),
            dbc.Col(', '.join(platforms), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Continuous States"), width=4),
            dbc.Col(html.Span(model_description.numberOfContinuousStates),
                    width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Event Indicators"), width=4),
            dbc.Col(html.Span(model_description.numberOfEventIndicators),
                    width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Model Variables"), width=4),
            dbc.Col(html.Span(len(model_description.modelVariables)), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Generation Date"), width=4),
            dbc.Col(na('generationDateAndTime'), width=8)
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Generation Tool"), width=4),
            dbc.Col(na('generationTool'), width=8)
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Description"), width=4),
            dbc.Col(na('description'), width=8)
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("SHA256"), width=4),
            dbc.Col(html.Span(fmu_hash), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("File Size"), width=4),
            dbc.Col(html.Span(f'{os.path.getsize(fmu_filename)} bytes'),
                    width=8),
        ],
                className='py-1'),
    ]

    try:
        problems = validate_fmu(fmu_filename)
    except Exception as e:
        problems = [str(e)]

    if problems:
        alert = dbc.Alert([
            html.P([
                html.I(className='fas fa-exclamation-circle me-3'),
                f"Validation failed. {len(problems)} {'problem was' if len(problems) == 1 else 'problems were'} found:"
            ]),
            html.Ul([html.Li(problem) for problem in problems])
        ],
                          id='alert',
                          color='danger',
                          className='mt-3')
    else:
        alert = dbc.Alert([
            html.I(className='fas fa-check me-3'),
            "Validation passed. No problems found."
        ],
                          id='alert',
                          color='success',
                          className='mt-3')

    variables = []

    table_header = [
        html.Thead(
            html.Tr([
                html.Th("Type"),
                html.Th("Name"),
                html.Th("Causality"),
                html.Th("Start", className='text-right'),
                html.Th("Unit"),
                html.Th("Description")
            ]))
    ]

    for variable in model_description.modelVariables:

        unit = variable.unit

        if unit is None and variable.declaredType is not None:
            unit = variable.declaredType.unit

        if variable.type == 'Boolean':
            color = '#c900c9'
        elif variable.type == 'Binary':
            color = '#ab0000'
        elif variable.type.startswith(('Int', 'Enum')):
            color = '#c78f00'
        elif variable.type.startswith(('Real', 'Float')):
            color = '#0000bf'
        else:  # String
            color = '#00a608'

        variables.append(
            html.Tr([
                html.Td(
                    html.Small(variable.type,
                               style={
                                   'color': color,
                                   'border': '1px solid ' + color,
                                   'border-radius': '1em',
                                   'padding': '0 0.5em 0 0.5em',
                               })),
                html.Td(variable.name),
                # html.Td(variable.variability),
                html.Td(variable.causality),
                html.Td(variable.start, className='text-right'),
                html.Td(unit),
                html.Td(variable.description, className='text-muted')
            ]))

    table = dbc.Table(table_header + [html.Tbody(variables)],
                      borderless=True,
                      size='sm')

    tabs = dbc.Tabs([
        dbc.Tab(rows, label="Model Info", className='p-4'),
        dbc.Tab(table, label="Variables", className='p-4'),
        dbc.Tab(html.Pre('\n'.join(nl)), label="Files", className='p-4'),
    ],
                    id='tabs')

    with open(pickle_filename, 'wb') as f:
        pickle.dump([alert, tabs], f)
Exemple #16
0
from dash import dcc, html
import dash_bootstrap_components as dbc

from dashboard.pages import sidebar
from dashboard.styles import CONTENT_STYLE

# TODO: Melhoria no css das páginas
navbar = dbc.Navbar(
    html.Div(
        [
            dbc.Button(
                html.I(className="fas fa-bars"),
                color="transparent",
                id="btn_sidebar",
            ),
            html.A(
                html.Span("Imóveis", className="navbar-brand mb-0 h1"),
                href="/",
                style={"color": "inherit"},
            ),
        ]
    )
)

layout = dcc.Loading(
    id="loading",
    children=html.Div(
        [
            dcc.Store(id="data"),
            dcc.Store(id="filtered_data"),
            dcc.Store(id="side_click"),
# the styles for the main content position it to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
    "margin-left": "18rem",
    "margin-right": "2rem",
    "padding": "2rem 1rem",
}

submenu_1 = [
    html.Li(
        # use Row and Col components to position the chevrons
        dbc.Row(
            [
                dbc.Col("Menu 1"),
                dbc.Col(
                    html.I(className="fas fa-chevron-right me-3"),
                    width="auto",
                ),
            ],
            className="my-1",
        ),
        style={"cursor": "pointer"},
        id="submenu-1",
    ),
    # we use the Collapse component to hide and reveal the navigation links
    dbc.Collapse(
        [
            dbc.NavLink("Page 1.1", href="/page-1/1"),
            dbc.NavLink("Page 1.2", href="/page-1/2"),
        ],
        id="submenu-1-collapse",
Exemple #18
0
    dbc.DropdownMenu(
        [
            dbc.DropdownMenuItem(page["name"], href=page["path"])
            for page in dash.page_registry.values()
            if not page["path"].startswith("/chapter")
        ],
        nav=True,
        label="More Pages",
    ),
    brand="Multi Page App Plugin Demo",
    color="primary",
    dark=True,
    className="mb-2",
)

sidebar_button = dbc.Button(html.I(className="fa fa-bars"), id="sidebar-btn")
sidebar = dbc.Offcanvas(
    dbc.Nav(
        [html.H3("Chapters")] + [
            dbc.NavLink(
                [
                    html.I(className=page["icon"]),
                    html.Span(page["name"], className="ms-2"),
                ],
                href=page["path"],
                active="exact",
            ) for page in dash.page_registry.values()
            if page["path"].startswith("/chapter")
        ],
        vertical=True,
        pills=True,
Exemple #19
0
sidebar = html.Div(
    [
        html.Div(
            [
                # width: 3rem ensures the logo is the exact width of the
                # collapsed sidebar (accounting for padding)
                html.Img(src=PLOTLY_LOGO, style={"width": "3rem"}),
                html.H2("Sidebar"),
            ],
            className="sidebar-header",
        ),
        html.Hr(),
        dbc.Nav(
            [
                dbc.NavLink(
                    [html.I(className="fas fa-home me-2"),
                     html.Span("Home")],
                    href="/",
                    active="exact",
                ),
                dbc.NavLink(
                    [
                        html.I(className="fas fa-calendar-alt me-2"),
                        html.Span("Calendar"),
                    ],
                    href="/calendar",
                    active="exact",
                ),
                dbc.NavLink(
                    [
                        html.I(className="fas fa-envelope-open-text me-2"),
Exemple #20
0
        dbc.themes.BOOTSTRAP,
        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css'
    ])

app.title = "FMU Check"

server = app.server

app.layout = dbc.Container([
    dcc.Store(id='submitted-store'),
    dcc.Store(id='finished-store'),
    dcc.Interval(id='update-interval', interval=500),
    dbc.Container([
        html.H2([
            "FMU Check",
            html.Span([html.I(className='fas fa-flask me-2'), "beta"],
                      className='badge badge-secondary ml-3'),
        ],
                className='bd-title'),
        html.
        P("Validate an FMU and get the meta information from the model description",
          className='bd-lead'),
        html.P(
            html.A([
                html.I(className='fas fa-info-circle me-2'),
                "What is being checked?"
            ],
                   id="what-is-validated-link",
                   style={
                       'color': '#007bff',
                       'cursor': 'pointer'