コード例 #1
0
ファイル: layouts.py プロジェクト: munrojm/crystaltoolkit
def get_table(rows: List[List[Any]],
              header: Optional[List[str]] = None) -> html.Table:
    """
    Create a HTML table from a list of elements.
    :param rows: list of list of cell contents
    :return: html.Table
    """
    contents = []
    for row in rows:
        contents.append(html.Tr([html.Td(item) for item in row]))
    if not header:
        return html.Table([html.Tbody(contents)], className="table")
    else:
        header = html.Thead([html.Tr([html.Th(item) for item in header])])
        return html.Table([header, html.Tbody(contents)], className="table")
コード例 #2
0
ファイル: common.py プロジェクト: ltalirz/sycofinder
def generate_table(dataframe, max_rows=100, download_link=False):

    components = []
    if download_link:
        csv_string = dataframe.to_csv(index=False,
                                      encoding='utf-8',
                                      float_format='%.2f')
        link = html.A('Download CSV',
                      download="synthesis_conditions.csv",
                      href="data:text/csv;charset=utf-8," +
                      urllib.parse.quote(csv_string),
                      target="_blank",
                      className='button')
        components.append(link)

    components.append(
        html.Table(
            # Header
            [html.Tr([html.Th(col) for col in dataframe.columns])] +

            # Body
            [
                html.Tr([
                    html.Td(cell_format(dataframe.iloc[i][col]))
                    for col in dataframe.columns
                ]) for i in range(min(len(dataframe), max_rows))
            ]))

    return components
コード例 #3
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'})
コード例 #4
0
ファイル: wfp.py プロジェクト: tquiviger/market-monitor
def get_tenders_table():
    return html.Table([
        html.Tbody(
            [
                html.Tr([
                    html.Th(tender['date']),
                    html.Td(tender['tender_id']),
                    html.Td(tender['supplier'],
                            style=get_style(tender['supplier'])),
                    html.Td(tender['product'],
                            style={'color': get_color(tender['product_type'])
                                   }),
                    html.
                    Td(functions.format_number(tender['amount_usd']) + ' USD'),
                    html.Td(display_original_amount(tender)),
                    html.Td(tender['destination'])
                ]) for index, tender in csv_reader.get_wfp_tender_awards().
                sort_values(['date'], ascending=False).iterrows()
            ],
            style={
                'display': 'block',
                'height': '500px',
                'overflow-y': 'scroll',
                'overflow-x': 'hidden'
            })
    ],
                      style={'font-size': 'x-small'})
