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'})
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")
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")
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)) ])
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'})
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
def create_and_plot_sample(distribution: str, size: int, *parameters) -> tuple: """Create a sample of the specified distribution using the provided parameters, then plot a histogram & violin-plot, and compute descriptive statistics. Parameters ---------- distribution : str The name of the currently selected distribution size : int The set sample size *parameters : int, float 1 or 2 parameter values, depending on the distribution Returns ------- tuple A histogram, a violin_plot, an ecdf-plot, a table of summary statistics, the currently specified parameters and a csv file with the sample data for download. """ sample = process_random_sample(distribution, size, parameters) histogram = plotting.plot_histogram(sample["data"], distribution) violin_plot = plotting.plot_violin(sample["data"], distribution) ecdf_plot = plotting.plot_ecdf(sample["data"], distribution) summary_statistics = sample["summary_statistics"] summary_statistics_table = [html.Th("Summary Statistics")] + [ html.Tr([html.Td(f"{name}:"), html.Td(value)]) for name, value in summary_statistics.items() ] parameters = sample["parameters"] param_dict = { distribution_data[distribution].get(f"param{idx}"): value for idx, value in enumerate(parameters, start=1) } param_dict["Sample Size"] = size parameter_info = [ html.H3("Parameters: "), html.P([ ", ".join([f"{key}: {value}" for key, value in param_dict.items()]) ]), ] sample_csv_download = { "content": sample["data"].to_csv(index=False), "filename": f"{distribution}-sample.csv", "type": "text/csv", } return ( histogram, violin_plot, ecdf_plot, summary_statistics_table, parameter_info, sample_csv_download, )
def __init__(self): """Create the HTML table for the webapp.""" self._table = [ html.Tr([ html.Th('OMEGA logger'), html.Th('Report No.'), html.Th('Description'), html.Th('Average'), html.Th('Stdev'), html.Th('Median'), html.Th('Max'), html.Th('Min'), html.Th('# Points')] )]
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)) ]) ])
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)) ]), ])
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"})
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)) ])
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)) ]) ])
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)) ])
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")
import dash_bootstrap_components as dbc from dash import html from .util import make_subheading table_header = html.Thead( html.Tr([ html.Th("#"), html.Th("First name"), html.Th("Last name"), ])) table_body = html.Tbody([ html.Tr([ html.Th("1", scope="row"), html.Td("Tom"), html.Td("Cruise"), ]), html.Tr([ html.Th("2", scope="row"), html.Td("Jodie"), html.Td("Foster"), ]), html.Tr([ html.Th("3", scope="row"), html.Td("Chadwick"), html.Td("Boseman"), ]), ]) table = html.Div(
import dash_bootstrap_components as dbc from dash import html table_header = [ html.Thead(html.Tr([html.Th("First Name"), html.Th("Last Name")])) ] row1 = html.Tr([html.Td("Arthur"), html.Td("Dent")]) row2 = html.Tr([html.Td("Ford"), html.Td("Prefect")]) row3 = html.Tr([html.Td("Zaphod"), html.Td("Beeblebrox")]) row4 = html.Tr([html.Td("Trillian"), html.Td("Astra")]) table_body = [html.Tbody([row1, row2, row3, row4])] table = dbc.Table(table_header + table_body, bordered=True)
return html.Tr([ html.Td(label), html.Td([range_low, html.Span('to'), range_high]), html.Td([html.Span(slider), 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([
def _generate_table_from_df(cls, df, float_format=None, columns=None, header=True, index=False, index_label=None, date_format=None, **table_kwargs): """ Generate a Table component from a dataframe. Parameters ---------- df : pandas.DataFrame DataFrame to render as a table. float_format : str, optional Format to use for floating point numbers. columns : sequence, optional Columns to render. header : boolean or list(str) or dict(str: str), optional Write out the column names. If a list of strings is given it is assumed to be aliases for the columns names (and hence must be the same length as df.columns). A dict can be passed to rename some columns, the format is {'<current_name>': '<new_name>'}. The dictionary need not have an entry for every column. index : boolean, optional Render the row names (index). index_label : str, optional Column label for index column if desired. If None is passed, but both header and index are True, then the index name is used. date_format : str, optional Format string for datetime objects. **table_kwargs : Keyword arguments Additional arguments to pass to the table component. See dash_bootstrap_components.Table for details. """ import numpy as np import pandas as pd if columns is not None: df = df.loc[:, columns] if float_format is not None: for c in df.select_dtypes(["float"]).columns: df[c] = df[c].map(lambda x: "{1:{0}}".format(float_format, x)) if date_format is not None: for c in df.select_dtypes(["datetime"]).columns: df[c] = df[c].map(lambda x: x.strftime(date_format)) if index: df = df.reset_index() if index_label is not None: df = df.rename(columns={"index": index_label}) if header: if isinstance(header, (tuple, list, np.ndarray, pd.Index)): try: df.columns = header except ValueError: raise ValueError( "If specifying column names with a sequence, the number " "of names must exactly match the number of columns.") elif isinstance(header, dict): df = df.rename(columns=header) # Get the actual headers n_levels = df.columns.nlevels header_values = [ list(df.columns.get_level_values(level)) for level in range(n_levels) ] # The sizes of consecutive header groups at each level header_spans = [[ len(list(group)) for _, group in groupby(level_values) ] for level_values in header_values] # The positions of header changes for each level as an integer header_breaks = [[ sum(level_spans[:i]) for i in range(1, len(level_spans) + 1) ] for level_spans in header_spans] # Include breaks from higher levels header_breaks = [ sorted(set(reduce(add, header_breaks[:level])).union({0})) for level in range(1, n_levels + 1) ] # Go from header break positions back to cell spans header_spans = [ reversed([ level_breaks[i] - level_breaks[i - 1] for i in range(len(level_breaks) - 1, 0, -1) ]) for level_breaks in header_breaks ] table = [ html.Thead([ html.Tr(children=[ html.Th( header_values[level][pos], colSpan=span, ) for pos, span in zip(header_breaks[level], header_spans[level]) ]) for level in range(n_levels) ]) ] else: table = [] table.append( html.Tbody([ html.Tr([html.Td(df.iloc[i, j]) for j in range(len(df.columns))]) for i in range(len(df)) ])) return cls(table, **table_kwargs)
# -*- coding: utf-8 -*- import datetime from dash import html from datasources import hdx_connect layout = html.Div(children=[ html.H3('Data Sources'), 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',
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)