html.Div(id='dummy') ], style={ "text-align" : "center" , "width" : "100%" , "columcount":2} ), html.H4("Must Watch :",style={"text-align":"center"}), html.Table( [ html.Thead( html.Tr( [ html.Th("Recommended"), ] ) ), html.Tbody( [ html.Th("1-"), html.Th("2-"), html.Th("3-"), html.Th("4-"), html.Th("5-"), ], id="rec-table" ) ], style={"width": "100%"}
def generate_table(dataframe, max_rows=10): return html.Table( [html.Tr([html.Th(col, style={'overflow':'hidden'}) for col in dataframe.columns])]+ [html.Tr([ html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows))] )
html.Table( style={'width': '100%'}, # Begin of Table children children=[ ####################################################################### # Begin of First Tr html.Tr( #Begin Tr children children=[ # Begin Th html.Th( style={'width': '30%'}, # Begin Th children children=[ html. H3('Cereals to consider for purchase based on rating level ' ) # End of Th children ] # End of Th - Notice a comma is placed here to separate the next Th ), # Begin of Th html.Th( style={'width': '70%'}, # Begin of Th children children=[ html.H3('All Details of Cereals') # End of Th children ] # End of Th
'border-style':'solid', 'border-width':2, 'border-color':'rgb(120,120,120)'}), html.Div( dcc.Graph(id='outcome-curves'), style={'display':'inline-block', 'border-style':'solid', 'border-width':2, 'border-color':'rgb(120,120,120)'}), html.Div(id='table-container',children= [ html.Table( [ html.Thead([ html.Tr(html.Th('Parameters',colSpan=2,style={'font-size':13, 'background-color':'rgb(220,220,220)', 'textAlign':'center', 'padding':5})) ], style={'height':'20px'}), html.Colgroup([ html.Col(style={'backgroundColor':'rgb(220,220,220)','width':100}), html.Col(style={'width':100}) ]), html.Tbody([ html.Tr([html.Th('RSI',style=th_style), html.Td(id='rsi-output',style=td_style)]), html.Tr([html.Th('Dose',style=th_style), html.Td(id='dose-output',style=td_style)]), html.Tr([html.Th('RxRSI',style=th_style),html.Td(id='rxdose-output',style=td_style)]), html.Tr([html.Th('GARD (Tx)',style=th_style),html.Td(id='gard-output',style=td_style)]), html.Tr(html.Th('Normal Tissue Doses',style={'textAlign':'center','fontSize':13,'padding':5},colSpan=2)), html.Tr([html.Th('Heart',style=th_style), html.Td(id='heart-dose-output',style=td_style)]),
def callback(model, method, dmord, nu, coords, x0, x1, go, tab): print(f"{tab}") # Setup some error handling coord_error = False freq_error = False dmord_error = False try: nu = float(nu) except ValueError: nu = 1.0 freq_error = True if method == "DM (pc/cm3) to Distance": f = pygedm.dm_to_dist units = 1.0 * u.pc / (u.cm**3) try: dmord = float(dmord) * units except ValueError: dmord = 10 * units dmord_error = True xt = 'DM (pc / cm3)' yt = 'Distance (kpc)' xl = 'Dispersion measure' yl = 'Distance' else: f = pygedm.dist_to_dm units = 1.0 * u.kpc try: dmord = float(dmord) * units except ValueError: dmord = 10 * units dmord_error = True #print(f, dmord) yt = 'DM (pc / cm3)' xt = 'Distance (kpc)' xl = 'Distance' yl = 'Dispersion measure' if coords == "Galactic (gl, gb)": try: gl = Angle(x0, unit='degree') gb = Angle(x1, unit='degree') sc = SkyCoord(gl, gb, frame='galactic') except ValueError: sc = SkyCoord(0 * u.deg, 0 * u.deg, frame='galactic') coord_error = True else: try: ra = Angle(x0, unit='hourangle') dec = Angle(x1, unit='degree') sc = SkyCoord(ra, dec) except: sc = SkyCoord(0 * u.deg, 0 * u.deg, frame='galactic') coord_error = True print(sc.galactic.l, sc.galactic.b, dmord, f) dout = f(sc.galactic.l, sc.galactic.b, dmord, method=model, nu=nu) dout_ne = f(sc.galactic.l, sc.galactic.b, dmord, method='ne2001', nu=nu) dout_ymw = f(sc.galactic.l, sc.galactic.b, dmord, method='ymw16', nu=nu) # Make plots D = np.linspace(0.1, dmord.value) y_ne21 = np.zeros_like(D) y_ymw = np.zeros_like(D) for ii, d in enumerate(D): d_ne21 = f(sc.galactic.l, sc.galactic.b, d * units, method='ne2001', nu=nu) d_ymw = f(sc.galactic.l, sc.galactic.b, d * units, method='ymw16', nu=nu) if method == "DM (pc/cm3) to Distance": y_ne21[ii] = d_ne21[0].to('kpc').value y_ymw[ii] = d_ymw[0].to('kpc').value else: y_ne21[ii] = d_ne21[0].value y_ymw[ii] = d_ymw[0].value #print(d, y) fig = pgo.Figure() fig.add_trace(pgo.Scatter(x=D, y=y_ne21, mode='lines', name='NE2001')) fig.add_trace(pgo.Scatter(x=D, y=y_ymw, mode='lines', name='YMW16')) fig.update_layout( xaxis_title=xt, yaxis_title=yt, title= f'ICRS: {sc.icrs.ra:2.2f} {sc.icrs.dec:2.2f} \t Galactic: {sc.galactic.l:2.2f} {sc.galactic.b:2.2f}' ) # SKYMAP if model == 'NE2001': skymap_data = skymap_data_ne else: skymap_data = skymap_data_ymw print(skymap_data.shape) skymap = px.imshow(animation_frame=0, img=skymap_data, origin='upper') skymap["layout"].pop("updatemenus") skymap.update_layout(xaxis_title='Galactic longitude (deg)', yaxis_title='Galactic latitude (Deg)', title=f'{model}: All-sky DM map') l_wrapped = sc.galactic.l.wrap_at(Angle(180, unit='deg')).value skymap.add_shape(type='rect', x0=l_wrapped - 2, x1=l_wrapped + 2, y0=sc.galactic.b.value - 2, y1=sc.galactic.b.value + 2, xref='x', yref='y', line_color='cyan') ## TEXT OUTPUT hdr = [html.H2(method), html.H4(f"Sky coordinates: {sc}")] if coord_error: hdr.append( dbc.Alert('Input coordinates invalid, please check', color='danger')) if freq_error: hdr.append( dbc.Alert('Could not parse frequency input, please check.', color='danger')) if dmord_error: hdr.append( dbc.Alert('Could not parse DM/distance input, please check.', color='danger')) hdr = html.Div(hdr) table_header = [ html.Thead(html.Tr([html.Th(""), html.Th("YMW16"), html.Th("NE2001")])) ] row1 = html.Tr( [html.Th(f"{xl}"), html.Td(f"{dmord}"), html.Td(f"{dmord}")]) row2 = html.Tr([ html.Th(f"{yl}"), html.Td(f"{dout_ymw[0]:2.4f}"), html.Td(f"{dout_ne[0]:2.4f}") ]) row3 = html.Tr([ html.Th(f"Scattering timescale @ {nu} GHz"), html.Td(f"{dout_ymw[1]:2.4e}"), html.Td(f"{dout_ne[1]:2.4e}") ]) table_body = [html.Tbody([row1, row2, row3])] gedm_out = html.Div( [hdr, dbc.Table(table_header + table_body, bordered=True)]) notes = html.Div([ html.H2("PyGEDM"), html.P(f"Version: {pygedm.__version__}"), html.P(["Authors: Danny C. Price, Chris Flynn, Adam Deller"]), html.P([ "PyGEDM Documentation: ", html.A("https://pygedm.readthedocs.io", href='https://pygedm.readthedocs.io') ]), html.P([ "Github: ", html.A("https://github.com/FRBs/pygedm", href='https://github.com/FRBs/pygedm') ]), html.P([ "Journal article: A comparison of Galactic electron density models using PyGEDM ", html. A("ADS", href= 'https://ui.adsabs.harvard.edu/abs/2021arXiv210615816P/abstract' ), " | ", html.A("arXiv", href='https://arxiv.org/abs/2106.15816') ]), html.H4("NE2001"), html.P("Cordes, J. M., & Lazio, T. J. W. (2002),"), html. P("NE2001.I. A New Model for the Galactic Distribution of Free Electrons and its Fluctuations, arXiv e-prints, astro-ph/0207156." ), html.H4("YMW16"), html.P("Yao, J. M., Manchester, R. N., & Wang, N. (2017),"), html. P("A New Electron-density Model for Estimation of Pulsar and FRB Distances, ApJ, Volume 888, Issue 2, id.105, Colume 835, id.29" ), html.P([ "Web app hosted by ", html.A("Data Central", href='https://datacentral.org.au/') ]), ]) return fig, gedm_out, skymap, notes
]), html.Div( className='col-6', children=[ html.Div( className='card', children=[ html.Div( className='table-responsive', children=[ html.Table( className= 'table table-hover table-outline table-vcenter card-table', children=[ html.Tr([ html.Th(x) for x in [ 'Name', 'Status', 'Manager', 'Status Text' ] ]) ] + [ html.Tr([ html.Td(x['Name']), html.Td( indicate( x['TrackStatus'] ['Name'])), html.Td(x[
def generate_prop_table(component_name, component_names, library_name): '''Generate a prop table for each component (both React and Python). :param (str) component_name: The name of the component as it is defined within the package. :param (dict[list]) component_names: A dictionary defining which components are React components, and which are Python components. The keys in the dictionary are 'react' and 'python', and the values for each are lists containing the names of the components that belong to each category. :param (str) library_name: The name of the library. :rtype (object): An html.Table containing data on the props of the component. ''' regex = { 'python': r'^\s*([a-zA-Z_]*)\s*\(([a-zA-Z\/]*);\s*([a-z]*)\):\s*(.*?)\s*(\(Default:\s*(.*)\)|)\s*$' } component_type = 'react' \ if component_name in component_names['react'] else 'python' tableRows = [ html.Tr([ html.Th('Attribute'), html.Th('Description'), html.Th('Type'), html.Th('Default value') ]) ] exec("import {}".format(library_name)) if component_type == 'python': sep = '\n-' doc = eval("{}.{}".format(library_name, component_name)).__doc__ props = doc.split(sep) elif component_type == 'react': path = os.path.join( os.path.dirname(os.path.abspath(eval(library_name).__file__)), 'metadata.json') with open(path, 'r') as f: metadata = json.load(f) # Mol3d for some reason is a plain JS file, not a react file cname = '{}.react.js'.format(component_name) if component_name == 'Molecule3dViewer': cname = 'Molecule3dViewer.js' elif component_name == 'Molecule2dViewer': cname = 'Molecule2dViewer.react.js' docs = metadata['src/lib/components/{}'.format(cname)] props = docs['props'] for prop in props: if component_type == 'python': desc_sections = prop.split('\n\n') partone = desc_sections[0].replace(' ', ' ') r = re.match(re.compile(regex[component_type]), partone.replace('\n', ' ')) if r is None: continue (prop_name, prop_type, prop_optional, prop_desc, _, prop_default) = r.groups() if prop_default is None: prop_default = '' if 'optional' in prop_optional: prop_optional = '' if len(desc_sections) > 1: prop_desc += ' ' prop_desc += desc_sections[1] elif component_type == 'react': prop_name = prop prop_desc = props[prop]['description'] prop_type = js_to_py_type(props[prop]['type']) if 'defaultValue' in props[prop].keys(): prop_default = props[prop]['defaultValue']['value'] else: prop_default = '' tableRows.append( html.Tr([ html.Td(rc.Markdown(prop_name)), html.Td(rc.Markdown(prop_desc)), html.Td(rc.Markdown(prop_type)), html.Td(rc.Markdown('```python \n' + prop_default + '\n```')) ])) return html.Div([ html.H3("{} Properties".format(component_name)), html.Table(tableRows) ])
def display_tab_content(value): if value == 0: #Introduction page with markdown text return html.Div([html.Div(dcc.Markdown(dedent(''' ### Welcome! ##### This dashboard containins the data of {} properties in Amsterdam. ##### Data is scraped from [Pararius.nl](https://www.pararius.nl) using a slow scraper ##### which you can find at [my Github]() ##### Use the Tabs to the left to navigate to different properties, ##### you can use the submenus to pick out different options. ##### Currently you can find: * A property price map with interactive slider and hover functions * a housing price predictor *(under construction)* * Some data visualization *(under construction)* * A table with the raw data ##### Hope you enjoy it! '''.format(len(data_frame))) ), style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'} ) ]) if value == 3: #prediction tab, sadly the predictor itself does not work yet... return html.Div([ html.Div(#Dropdown menu at the top dcc.Dropdown(id = 'prediction-menu', options = [ {'label': 'Total Surface (m2)', 'value': 'space'}, {'label': 'Total volume (m3)', 'value': 'volume'}, {'label': 'Number of rooms', 'value': 'rooms'}, #{'label': 'Neighbourhood', 'value': 'nh'}, {'label': 'property type', 'value': 'type'}, ], multi = True, value = 1 )), #Slider 1 html.Div(id = 'dynamic-prediction-input-surface', style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), #Slider 2 html.Div(id = 'dynamic-prediction-input-volume', style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), #Slider 3 html.Div(id = 'dynamic-prediction-input-rooms', style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), #OPtion selector for house type html.Div(id = 'dynamic-prediction-input-type', style ={'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), #Button to fire callback html.Button('Submit', id='button', ), #outpur html.Div(id = 'price-prediction-output', children = "select values and press submit", ) ]) #Display the price map elif value == 1: return html.Div([ html.H1('Property price map', style = {'width': '100%', 'textAlign': 'center' }), html.Div(id='text-content', style={'width': '70%', 'textAlign': 'center'} ), html.Div(id='property-details', style={'width': '30%', 'float': 'right', 'margin-left': '10px'}), #this contains the map html.Div(id = 'map-container', style={'width': '70%'} ), html.H4('Select Price range', style = {'width': '70%', 'textAlign': 'center' }), #Price slider html.Div( dcc.RangeSlider(id = 'pricerange-map', min = min(data_frame.Price), max = max(data_frame.Price), value = [min(data_frame.Price), max(data_frame.Price)], ), style = {'width': '70%'}), html.Div(id = 'pricerange-text', style = {'width': '70%', 'textAlign': 'center'}) ]), #this is not there elif value == 2: return html.Div([html.H4('Predict the price of your desired property!'), html.Div(id = 'Predictor-tab') ]) #Data viz tab, both plots are not working yet... elif value == 4: return html.Div([ html.H3('Data vizualization tab, choose option below', ), dcc.Dropdown(id = 'data-viz-menu', options = [ {'label': 'average price map', 'value': 1}, {'label': 'graphs', 'value' :2}, {'label': 'add something', 'value':3} ]), html.Div(id = 'data-viz-content', ) ]) #Raw data table, might change this into an interactive one elif value == 5: return html.Div([html.Table( [html.Tr([html.Th(col) for col in data_frame.columns])] + [html.Tr([ html.Td(data_frame.iloc[i][col]) for col in data_frame.columns ]) for i in range(min(len(data_frame), len(data_frame)))]) ])
def createTierMappingMenus(eafFilename): print("=== createTierMappingMenus: %s [exists: %s]" % (eafFilename, os.path.exists(eafFilename))) dropDownMenus = html.H5("☠️ failure in extracting tierIDs from %s" % eafFilename) if (os.path.exists(eafFilename)): tmpDoc = etree.parse(eafFilename) userProvidedTierNamesToAssignToStandardTiers = [ tier.attrib["TIER_ID"] for tier in tmpDoc.findall("TIER") ] print(userProvidedTierNamesToAssignToStandardTiers) tierChoices = userProvidedTierNamesToAssignToStandardTiers dropDownMenus = html.Table( id="tierMappingMenus", children=[ html.Tr([ html.Th("Standard interlinear tiers", className="first"), html.Th("(e.g., from Totonac)", className="second"), html.Th("Select ELAN tier", className="third") ]), html.Tr([ html.Td(children=[ html.Div("line", style={'display': 'inline-block'}), html.Div("*", style={ 'display': 'inline-block', 'color': 'red' }) ]), html.Td("tanhe:x’a'ha:ma:lhtzá'"), html.Td(createPulldownMenu("speech", tierChoices)) ]), html.Tr([ html.Td("alternate transcription"), html.Td("taŋʔeːš’a̰ʔaːmaːɬtsá̰"), html.Td(createPulldownMenu("transcription2", tierChoices)) ]), html.Tr([ html.Td("morphological analysis"), html.Td("taŋʔeː–š’a̰ʔáː–maːɬ=tsá̰"), html.Td(createPulldownMenu("morpheme", tierChoices)) ]), html.Tr([ html.Td("morphemic glosses"), html.Td(children=[ html.Div("basin–", style={'display': 'inline-block'}), html.Div("shine", style={'display': 'inline-block'}), html.Div("–prog", style={ 'font-variant': 'small-caps', 'display': 'inline-block' }), html.Div("=now", style={ 'font-variant': 'small-caps', 'display': 'inline-block' }) ]), html.Td(createPulldownMenu("morphemeGloss", tierChoices)) ]), html.Tr([ html.Td(children=[ html.Div("translation", style={'display': 'inline-block'}), html.Div("*", style={ 'display': 'inline-block', 'color': 'red' }) ]), html.Td("‘The horizon is growing light.’"), html.Td(createPulldownMenu("translation", tierChoices)) ]), html.Tr([ html.Td("second translation"), html.Td("‘Está aclarando donde sale el sol.’"), html.Td(createPulldownMenu("translation2", tierChoices)) ]) ], className="tiermap") saveTierMappingChoicesButton = html.Button( 'save', id='saveTierMappingSelectionsButton', className="button") tierMappingChoicesResultDisplay = html.Span( id="tierMappingChoicesResultDisplay", children="", style={ "border": 1, "margin-left": 10, "font-size": "12pt" }) requiredTiersFootnote = html.Span("*Required", id='requiredTiersFootnote', className="warningfootnote") children = [ dropDownMenus, html.Br(), saveTierMappingChoicesButton, tierMappingChoicesResultDisplay, requiredTiersFootnote ] enclosingDiv = html.Div(children=children) return (enclosingDiv)
def generate_table(dataframe): print('html.Table(className='mytable',children= \ [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 make_html_table_from_df(df: pd.DataFrame, max_rows: int = 20): ''' ''' return html.Table(children=[html.Tr([html.Th(i) for i in df.columns])] + \ [html.Tr([html.Td(i) for i in row]) for row in df.head(max_rows).values.tolist()] )
import dash_core_components as dcc import dash_bootstrap_components as dbc import dash_html_components as html from building_blocks import * from callbacks import * prefix = "help" print("Loading " + prefix.capitalize() + " ...") #TABLES nodes_header = [ html.Thead( html.Tr( [html.Th("Property"), html.Th("Description"), html.Th("Source")])) ] drugs_body = [ html.Tbody([ html.Tr([ html.Td("ID"), html.Td("DrugBank unique identification code"), html.Td( html.A("DrugBank", href="https://go.drugbank.com/", target="_blank")) ]), html.Tr([ html.Td("SMILES"), html.
def createDetailRow(content, name, rowNumber): """ Returns a single row for the details table Positional arguments: content -- The attribute data as String. name -- Name for the attribute. rowNumber -- Used for odd/even coloring. """ # Check subtable information try: headerLine = [cfg.subTables['column_id'].str.contains(name)] except (TypeError, AttributeError, KeyError): headerLine = None try: headers = str(headerLine.iloc[0]['columns']).split(';') except (TypeError, AttributeError, KeyError): headers = None if content == None or name == None: return None subRows = [] # Holds elements for multivalue attributes subTable = [] # Holds elements for subtables if headers != None: # We have subtable information, so try and create one headerRow = [] for k in headers: # Build table header line headerRow.append(html.Th(k)) subTable.append(html.Tr(children=headerRow)) tableError = False for i in content.split( ';'): # Build subtable rows dictated by ; delimitation subSubRow = [] if len(i.split(',')) == len(headers): for j in i.split( ',' ): # Build subtable columns dictated by , delimitation if j != '': if j[0] == '?': subSubRow.append( html.Td( html.A(j[1:], href=j[1:].strip(), target='_blank'))) else: subSubRow.append(html.Td(j.strip())) subTable.append(html.Tr(children=subSubRow)) else: tableError = True if tableError == True: # Column numbers didn't match, default display print( 'Warning: Number of columns specified in subtable file do not match number of columns in description file' ) subTable = [] for l in content.split(';'): if l != '': if l[0] == '?': # Create hyperlinks subRows.append( html.Tr( html.Td( html.A(l[1:], href=l[1:].strip(), target='_blank')))) else: subRows.append(html.Tr(html.Td(l.strip()))) else: # No subtable information for i in content.split(';'): if i != '': if i[0] == '?': subRows.append( html.Tr( html.Td( html.A(i[1:], href=i[1:].strip(), target='_blank')))) else: subRows.append(html.Tr(html.Td(i.strip()))) if len(subRows ) > 5: # Hide values in details element if more than 5 values tableRow = html.Tr(children=[ html.Td(html.B(name.replace('_', ' ').title())), html.Td( html.Details(title=str(len(subRows)) + ' values', children=[ html.Summary(str(len(subRows)) + ' values'), html.Table(children=subRows) ])) ], style={ 'background-color': tableColors[rowNumber % 2] }) else: tableRow = html.Tr( children=[ html.Td(html.B(name.replace('_', ' ').title())), html.Td(html.Table(children=subRows)) ], style={'background-color': tableColors[rowNumber % 2]}) if len(subTable) > 0: return html.Tr(children=[ html.Td(html.B(name.replace('_', ' ').title())), html.Td(html.Table(children=subTable)) ], style={'background-color': tableColors[rowNumber % 2]}) else: return tableRow
def display_tab_content(value): if value == 3: return html.Div([ html.Div( dcc.Dropdown(id = 'prediction-menu', options = [ {'label': 'Total Surface (m2)', 'value': 'space'}, {'label': 'Total volume (m3)', 'value': 'volume'}, {'label': 'Number of rooms', 'value': 'rooms'}, #{'label': 'Neighbourhood', 'value': 'nh'}, {'label': 'property type', 'value': 'type'}, ], multi = True, value = 1 )), html.Div(id = 'dynamic-prediction-input-surface', style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), html.Div(id = 'dynamic-prediction-input-volume', style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), html.Div(id = 'dynamic-prediction-input-rooms', style ={'width':'80%', 'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), html.Div(id = 'dynamic-prediction-input-type', style ={'marginBottom': 50, 'marginTop': 20, 'margin-left': 'auto', 'margin-right': 'auto'}), html.Button('Submit', id='button', style = { 'horizontalAllign': 'middle'}), html.Div(id = 'price-prediction-output', children = "select values and press submit", ) ]) elif value == 1: return html.Div([ html.H1('Property price map', style = {'width': '100%', 'textAlign': 'center' }), html.Div(id='text-content', style={'width': '70%', 'textAlign': 'center'} ), html.Div(id='property-details', style={'width': '30%', 'float': 'right', 'margin-left': '10px'}), dcc.Graph(id='map', figure={ 'data': [{ 'lat': data_frame['Latitude'], 'lon': data_frame['Longitude'], 'marker': { 'color': data_frame.Price, 'size': 11, 'opacity': 0.7, 'colorscale': 'Jet', 'colorbar': { 'thicknessmode': 'fraction', 'title': 'Price range', 'titlefont': {'family':'Sans-Serif', 'size': 17}, 'ticks': 'outside', 'nticks': 20, 'xanchor': 'right', 'x': 1.02, 'outlinewidth': 0, 'tickfont':{'family':'Sans-Serif','size': 14}, 'xpad': 0, } }, 'text': data_frame['Street'], 'customdata': data_frame['Property number'], 'type': 'scattermapbox', }], 'layout': { 'autosize': True, 'mapbox': { 'center':{'lat':52.35211, 'lon': 4.88773}, 'zoom': 10.8, 'accesstoken': mapbox_access_token }, 'hovermode': 'closest', 'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0} } }, style={'width': '70%'}), dcc.RangeSlider(id = 'pricerange-map', ) ]), elif value == 2: return html.Div([html.H4('Predict the price of your desired property!'), html.Div(id = 'Predictor-tab') ]) elif value == 4: return html.Div([ html.Div('Data viz tab', ), dcc.Dropdown(id = 'data-viz-menu', options = [ {'label': 'average price map', 'value': 1}, {'label': 'graphs', 'value' :2}, {'label': 'add something', 'value':3} ]), html.Div(id = 'data-viz-content') ]) elif value == 5: return html.Div([html.Table( [html.Tr([html.Th(col) for col in data_frame.columns])] + [html.Tr([ html.Td(data_frame.iloc[i][col]) for col in data_frame.columns ]) for i in range(min(len(data_frame), len(data_frame)))]) ])
def update_output(n_clicks, input1, input2, input3, input4, input5, input6, input7, input8, input9, input10, input11, input12, input13): if n_clicks == 0: pass else: # Gather and compute input values input13 = datetime.datetime.strptime(input13, '%Y-%m-%d %H:%M:%S.%f') y = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) index = 0 parseInput1 = input1.split(",") for i in parseInput1: y[index] = float(i) index += 1 if input2 == "" or input3 == "" or input4 == "": pass else: t0 = float(input2) tf = float(input3) step = float(input4) kepOrGeo = int(input5) other = list(input6) sunAndMoon = False solar = False drag = False if 1 in other: sunAndMoon = True if 2 in other: solar = True if 3 in other: drag = True loopTf = step loopIndex = int((tf - t0) / step) # Run main computation method y = propagatorObj.rk4(y, t0, tf, step, kepOrGeo, solar, float(input7), sunAndMoon, drag, float(input8), input12, propagatorObj.C, propagatorObj.S, float(input9), input10, input11, input13) # Create dataframe for state vectors table altitude = np.sqrt(np.asarray(propagatorObj.keepStateVectors)[:, 0]**2 + np.asarray(propagatorObj.keepStateVectors)[:, 1]**2 + np.asarray(propagatorObj.keepStateVectors)[:, 2]**2) beforeDataFrame = np.zeros((loopIndex, 7)) beforeDataFrame[:, 1:7] = propagatorObj.keepStateVectors[:] beforeDataFrame[:, 0] = propagatorObj.epochs[:] returnTable = pd.DataFrame(data=beforeDataFrame[:, :], index=range(0, loopIndex), columns=["Time(sec)", "rx(m)", "ry(m)", "rz(m)", "vx(m/s)", "vy(m/s)", "vz(m/s)"]) # Create dataframe for accelerations table propagatorObj.accelerations_graph(solar, sunAndMoon, drag) beforeAccelTable = np.zeros((len(propagatorObj.tickLabels), 4)) for i in range(0, len(propagatorObj.tickLabels)): beforeAccelTable[i, 0] = propagatorObj.keepAbsoluteAccelerations[i][0] beforeAccelTable[i, 1] = propagatorObj.keepAbsoluteAccelerations[i][1] beforeAccelTable[i, 2] = propagatorObj.keepAbsoluteAccelerations[i][2] beforeAccelTable[i, 3] = propagatorObj.keepAbsoluteAccelerations[i][3] returnAcceTable = pd.DataFrame( data=beforeAccelTable, index=propagatorObj.tickLabels, columns=["Max(m/s^2)", "Min(m/s^2)", "Average(m/s^2)", "STD(m/s^2)"] ) returnAcceTable.insert(0, "Source", returnAcceTable.index) if len(propagatorObj.tickLabels) == 1: depends = "accel-sizes-hide" depends1 = "accel-sizes-hide1" else: depends = "accel-sizes" depends1 = "accel-sizes1" # Keplerian Elements Graph returnStaticKepTable, kepElements = propagatorObj.keplerian_elements_graph() trace1 = go.Scatter( x=propagatorObj.epochs, y=kepElements[:, 0], opacity=0.7, ) trace2 = go.Scatter( x=propagatorObj.epochs, y=kepElements[:, 1], opacity=0.7, ) trace3 = go.Scatter( x=propagatorObj.epochs, y=kepElements[:, 2], opacity=0.7, ) trace4 = go.Scatter( x=propagatorObj.epochs, y=kepElements[:, 3], opacity=0.7, ) trace5 = go.Scatter( x=propagatorObj.epochs, y=kepElements[:, 4], opacity=0.7, ) trace6 = go.Scatter( x=propagatorObj.epochs, y=kepElements[:, 5], opacity=0.7, ) fig = tools.make_subplots(rows=3, cols=2, specs=[[{}, {}], [{}, {}], [{}, {}]], subplot_titles=('Semi Major Axis(km)', 'Eccentricity(float)', 'Inclination(Degrees)', 'Argument of Perigee(degrees)', "Longitude of the ascending node(degrees)", "True anomaly(degrees)"), shared_xaxes=True, vertical_spacing=0.1) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 2, 1) fig.append_trace(trace4, 2, 2) fig.append_trace(trace5, 3, 1) fig.append_trace(trace6, 3, 2) fig['layout'].update(height=1000, title='Keplerian Elements', showlegend=False) # Log Acceleration Graph allTraceLogs = [] for i in range(0, len(propagatorObj.keepWantedAcceleration)): tracelog = go.Scatter( x=propagatorObj.epochs, y=propagatorObj.keepWantedAcceleration[i], name=propagatorObj.keepWantedTickLabels[i], ) allTraceLogs.append(tracelog) layoutlog = go.Layout( yaxis=dict( type='log', exponentformat='e', ) ) figlog = go.Figure(layout=layoutlog) figlog['layout'].update(title='Logarithmic Accelerations Graph (m^2/sec)') figlog.add_traces(allTraceLogs) # Return all the tables and graphs return html.Div(children= [html.Table( # Header [html.Tr([html.Th(col) for col in returnTable.columns])] + # Body [html.Tr([ html.Td(returnTable.iloc[i][col]) for col in returnTable.columns ]) for i in range(min(len(returnTable), loopIndex))] )], style={"padding": "20px 17%", "width": "100%"}),\ html.Div(id="info-download-state"), \ html.Button(children="Download State Vectors", id="download-state-vectors", n_clicks=0), \ html.Br(),\ dcc.Graph( id='alitutde-graph', figure={ 'data': [ go.Scatter( x=propagatorObj.epochs, y=altitude/1000, opacity=0.7, ) ], 'layout': {'title': 'Altitude (km)', 'exponentformat': "'e'"} } ), \ \ \ html.Div(children= [html.Table( # Header [html.Tr([html.Th(col) for col in returnStaticKepTable.columns])] + # Body [html.Tr([ html.Td(returnStaticKepTable.iloc[i][col]) for col in returnStaticKepTable.columns ]) for i in range(min(len(returnStaticKepTable), loopIndex))] , id="kep-table")], style={"padding": "20px 17%", "margin": "25px 0px", "width": "100%"}), \ html.Div(id="info-download-kep"), \ html.Button(children="Download Keplerian Elements", id="download-kep-elements", n_clicks=0), \ html.Br(), \ dcc.Graph( id="kep-graph", figure=fig ), \ \ \ html.Div(children= [html.Table( # Header [html.Tr([html.Th(col) for col in returnAcceTable.columns])] + # Body [html.Tr([ html.Td(returnAcceTable.iloc[i][col]) for col in returnAcceTable.columns ]) for i in range(min(len(returnAcceTable), loopIndex))] , id="accel-table")], style={"padding": "20px 25%", "margin": "25px 0px"}), \ html.Div(id="info-download-accel"), \ html.Button(children="Download Acceleration Vectors", id="download-accel-vectors", n_clicks=0), \ html.Br(), \ dcc.Graph( id=depends, figure={ 'data': [ {'x': propagatorObj.tickLabels, 'y': propagatorObj.accelerationsGraph, 'type': 'bar'} ], 'layout': {'title': 'Accelerations Order of Magnitude'} } ), \ html.Br(), \ dcc.Graph( id=depends1, figure=figlog, ),
import dash_html_components as html from dash.dependencies import Input, Output, State import plotly.graph_objs as go import flask app = dash.Dash( __name__, external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']) url_bar_and_content_div = html.Div( [dcc.Location(id='url', refresh=False), html.Div(id='page-content')]) #-----------------------------------------page-0-Layout home page---------------------------------------------------------------- layout_index = html.Div([ html.Table([ html.Tr([ html.Th(html.Img(src=app.get_asset_url('infogen.png')), style={'textAlign': 'left'}), html.Th(html.H2("King's County Housing Data Analysis")), html.Th(dcc.Link('Home', href='/page-0'), style={'text-align': 'center'}), html.Th(dcc.Link('Data', href='/page-1'), style={'text-align': 'center'}), html.Th(dcc.Link('Distribution', href='/page-2'), style={'text-align': 'center'}), html.Th(dcc.Link('Scatter', href='/page-3'), style={'text-align': 'center'}), html.Th(dcc.Link('Zipcode', href='/page-4'), style={'text-align': 'center'}), html.Th(dcc.Link('Price Predictor', href='/page-5'), style={'text-align': 'center'}), html.Th(dcc.Link('Results', href='/page-6'), style={'text-align': 'center'}),
def full_graph(value): if value == "moving_average": graph = html.Div(children=[ dcc.RadioItems( id='radio-items', options = [ {'label': 'SMA', 'value': 'sma'}, {'label': 'EMA', 'value': 'ema'}, {'label': 'MACD', 'value': 'macd'}, {'label': 'Bollinger', 'value': 'bollinger'}, ], value = "sma", labelStyle={'display': 'inline-block'} ), dcc.Graph( id='moving_average', figure={ 'data': [ main_price_plot, ], 'layout': standard_layout } ), profit_loss, ] ) if value == "sentiment": graph = [ html.Div(className='two-thirds column', children=[ dcc.Graph( id='graph', figure={ 'data': [ open_price_plot, buy_annotations, sell_annotations, ], 'layout': standard_layout } ), profit_loss, ]), html.Div(className='four columns', children=[ html.H4(id="news_title", children="Click to see news headlines!"), html.Div(style={'margin-left': 'auto', 'margin-right': 'auto'}, children=[ html.Table(className="center", id='click-data', children=[ html.Tr([ html.Th("Article Title"), html.Th("Sentiment") ]), ]) ]) ])] return graph
# Begin of First Table html.Table(style={'width':'100%'}, # Begin of Table children children=[ ####################################################################### # Begin of First Tr html.Tr( #Begin Tr children children=[ # Begin Th html.Th(style={'width':'30%'}, # Begin Th children children=[ html.H3('US Export Performance of Fruits and Veggies in 2019') # End of Th children ] # End of Th - Notice a comma is placed here to separate the next Th ), # Begin of Th html.Th(style={'width':'70%'}, # Begin of Th children children=[ html.H3('Global GDP for Fruits and Veggies') # End of Th children ] # End of Th )
className="slider" ), dcc.Slider( id="u4", min=1, max=10, step=1, value=u4, updatemode='drag', className="slider" ) ], className='graph-section'), html.Div(children=[ html.Table( [ html.Tr([html.Th(""), html.Th("تمکین"), html.Th("تمرد")]) ] + [ html.Tr([html.Td("تمکین"), html.Td(html.Span(id='u1-value', children=str(u4) + "," + str(u4))), html.Td(html.Span(id='u2-value', children=str(u2) + "," + str(u1)))]), html.Tr([html.Td("تمرد"), html.Td(html.Span(id='u3-value', children=str(u1) + "," + str(u2))), html.Td(html.Span(id='u4-value', children=str(u3) + "," + str(u3)))]) ] ), ], className="section")
'layout': go.Layout( title='Coût de Contravention Selon les Années', yaxis={'title': 'Année'}, xaxis={'title': 'Montant de la Contravention ($)'}, hovermode='closest', #legend={'x': 0, 'y': 1} ) }, style={'paddingLeft': '25px'}), html.Div(children='Liste Des Restaurants', style={ 'color': colors['text'], 'fontSize': '35px', 'marginLeft': '100px' }), html.Table(children=[html.Tr([html.Th(col) for col in df.columns])] + [ html.Tr([html.Td(df.iloc[i][col]) for col in df.columns]) for i in range(min(len(df), number_rows)) ], style={ 'color': colors['text'], 'fontSize': '12px', 'marginLeft': 'auto', 'marginRight': 'auto' }) ]) if __name__ == '__main__': app.run_server(debug=True)
}), ], # CSS style to display on web page nicely style={ 'display': 'grid', 'grid-template-rows': '25px 25px 25px 25px', 'grid-auto-columns': '100px 100px 100px 100px 150px' }), # Break element for spacing between elements of page html.Br(), # Explantory table to remind trader what comment represents # Allows trader to make adjustments to find a bond if comment is too restrictive html.Div( children=[ html.Table( [html.Tr([html.Th(col) for col in comment_names])] + [ html.Tr([ html.Td( dcc.Input(id='increment', placeholder='Input Increment', value='', type='number', min=1, max=50, step=1, style={'width': 60})), html.Td( dcc.Input(id='size', value='', placeholder='Input Size', min=10000,
className='example-container', style={'overflow-x': 'initial'} ), html.Hr(), html.H3('Month and Display Format'), dcc.Markdown("The `display_format` property \ determines how selected dates are displayed \ in the `DatePickerRange` component. The `month_format` \ property determines how calendar headers are displayed when \ the calendar is opened."), html.P("Both of these properties are configured through \ strings that utilize a combination of any \ of the following tokens."), html.Table([ html.Tr([ html.Th('String Token', style={'text-align': 'left', 'width': '20%'}), html.Th('Example', style={'text-align': 'left', 'width': '20%'}), html.Th('Description', style={'text-align': 'left', 'width': '60%'}) ]), html.Tr([ html.Td(dcc.Markdown('`YYYY`'), style={'text-align': 'left'}), html.Td(dcc.Markdown('`2014`'), style={'text-align': 'left'}), html.Td('4 or 2 digit year') ]), html.Tr([ html.Td(dcc.Markdown('`YY`'), style={'text-align': 'left'}), html.Td(dcc.Markdown('`14`'), style={'text-align': 'left'}), html.Td('2 digit year') ]), html.Tr([ html.Td(dcc.Markdown('`Y`'), style={'text-align': 'left'}),
def update_graph(term,n): global old_term if term == '' : term = old_term old_term = term conn = sqlite3.connect('twitter.db') # manage_data(conn) df = pd.read_sql("select * from sentiment where tweet like '%"+term+"%' order by unix desc limit 1000",conn) df['unix'] = pd.to_datetime(df['unix'],unit='ms') df.sort_values('unix',inplace=True) df.set_index('unix',inplace=True) df = df.iloc[-100:,:] tableData = df.iloc[-10:,:] positive = 0 negative = 0 neutral = 0 for senti in df['sentiment']: if senti > 0: positive += 1 if senti < 0: negative += 1 else: neutral += 1 df['smoothe_sentiment'] = df['sentiment'].rolling(int(len(df)/5)).mean() df = df.resample('2s').mean() df.dropna(inplace=True) X = df.index Y = df.smoothe_sentiment.values data = go.Scatter( x=list(X), y=list(Y), name = 'Scatter', mode = 'lines+markers' ) layout = go.Layout(xaxis = dict(range=[min(X),max(X)]), yaxis = dict(range=[min(Y),max(Y)]), margin=dict(l=40,r=20,b=20,t=60,pad=0), template = 'plotly_dark', hovermode='x') pie = go.Pie(values=[positive,negative,neutral], labels= ['Positive','Negative','Neutral'], text=['Positive','Negative','Neutral'], marker={'colors' :['green','red','blue']}, hole = 0.4) print(tableData.columns) return [{'data':[data],'layout':layout}, {'data':[pie],'layout':layout}, html.Table(className="responsive-table", children=[ html.Thead( html.Tr( children=[ html.Th(col.title()) for col in tableData.columns.values], style={'color':app_colors['text']} ) ), html.Tbody( [ html.Tr( children=[ html.Td(data) for data in d ], style={'color':app_colors['text'], 'background-color':quick_color(d[1])} ) for d in tableData.values.tolist()]) ] )]
def generate_table(dataframe, max_rows=10): return html.Table([html.Tr([html.Th(col) for col in dataframe.columns])] + [ html.Tr([html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows)) ])
dbc.Col([ html.H2("Detailed Result"), # dcc.Graph( # figure={"data": [{"x": [1, 2, 3], "y": [1, 4, 9]}]} # ), ##efffefd1 dash_table.DataTable(id='upload-table', data=[{} for _ in range(6)], columns=[{"name": i, "id": i} for i in columns], fixed_rows={'headers': True, 'data': 0}, style_cell={'width': '150px', 'textAlign': 'left', 'backgroundColor': '#efffefd1'}, style_header={'backgroundColor':'#fafafa'}, style_table={'maxHeight': '227px', 'width': '587px'}) ], md=5), ]) ] feature_importance_table = html.Div([ html.Td([ html.Thead([ html.Tr([ html.Th("bootstrap",), html.Th("class_weight",), html.Th("criterion",), html.Th("max_depth",), html.Th("max_features",), html.Th("max_leaf_nodes",), html.Th("min_impurity_decrease",), html.Th("min_impurity_split",), html.Th("min_samples_split",), html.Th("min_weight_fraction_leaf",), html.Th("n_estimators",), html.Th("n_jobs",), html.Th("oob_score",), html.Th("random_state",), html.Th("verbose",), html.Th("warm_start",),
def on_form_change(seats_value, rapidCharge_value, drivingRange_value, budgetRange_value): results = [ seats_value, rapidCharge_value, drivingRange_value, budgetRange_value ] if len(results) == 4: predicted_EV = c.build_knn_model(results) EV = c.recommended_EV(predicted_EV) EV_stats = c.get_EV_stats(EV) a = str(EV_stats) final_ev_stats = ''.join(a) table_header = [ html.Thead(html.Tr([html.Th("Your Recommended EV is:"), html.Th(EV)])) ] row1 = html.Tr([html.Td("Brand"), html.Td(EV_stats[1])]) row2 = html.Tr([html.Td("Model"), html.Td(EV_stats[2])]) row3 = html.Tr([html.Td("AccelSec"), html.Td(EV_stats[3])]) row4 = html.Tr([html.Td("Efficiency_WhKm"), html.Td(EV_stats[4])]) row5 = html.Tr([html.Td("FastCharge_KmH"), html.Td(EV_stats[5])]) row6 = html.Tr([html.Td("RapidCharge"), html.Td(EV_stats[6])]) row7 = html.Tr([html.Td("PowerTrain"), html.Td(EV_stats[7])]) row8 = html.Tr([html.Td("PlugType"), html.Td(EV_stats[8])]) row9 = html.Tr([html.Td("BodyStyle"), html.Td(EV_stats[9])]) row10 = html.Tr([html.Td("Segment"), html.Td(EV_stats[10])]) row11 = html.Tr([html.Td("Seats"), html.Td(EV_stats[11])]) row12 = html.Tr([html.Td("TopSpeed_mph"), html.Td(EV_stats[13])]) row13 = html.Tr([html.Td("Range_Mi"), html.Td(EV_stats[14])]) row14 = html.Tr([html.Td("EV Price"), html.Td(EV_stats[15])]) table_body = [ html.Tbody([ row1, row2, row3, row4, row5, row6, row7, row8, row9, row10, row11, row12, row13, row14 ]) ] table = dbc.Table( table_header + table_body, style={ 'width': '650px', 'font-size': '14px', 'height': '20px' }, bordered=True, # dark=True, hover=True, responsive=True, striped=True) image = dbc.Card([ dbc.CardBody(html.P("Here is an image of your recommended EV!"), style={'backgroundColor': '#d0eeea'}), dbc.CardImg( src="assets/bmw-i4.png", bottom=True, style={"width": "650px"}, ), ]) recommendation = html.Div([table, image], style={ 'layout': 'inline-block', 'align': 'right' }) return recommendation
def extractor__to_html_row(obj__value): print("\n#49 START extractor__to_html_row() \n") this_df = obj__value[0] list_of_rows = obj__value[1] n_row = 0 row_col_id = "" list_of_row_column_pair.clear() table_head = [] list_of_tr_item = [] list_of_rd_input = [] #// list_of_this_pair=[] # A Local Storage for cell x,y coordination for k in list_of_rows: listOf_cell = list_of_rows[n_row] list_of_row_radio_items = [] list_x1 = [] # print("\n -> extractor() --> for k in list_of_rows : ", n_row ,"\n") # print("\n -> extractor() --> for k in list_of_rows --> printing this_cell ", this_cell ,"\n") print("\n -> extractor()" " \n --> for k in list_of_rows") #===================== # DESC: Loops through each column-cells in a row: n_cell = 0 # n_cell -- column cell (left to right) for this_cell in listOf_cell: cell_index = this_cell[0] # L4-1 cell_index_x = cell_index[0] #L5-1 cell_index_y = cell_index[1] #L5-2 cell_value = this_cell[2] print( "\n -> extractor()", " \n --> for k in list_of_rows" "\n --> for this_cell in listOf_cell", this_cell, "\n") if this_cell[1] == False: bg_cell = "rgb(255, 179, 153)" row_col_id = str(cell_index_x) + "_" + str(n_cell) list_of_row_column_pair.append((cell_index_x, n_cell)) else: bg_cell = "white" list_x1_2 = [ html.Td(cell_value, style={'backgroundColor': bg_cell}) ] list_x1 = list_x1 + list_x1_2 n_cell = n_cell + 1 # END (for this_cell in listOf_cell) list_x3 = [ dcc.RadioItems(id='radioitem_' + str(row_col_id), options=[{ 'label': 'Ignore', 'value': 'ign' }, { 'label': 'Delete', 'value': 'del' }], value='ign', labelStyle={'display': 'inline-block'}), #// add_to_bt_itemlist(component_id, component_value) print("\n #16 \n"), list_of_radio_items_id.append('radioitem_' + str(row_col_id)), ] list_x4 = list_x1 + list_x3 list_of_row_radio_items = list_of_row_radio_items + list_x4 #list_x1_tup = tuple(list_x1) print("\n") list_x2 = [html.Tr(list_of_row_radio_items)] list_of_tr_item = list_of_tr_item + list_x2 print("\n test_3:") print(list_of_row_radio_items) print("\n") n_row = n_row + 1 print("\n test_2 \n") print(list_of_tr_item) print("\n") # DESCRIPTION: # Table -- with rows of value + option buttons html_table = html.Table( [html.Tr([html.Th(col) for col in this_df.columns])] + list_of_tr_item) html_output = html.Div( [html_table, html.Button('Apply', id='apply_btn')], ) L2_3 = obj__value[2] data_is_clean = L2_3[1] # DEBUG PRINT: print("\n extractor__to_html_row() #14 :") print("> data_is_clean = ", data_is_clean) if data_is_clean == True: html_output = html.Div(children="Data is valid and clean") # DEBUG PRINT: print("\n printing the object: \n") print(obj__value) print("\n printing the return: \n") print(html_table) print("\n") print("#49 END extractor__to_html_row()") return html_output
'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, multiple=False), ]), html.Div([ html.Label( 'Select below how to clean Columns before loading the file' ), html.Table([ # header html.Tr([ html.Th('Categorical'), html.Th('Numerical') ]), # body html.Tr([ html.Td([ dcc.Checklist(options=[{ 'label': 'lower', 'value': 'lower' }, { 'label': 'trim', 'value': 'trim' }, { 'label': 'one-hot enc', 'value': 'one-hot', 'disabled': True
def test_inin011_multi_output(dash_duo): app = Dash(__name__) app.layout = html.Div( [ html.Button("OUTPUT", id="output-btn"), html.Table( [ html.Thead( [html.Tr([html.Th("Output 1"), html.Th("Output 2")])] ), html.Tbody( [ html.Tr( [html.Td(id="output1"), html.Td(id="output2")] ) ] ), ] ), html.Div(id="output3"), html.Div(id="output4"), html.Div(id="output5"), ] ) @app.callback( [Output("output1", "children"), Output("output2", "children")], [Input("output-btn", "n_clicks")], [State("output-btn", "n_clicks_timestamp")], ) def on_click(n_clicks, n_clicks_timestamp): if n_clicks is None: raise PreventUpdate return n_clicks, n_clicks_timestamp # Dummy callback for DuplicateCallbackOutput test. @app.callback( Output("output3", "children"), [Input("output-btn", "n_clicks")] ) def dummy_callback(n_clicks): if n_clicks is None: raise PreventUpdate return "Output 3: {}".format(n_clicks) with pytest.raises(DuplicateCallbackOutput) as err: @app.callback( Output("output1", "children"), [Input("output-btn", "n_clicks")] ) def on_click_duplicate(n_clicks): if n_clicks is None: raise PreventUpdate return "something else" pytest.fail("multi output can't be included in a single output") assert "output1" in err.value.args[0] with pytest.raises(DuplicateCallbackOutput) as err: @app.callback( [Output("output3", "children"), Output("output4", "children")], [Input("output-btn", "n_clicks")], ) def on_click_duplicate_multi(n_clicks): if n_clicks is None: raise PreventUpdate return "something else" pytest.fail("multi output cannot contain a used single output") assert "output3" in err.value.args[0] with pytest.raises(DuplicateCallbackOutput) as err: @app.callback( [Output("output5", "children"), Output("output5", "children")], [Input("output-btn", "n_clicks")], ) def on_click_same_output(n_clicks): return n_clicks pytest.fail("same output cannot be used twice in one callback") assert "output5" in err.value.args[0] with pytest.raises(DuplicateCallbackOutput) as err: @app.callback( [Output("output1", "children"), Output("output5", "children")], [Input("output-btn", "n_clicks")], ) def overlapping_multi_output(n_clicks): return n_clicks pytest.fail( "no part of an existing multi-output can be used in another" ) assert ( "{'output1.children'}" in err.value.args[0] or "set(['output1.children'])" in err.value.args[0] ) dash_duo.start_server(app) t = time.time() btn = dash_duo.find_element("#output-btn") btn.click() time.sleep(1) dash_duo.wait_for_text_to_equal("#output1", "1") assert int(dash_duo.find_element("#output2").text) > t
def schema_table(df, types, subtypes): """ Helper to create the table. Dash's DataTable doesn't allow for \ dropdowns to only some rows so we create our own where the first \ row is the head, the second rows are like head but have dropdowns \ for picking types Args: df (`pd.DataFrame`): The dataset. types (dict): The types from the data schema. subtypes (dict): The subtypes from the data schema. Returns: A Dash element containing the table. """ subtype_options = { "categorical": [{ "label": dtype, "value": dtype } for dtype in "binary categorical".split()], "integer": [{ "label": "integer", "value": "integer" }], "date": [{ "label": "date", "value": "date" }], "float": [{ "label": dtype, "value": dtype } for dtype in "float longitude latitude".split()], "string": [{ "label": dtype, "value": dtype } for dtype in "email ipv4 ipv6 mac_address string".split()], } return html.Div([ html.Table([ html.Thead([html.Th(col_name) for col_name in df.columns], id="table_colnames"), html.Tbody([ html.Tr([ html.Td( dcc.Dropdown(options=all_datatypes_options, value=types[col_name])) for col_name in df.columns ], id="row_type"), html.Tr([ html.Td( dcc.Dropdown(options=subtype_options[types[col_name]], value=subtypes[col_name])) for col_name in df.columns ], id="row_subtype"), ] + [ html.Tr([html.Td(item) for item in row]) for (i, row) in df.iterrows() ]) ]) ])