コード例 #5
0
def generate_table(dataframe):
    return html.Table([
        html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
        html.Tbody([
            html.Tr(
                [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(len(dataframe))
        ])
    ])
コード例 #6
0
def make_dash_table(old_code, new_code):
    # Line 2
    old_income = get_attribute(old_code, 'Average income of inhabitants')
    new_income = get_attribute(new_code, 'Average income of inhabitants')
    result_income = float(new_income) / float(old_income) - 1
    if result_income > 0:
        analysis_income = f"↗ {result_income:.2%} potential increase"
    elif result_income > -0.15:
        analysis_income = "Similar income"
    else:
        analysis_income = f"↘ {result_income:.2%} easier life"

    # Line 3
    attribute_name = 'Academic degree - Higher level university degree scaled'
    old_education = float(get_attribute(old_code, attribute_name))
    new_education = float(get_attribute(new_code, attribute_name))
    result_education = new_education - old_education
    analysis_education = "↗ Find more skilled fellows" if result_education > 0 else "↘ Less competitions"

    # for x in old_dict.keys():
    #    table.append(four_row_list(x, old_dict[x], new_dict[x], ""))

    # Line 4
    # url = "https://avoindata.prh.fi/bis/v1?totalResults=true&maxResults=1&resultsFrom=10000" + \
    #       "&streetAddressPostCode={:s}&companyRegistrationFrom=1950-01-01"
    # print("This part takes time (~10s). Comment this part to accelerate. \n(From line 100, reference_function.py)")
    # old_company_num = eval(requests.get(url.format(old_code)).text.split(',"previous')[0] + '}')['totalResults']
    # new_company_num = eval(requests.get(url.format(new_code)).text.split(',"previous')[0] + '}')['totalResults']
    # result_company_num = int(new_company_num) - int(old_company_num)
    # analysis_company_num = "↗ Big town with more opportunities" if result_company_num > 0 else "↘ Peaceful life"
    return html.Table(
        [
            html.Thead(
                html.Tr([
                    html.Th(),
                    html.Th("Current Location"),
                    html.Th("New Location"),
                    html.Th("Significance")
                ])),
            html.Tbody([
                html.Tr([
                    html.Td("Income"),
                    html.Td(old_income),
                    html.Td(new_income),
                    html.Td(analysis_income)
                ]),
                html.Tr([
                    html.Td("Education index"),
                    html.Td(f"{old_education:.2%}"),
                    html.Td(f"{new_education:.2%}"),
                    html.Td(analysis_education)
                ]),
                # html.Tr([html.Td("Number of companies"), html.Td(old_company_num),
                #         html.Td(new_company_num), html.Td(analysis_company_num)])
            ])
        ],
        id="insight_table")
コード例 #7
0
def generate_table(dataframe, max_rows=10):
    return html.Table([
        html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
        html.Tbody([
            html.Tr(
                [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(min(len(dataframe), max_rows))
        ]),
    ])
コード例 #8
0
def get_about_html():
    text = """
           This is the implementation of our Data Science Project. The aim of this project is to provide 
           suggestions on suitable relocation areas in Finland, based on housing prices and demographics.
           """
    return html.Div([
        html.H1("About"),
        html.H3(text, id="about_text"),
        html.H1("Team"),
        html.Table([
            html.Thead(
                html.Tr([
                    html.Th("Letizia"),
                    html.Th("Taige"),
                    html.Th("Roope"),
                    html.Th("Trang"),
                    html.Th("Thong")
                ])),
            html.Tbody(
                html.Tr([
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars1.githubusercontent.com/u/45148109?s=200&v=4",
                            alt="Letizia"),
                               href="https://github.com/letiziaia")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars2.githubusercontent.com/u/16875716?s=200&v=4",
                            alt="Taige"),
                               href="https://github.com/xiaoxiaobt")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars2.githubusercontent.com/u/43811718?s=200&v=4",
                            alt="Roope"),
                               href="https://github.com/rooperuu")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars3.githubusercontent.com/u/55182434?s=200&v=4",
                            alt="Trang"),
                               href="https://github.com/trangmng")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars0.githubusercontent.com/u/32213097?s=200&v=4",
                            alt="Thong"),
                               href="https://github.com/trananhthong"))
                ]))
        ],
                   id="team_table")
    ],
                    id="about_info")
コード例 #9
0
def df_to_table(df):
    """Transforms a dataFrame into an html table for Dash
    """
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in df.columns])] +

        # Body
        [
            html.Tr([html.Td(df.iloc[i][col]) for col in df.columns])
            for i in range(len(df))
        ])
コード例 #10
0
def generate_table(dataframe, max_rows=10):
    """
    This is a helper function which generates a Dash HTML table
    from a pandas dataframe
    """
    return html.Table([
        html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
        html.Tbody([
            html.Tr(
                [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(min(len(dataframe), max_rows))
        ])
    ])
コード例 #11
0
def generate_table(dataframe, max_rows=50):
    return html.Table(
        # Header
        [
            html.Tr([html.Th(dataframe.index.name)] +
                    [html.Th(col) for col in dataframe.columns])
        ] +

        # Body
        [
            html.Tr([html.Td(dataframe.index[i])] + [
                html.Td('{:,.0f}'.format(dataframe.iloc[i][col]))
                for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
コード例 #12
0
def generate_table(dataframe: List[output_column]) -> html.Table:
    return html.Table(
        # Header
        [
            html.Tr([
                html.Th(col["name"], style={"textAlign": "center"})
                for col in dataframe
            ])
        ] +
        # Body
        [
            html.
            Tr([col_align(col["values"][i], col["name"]) for col in dataframe])
            for i in range(len(ROWS))
        ])
コード例 #13
0
ファイル: layouts.py プロジェクト: munrojm/crystaltoolkit
def get_data_list(data: Dict[str, str]):
    """
    Show a formatted table of data items.
    :param data: dictionary of label, value pairs
    :return: html.Div
    """
    contents = []
    for title, value in data.items():
        if isinstance(title, str):
            title = Label(title)
        contents.append(
            html.Tr([
                html.Td(title, style={"vertical-align": "middle"}),
                html.Td(value, style={"vertical-align": "middle"}),
            ]))
    return html.Table([html.Tbody(contents)], className="table")
コード例 #14
0
ファイル: test_derived_props.py プロジェクト: plotly/dash
 def show_props(*args):
     # return 'Something yet!'
     # print('show props')
     return html.Table(
         [
             html.Tr(
                 [
                     html.Td(prop),
                     html.Td(
                         json.dumps(val) if val is not None else "None", id=prop
                     ),
                 ]
             )
             for prop, val in zip(props, args)
         ]
     )
コード例 #15
0
    def update_calibration(self, n):
        header = html.Tr(children=[
            html.Th("Frequency (MHz)"),
            html.Th("Max (dBW)"),
        ],
                         style={"text-align": "left"})

        settings_row = html.Tr(children=[
            html.Td("[current settings]"),
            html.Td(""),
        ])

        for device, calibration in zip(self.device, self.calibration):
            header.children.append(html.Th(f"SDR {device} (dB)"))
            settings_row.children.append(html.Td(f"{calibration:.2f}"))

        table = html.Table(children=[header, settings_row],
                           style={
                               "width": "100%",
                               "text-align": "left"
                           })

        for freq, avgs in sorted(self.calibrations.items(),
                                 key=lambda item: max(item[1])):
            ordered_avgs = [
                avgs[d] + old if d in avgs else float("-inf")
                for d, old in zip(self.device, self.calibration)
            ]
            freq_max = max(ordered_avgs)

            row = html.Tr(children=[
                html.Td(f"{freq/1000/1000:.3f}"),
                html.Td(f"{freq_max:.2f}")
            ])
            for avg in ordered_avgs:
                row.children.append(html.Td(f"{avg - freq_max:.2f}"))

            table.children.append(row)

        return html.Div([
            html.H2("Calibration Table"),
            table,
        ],
                        style={"break-inside": "avoid-column"})
コード例 #16
0
from dash import dcc
from dash import html
from dash.dependencies import Input, Output

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

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

app.layout = html.Div([
    dcc.Input(id="num-multi", type="number", value=5),
    html.Table([
        html.Tr([html.Td(["x", html.Sup(2)]),
                 html.Td(id="square")]),
        html.Tr([html.Td(["x", html.Sup(3)]),
                 html.Td(id="cube")]),
        html.Tr([html.Td([2, html.Sup("x")]),
                 html.Td(id="twos")]),
        html.Tr([html.Td([3, html.Sup("x")]),
                 html.Td(id="threes")]),
        html.Tr([html.Td(["x", html.Sup("x")]),
                 html.Td(id="x^x")]),
    ]),
])


@app.callback(
    Output("square", "children"),
    Output("cube", "children"),
    Output("twos", "children"),
    Output("threes", "children"),
    Output("x^x", "children"),
    Input("num-multi", "value"),
コード例 #17
0
ファイル: custom.py プロジェクト: mwvgroup/Egon
    def __init__(self, pipeline) -> None:
        inputs, outputs = pipeline.connectors
        number_inputs = len(inputs)
        number_outputs = len(outputs)
        total_connectors = number_inputs + number_outputs

        sources, nodes, targets = pipeline.nodes
        num_sources = len(sources)
        num_nodes = len(nodes)
        num_targets = len(targets)
        number_nodes = num_sources + num_nodes + num_targets

        super().__init__(
            className='div-info-table',
            children=[
                dhtml.Table(
                    className='table-info-primary',
                    children=[
                        dhtml.Tr(children=[
                            dhtml.Td(children=[f'Total Nodes: {number_nodes}'])
                        ]),
                        dhtml.Tr(children=[
                            dhtml.Td(children=[
                                dhtml.Table(
                                    className='table-info-secondary',
                                    children=[
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Source:']),
                                            dhtml.Td(
                                                children=[f'{num_sources}'])
                                        ]),
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Inline:']),
                                            dhtml.Td(children=[f'{num_nodes}'])
                                        ]),
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Target:']),
                                            dhtml.Td(
                                                children=[f'{num_targets}'])
                                        ])
                                    ])
                            ])
                        ]),
                        dhtml.Tr(children=[
                            dhtml.Td(children=[
                                f'Total Connectors: {total_connectors}'
                            ])
                        ]),
                        dhtml.Tr(children=[
                            dhtml.Td(children=[
                                dhtml.Table(
                                    className='table-info-secondary',
                                    children=[
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Input:']),
                                            dhtml.Td(
                                                children=[f'{number_inputs}'])
                                        ]),
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Output:']),
                                            dhtml.Td(
                                                children=[f'{number_outputs}'])
                                        ])
                                    ])
                            ])
                        ])
                    ])
            ])
コード例 #18
0
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

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

app.layout = html.Div([
    dcc.Input(
        id='num-multi',
        type='number',
        value=5
    ),
    html.Table([
        html.Tr([html.Td(['x', html.Sup(2)]), html.Td(id='square')]),
        html.Tr([html.Td(['x', html.Sup(3)]), html.Td(id='cube')]),
        html.Tr([html.Td([2, html.Sup('x')]), html.Td(id='twos')]),
        html.Tr([html.Td([3, html.Sup('x')]), html.Td(id='threes')]),
        html.Tr([html.Td(['x', html.Sup('x')]), html.Td(id='x^x')]),
    ]),
])


@app.callback(
    Output('square', 'children'),
    Output('cube', 'children'),
    Output('twos', 'children'),
    Output('threes', 'children'),
    Output('x^x', 'children'),
    Input('num-multi', 'value'))
def callback_a(x):
    if not x:
コード例 #19
0
            ),
            # ECDF-plot & summary statistics table
            html.Div(
                className="ecdf-and-stats",
                children=[
                    # ECDF plot
                    dcc.Loading(
                        color="cyan",
                        children=[
                            dcc.Graph(id="ecdf-plot", config=plot_config)
                        ],
                    ),
                    # Summary statistics table
                    html.Div(
                        className="stats-table",
                        children=[html.Table(id="summary-stats")],
                    ),
                    dcc.Store(id="sample-store"),
                    # Sample download button
                    html.Button(
                        "Download sample",
                        id="sample-download-button",
                        className="custom-button",
                    ),
                    dcc.Download(id="download-sample"),
                ],
            ),
        ],
    ),
])
コード例 #20
0
ファイル: about.py プロジェクト: tquiviger/market-monitor
 html.Table([
     html.Thead([
         html.Tr([
             html.Th('Dataset'),
             html.Th('Source'),
             html.Th('Type'),
             html.Th('Files'),
             html.Th('Last Update')
         ])
     ]),
     html.Tbody([
         html.Tr([
             html.Td('Joint Malnutrition Estimate (UNICEF, WB, WHO)'),
             html.Td(
                 html.A('Humanitarian Data Exchange',
                        href='https://data.humdata.org/',
                        target='_blank')),
             html.Td('CSV File'),
             html.Td(
                 html.A(
                     'https://data.humdata.org/dataset/'
                     'child-malnutrition-joint-country-dataset-unicef-who-world-bank-group-2017',
                     href='https://data.humdata.org/dataset/'
                     'child-malnutrition-joint-country-dataset-unicef-who-world-bank-group-2017',
                     target='_blank')),
             html.Td(hdx_connect.get_jme_dataset().get_date_of_dataset()
                     ['startdate'])
         ]),
         html.Tr([
             html.Td('Relief Web Data'),
             html.Td(
                 html.A('Humanitarian Data Exchange',
                        href='https://data.humdata.org/',
                        target='_blank')),
             html.Td('CSV File'),
             html.Td(
                 html.A(
                     'https://data.humdata.org/dataset/'
                     'reliefweb-crisis-app-data',
                     href='https://data.humdata.org/dataset/'
                     'reliefweb-crisis-app-data',
                     target='_blank')),
             html.Td(hdx_connect.get_reliefweb_dataset().
                     get_date_of_dataset()['startdate'])
         ]),
         html.Tr([
             html.Td('Relief Web Reports'),
             html.Td(
                 html.A('Relief Web API',
                        href='https://reliefweb.int/help/api',
                        target='_blank')),
             html.Td('API'),
             html.Td('N/A'),
             html.Td(datetime.datetime.now().strftime("%Y-%m-%d"))
         ]),
         html.Tr([
             html.Td('Fundings'),
             html.Td(
                 html.A(
                     'FTS',
                     href='https://fts.unocha.org/content/fts-public-api',
                     target='_blank')),
             html.Td('API'),
             html.Td('N/A'),
             html.Td(datetime.datetime.now().strftime("%Y-%m-%d"))
         ]),
         html.Tr([
             html.Td('WFP Tender Awards'),
             html.Td(
                 html.
                 A('WFP Tender Awards',
                   href='https://www.wfp.org/procurement/food-tender-awards',
                   target='_blank')),
             html.Td('Webpage'),
             html.Td('N/A'),
             html.Td('Unknown')
         ])
     ])
 ],
            style={'font-size': 'small'}),
コード例 #21
0
ファイル: webapp.py プロジェクト: MSLNZ/pr-omega-logger
def update_plot_viewer(tab, dropdown, start, end):
    if tab == 'current-readings' or not start or not end:
        return []

    plots = []
    labels = dropdown or [
    ]  # dropdown values could be None, but we still need an iterable
    start_date = fromisoformat(start)
    end_date = fromisoformat(end)
    y_range = [sys.maxsize, -sys.maxsize]
    table = HTMLTable()
    for label in labels:
        # find the latest CalibrationReport
        report = find_report(calibrations[label])

        # fetch the data
        data, message = read_database(report,
                                      tab,
                                      start=start_date,
                                      end=end_date,
                                      label=label)

        # apply the calibration equation
        if tab != 'dewpoint':
            data = apply_calibration(data, report)

        # add the data to the HTML table
        table.append(data, report, label)

        # if there is no data for the specified date range then calling
        # np.min or np.max will raise the following exception
        #   ValueError: zero-size array to reduction operation minimum which has no identity
        if data[tab].size > 0:
            y_range = [
                min(np.min(data[tab]), y_range[0]),
                max(np.max(data[tab]), y_range[1])
            ]

        plots.append(
            go.Scatter(
                x=data['datetime'],
                y=data[tab],
                name=label,  # the name displayed in the legend
            ))

    # want the y_range values to be nice numbers like 20.1 not 20.0913136
    if y_range[0] == sys.maxsize:
        y_range = [0, 1]
    else:
        factor = 10.
        y_range = [
            floor(y_range[0] * factor) / factor,
            ceil(y_range[1] * factor) / factor
        ]

    return [
        html.A(
            id='download-link',
            children='Download',
            download='omega-logger-data.csv',
            href='/download',
            target='_blank',
            title='Download the data in the plot as a CSV file',
        ),
        dcc.Graph(
            id='plot',
            figure={
                'data':
                plots,
                'layout':
                go.Layout(
                    title=tab.title(),
                    xaxis={
                        'title': 'Timestamp',
                        'type': 'date'
                    },
                    yaxis={
                        'title':
                        tab.title() +
                        (' [%]' if tab == 'humidity' else ' [°C]'),
                        'range':
                        y_range,
                    },
                    hovermode='closest',
                    legend=dict(orientation='v', x=1, y=1),
                    # height=500,
                    margin=go.layout.Margin(autoexpand=True,
                                            l=75,
                                            r=0,
                                            b=75,
                                            t=50,
                                            pad=10)),
            }),
        html.Table(
            className='summary-table',
            children=table.get(),
            style=dict(width='100%',
                       border='2px solid black',
                       textAlign='center'),
        ),
    ]
コード例 #22
0
                 html.Span('', id=id + "_weight_label")])
    ],
                   id=id + "_tr")


controls_dict = collections.OrderedDict()
for k, v in list(variables.items()):
    controls = get_controls(k, v['label'], v['range'])
    controls_dict[k] = controls

head_row = html.Tr([
    html.Th('Variable'),
    html.Th('Range'),
    html.Th('Importance'),
])
controls_html = html.Table([head_row] + list(controls_dict.values()),
                           id='controls')
label_states = [
    dash.dependencies.State(k + "_label", 'value') for k in var_ids
]
low_states = [dash.dependencies.State(k + "_low", 'value') for k in var_ids]
high_states = [dash.dependencies.State(k + "_high", 'value') for k in var_ids]
weight_states = [
    dash.dependencies.State(k + "_weight", 'value') for k in var_ids
]

inp_nvars = html.Tr([
    html.Td('Number of variables: '),
    html.Td(
        dcc.Input(id='inp_nvars',
                  type='number',
                  value=NVARS_DEFAULT,