def file_menu(): """File menu items 1. New Document 2. Open mrsimulator file (.mrsim) """ file_items = [ menu_item( icon_text("fas fa-file", "New Document"), href="/simulator", external_link=True, target="_blank", ), dcc.Upload( menu_item(icon_text("fas fa-folder-open", "Open...")), id="open-mrsimulator-file", accept=".mrsim", ), menu_item( icon_text("fas fa-file-download fa-lg", "Download Session"), id="download-session-menu-button", ), ] # callback for downloading session from menu app.clientside_callback( """function(n) { return n+1; }""", Output("download-session-button", "n_clicks"), Input("download-session-menu-button", "n_clicks"), State("download-session-button", "n_clicks"), prevent_initial_call=True, ) return create_submenu(label="File", children=file_items)
def global_environment(): """Generate a list of widgets whose entries are the sample global environment parameter. The widgets includes flux density, rotor frequency, and rotor angle.""" flux_density = custom_input_group( prepend_label="Magnetic flux density (B₀)", append_label="T", value=9.4, id="magnetic_flux_density", min=0.0, debounce=True, ) # rotor frequency rotor_frequency = custom_input_group( prepend_label="Rotor frequency (𝜈ᵣ)", append_label="kHz", value=0.0, id="rotor_frequency", min=0.0, debounce=True, ) # rotor angle magic_angle = custom_button( icon_classname="fas fa-magic", tooltip="Set value to the magic angle.", id="set-to-magic-angle", className="icon-button", module="html", ) # dbc.Button( # html.I(className="fas fa-magic"), # color="light", # id="set-to-magic-angle", # size="sm", # ) # datalist = html.Datalist([0, 54.7356103172, 90], id="datalist-magic-angle") rotor_angle = custom_input_group( prepend_label=html.Div(["Rotor angle (θᵣ)", magic_angle]), append_label="deg", value=54.7356103172, id="rotor_angle", max=90, min=0, debounce=True, # list="datalist-magic-angle", ) app.clientside_callback( """function(n) { return 54.7356103172; }""", Output("rotor_angle", "value"), Input("set-to-magic-angle", "n_clicks"), ) return container( text="Global Environment Parameters", featured=[flux_density, rotor_frequency, rotor_angle], )
def method_menu(): """Method menu items 1. Add a new method 2. Duplicate selected method 3. Remove selected method ------------------------------ 4. Clear methods """ message_method = "You are about to delete all methods. Do you want to continue?" method_items = [ menu_item(icon_text("fas fa-plus-circle", "Add a new method"), id="add_method"), menu_item(icon_text("fas fa-clone", "Duplicate selection"), id="duplicate_method"), menu_item(icon_text("fas fa-minus-circle", "Remove selection"), id="remove_method"), menu_item(divider=True), menu_item("Clear all methods", id="clear-methods"), menu_item(divider=True), menu_item("Measurement", header=True), menu_item( dcc.Upload( icon_text("fas fa-paperclip", "Add to selection"), id="add-measurement-for-method", )), menu_item( icon_text("fas fa-times-circle", "Remove from selection"), id="remove-measurement-from-method", ), dcc.ConfirmDialog(id="confirm-clear-methods", message=message_method), ] # Callbacks for the add, duplicate, and remove methods _ = [ app.clientside_callback( f"""function() {{ document.getElementById("{t}-method-button").click(); throw window.dash_clientside.PreventUpdate; }}""", Output(f"{t}-method-button", "n_clicks"), Input(f"{t}_method", "n_clicks"), prevent_initial_call=True, ) for t in TARGET ] # Callbacks for the clear all methods app.clientside_callback( """function(n) { if (n == null) throw window.dash_clientside.PreventUpdate; return true; }""", Output("confirm-clear-methods", "displayed"), Input("clear-methods", "n_clicks"), prevent_initial_call=True, ) return create_submenu(label="Method", children=method_items, right=False)
def graph_ui(): plotly_graph = generate_graph_instance(id_="nmr_spectrum") # initialize app with graph instance app.clientside_callback( ClientsideFunction(namespace="clientside", function_name="initialize"), Output("temp1", "children"), [Input("nmr_spectrum", "figure")], ) return dcc.Loading(plotly_graph, type="dot")
def scrollable(): default = display() app.clientside_callback( """function(n) { document.getElementById("add-method-button").click(); throw window.dash_clientside.PreventUpdate; }""", Output("open-edit_method", "children"), Input("open-edit_method", "n_clicks"), prevent_initial_call=True, ) method_read_only = html.Div(default, id="method-read-only") return html.Div(method_read_only, className="slider1")
def spin_system_menu(): """Spin system menu items 1. Add a new spin system 2. Duplicate selected spin system 3. Remove selected spin system ---------------------------------- 4. Clear spin systems """ message_sys = "You are about to delete all spin systems. Do you want to continue?" spin_system_items = [ menu_item(icon_text("fas fa-plus-circle", "Add a new spin system"), id="add_sys"), menu_item(icon_text("fas fa-clone", "Duplicate selection"), id="duplicate_sys"), menu_item(icon_text("fas fa-minus-circle", "Remove selection"), id="remove_sys"), menu_item(divider=True), menu_item(icon_text("", "Clear all spin systems"), id="clear-spin-systems"), dcc.ConfirmDialog(id="confirm-clear-spin-system", message=message_sys), ] # Callbacks for the add, duplicate, and remove spin systems _ = [ app.clientside_callback( f"""function() {{ document.getElementById("{t}-spin-system-button").click(); throw window.dash_clientside.PreventUpdate; }}""", Output(f"{t}-spin-system-button", "n_clicks"), Input(f"{t}_sys", "n_clicks"), prevent_initial_call=True, ) for t in TARGET ] # Callbacks for the clear all spin systems app.clientside_callback( """function(n) { if (n == null) throw window.dash_clientside.PreventUpdate; return true; }""", Output("confirm-clear-spin-system", "displayed"), Input("clear-spin-systems", "n_clicks"), prevent_initial_call=True, ) return create_submenu(label="Spin System", children=spin_system_items, right=True)
def integration_info(): """Text field displaying number of crystallite orientations.""" app.clientside_callback( """function (density, vol) { let ori = (density + 1) * (density + 2)/2; if (vol === 'octant') { return `Averaging over ${ori} orientations.`; } return `Averaging over ${ori*4} orientations.`; }""", Output("integration_points_info", "children"), Input("integration_density", "value"), Input("integration_volume", "value"), prevent_initial_call=False, ) return dbc.Col(dbc.FormText(id="integration_points_info"))
def info_modal_ui(): """Info about features interface""" head = dbc.ModalHeader("Least Squares Fitting Interface Info") body = info_body() foot = dbc.ModalFooter( dbc.Button(id="features-info-modal-close", children="Close")) app.clientside_callback( "function (n1, n2, is_open) { return !is_open; }", Output("features-info-modal", "is_open"), Input("features-info-modal-button", "n_clicks"), Input("features-info-modal-close", "n_clicks"), State("features-info-modal", "is_open"), prevent_initial_call=True, ) return dbc.Modal(id="features-info-modal", children=[head, body, foot])
def download_spectra(): """Button for opening spectra downloads modal""" kwargs = {"outline": True, "color": "dark", "size": "md"} download_btn = custom_button( icon_classname="fas fa-download fa-lg", tooltip="Download Simulation from selected method.", id="open-download-spectra-modal", **kwargs, ) app.clientside_callback( """function (n1, n2, is_open) { return !is_open; }""", Output("download-spectra-modal", "is_open"), Input("open-download-spectra-modal", "n_clicks"), Input("close-download-spectra-modal", "n_clicks"), State("download-spectra-modal", "is_open"), prevent_initial_call=True, ) return download_btn
def isotope_ui(): """Isotope""" label = dbc.InputGroupAddon("Isotope", addon_type="prepend") select = dbc.Select(options=isotope_options_list, value="1H", id="isotope") # callback to hide the quadrupolar fields when isotope is I=1/2 app.clientside_callback( """ function (isotope) { hideQuad(); throw window.dash_clientside.PreventUpdate; } """, Output("isotope", "value"), [Input("isotope", "value")], ) return dbc.InputGroup([label, select], className="input-form")
def about(): title = dbc.ModalHeader("About") def make_row_element(name, link=None, version="", element="td"): link = html.A(name, href=link, target="blank_") if link is not None else name if element == "td": contents = [ html.Td(item) if element == "td" else html.Th(item) for item in [link, version] ] return html.Thead(html.Tr(contents)) table = html.Table([ make_row_element(html.B("Projects"), None, html.B("Version")), make_row_element("Mrsimulator", LINK_MRSIMULATOR_LIB, mrsim_version), make_row_element("Mrsimulator-App", LINK_MRSIMULATOR_APP, mrapp_version), ]) content = [ABOUT_CONTENT, table] modal = dbc.Modal( [title, dbc.ModalBody(content)], size="lg", id="modal-about", role="document", className="modal-dialogue", ) app.clientside_callback( """function (value) { if (value == null) throw window.dash_clientside.PreventUpdate; return true; }""", Output("modal-about", "is_open"), Input("modal-about-button", "n_clicks"), prevent_initial_call=True, ) return modal
def download_session_ui(): """Download session""" session_link = html.A(id="download-session-link", style={"display": "none"}) session_button = custom_button( icon_classname="fas fa-file-download fa-lg", tooltip="Click to download the session", id="download-session-button", className="icon-button", module="html", ) # callback for downloading session app.clientside_callback( ClientsideFunction(namespace="clientside", function_name="downloadSession"), Output("download-session-link", "href"), Input("download-session-button", "n_clicks"), State("local-simulator-data", "data"), prevent_initial_call=True, ) return html.Div([session_link, session_button])
def header(): icon = html.I(className="fac fa-spectrum fa-lg") # help button and associated callback help_button = html.Div( html.I(className="fas fa-question-circle pl-1 fa-lg", title="Show help"), id="pop-up-simulation-button", style={"cursor": "pointer"}, ) app.clientside_callback( "function (n, is_open) { return !is_open; }", Output("modal-simulation-help", "is_open"), Input("pop-up-simulation-button", "n_clicks"), State("modal-simulation-help", "is_open"), prevent_initial_call=True, ) title = html.H4(["Simulation", help_button], className="title-with-help") head = html.Div([icon, title]) return html.Div([head, tools()], className="card-header")
method_selection = dcc.Dropdown(id="method-type", options=METHOD_OPTIONS, value=0) # Channel selection ch_label = dbc.InputGroupAddon("Channel", addon_type="prepend") ch_selection = dbc.Select(options=isotope_options_list, value="1H", id="channel") channel_ui = dbc.InputGroup([ch_label, ch_selection], className="container") # select button button = dbc.Button( "Select", id="close-method-selection", color="dark", className="ml-auto", outline=True, ) app.clientside_callback( "function(n1, n2, is_open) { return !is_open; }", Output("method-modal", "is_open"), Input("add-method-button", "n_clicks"), Input("close-method-selection", "n_clicks"), State("method-modal", "is_open"), prevent_initial_call=True, ) method_selection_modal = dbc.Modal( [head, dbc.ModalBody(method_selection), channel_ui, dbc.ModalFooter(button)], is_open=False, id="method-modal", )
role="document", className="modal-dialogue", backdrop="static", ) modal = ui() app.clientside_callback( """function openModal(n1, n2, data) { let _id = dash_clientside.callback_context.triggered.map((t) => t.prop_id); let trigger_id = _id[0].split(".")[0] let no_update = window.dash_clientside.no_update; if (trigger_id == "close-info-modal") { return [false, no_update, no_update]; } let name = "Title", description = "Sample description"; if (data != null) { name = data["name"]; description = data["description"]; } return [true, name, description]; }""", Output("info-modal-editor", "is_open"), Output("info-name-edit", "value"), Output("info-description-edit", "value"), Input("title-home-button", "n_clicks"), Input("close-info-modal", "n_clicks"), State("local-mrsim-data", "data"), prevent_initial_call=True, )
return newValue triggered_id = [p['prop_id'] for p in ctx.triggered][0] clickedButton_id = triggered_id.split('.')[0] if clickedButton_id and clickedButton_id in menuSubLink2Scroll : return menuSubLink2Scroll.get(clickedButton_id).get('scrollTo') return newValue @app.callback( Output("menu-modal-setting", "is_open"), [Input("menu-modal-setting-open", "n_clicks"), Input("menu-modal-setting-close", "n_clicks")], [State("menu-modal-setting", "is_open")], ) def toggle_modal(n1, n2, is_open): if n1 or n2: return not is_open return is_open app.clientside_callback( # specifiy the callback with ClientsideFunction(<namespace>, <function name>) ClientsideFunction('ui', 'jsFunction'), # the Output, Input and State are passed in as with a regular callback Output('menu-sub-link-output-hidden', 'children'), [Input("menu-sub-link-input", "value")] )
from dash.dependencies import ClientsideFunction, Input, Output from app import app from apps import home, itesm app.layout = html.Div([ dbc.Container([], id='page-content', fluid=True), dcc.Location(id='url', refresh=False), html.Div([], id="hijack-target") ], id="top-container") @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')], prevent_initial_call=True) def display_page(pathname): "Enrutamiento de las páginas" if pathname == '/apps/itesm': return itesm.layout return home.layout app.clientside_callback(ClientsideFunction(namespace="clientside", function_name="scrollHijack"), Output("hijack-target", "n_clicks"), Input('url', 'pathname'), prevent_initial_call=True) if __name__ == '__main__': app.run_server(debug=True, host="0.0.0.0")
if pathname == "/": return 'div-for-nav-white' # Else navbar white return 'div-for-nav-white' # Changing name of app.clientside_callback( """ function(pathname) { if (pathname === '/') { document.title = ' - Home' } else if (pathname === '/sobre_nosotros') { document.title = 'Supplier - Sobre Nosotros' } else if (pathname === '/panorama_estadistico') { document.title = 'Supplier - Panorama Estadístico' } else if (pathname === '/mapa') { document.title = 'Supplier - Mapa' } else if (pathname === '/prediccion') { document.title = 'Supplier - Predicción' } } """, Output('blank-output', 'children'), [Input("url", "pathname")] ) if __name__ == "__main__": app.run_server(debug=True)
# Output('tableauPolicyMandatesMap', 'children'), # [Input('url', 'pathname')] # ) # else: # return 'idk'; # app.callback( # Output('loadingTableauPolicyMandatesMap', 'children'), # Input('url', 'pathname') # )(load_tableau_maps) # clientside callbacks responsible for calling the (java)scripts loading the tableau maps # i chose to use clientside callbacks because everytime we change the view, we need different visualizations to load, causing a lot of overhead app.clientside_callback( ClientsideFunction( namespace='clientsidePolicyMandates', function_name='initPolicyMandatesMap', ), Output('tableauPolicyMandatesMap', 'children'), [Input('url', 'pathname')]) app.clientside_callback( ClientsideFunction( namespace='clientsideReliefFunding', function_name='initReliefFundingMap', ), Output('tableauReliefFundingMap', 'children'), [Input('url', 'pathname')]) app.clientside_callback( ClientsideFunction( namespace='clientsideDemographics', function_name='initDemographicsMap', ), Output('tableauDemographicsMap', 'children'),
# # Scroll up # app.clientside_callback( # """ # var textarea = document.getElementById('results_box'); # textarea.scrollTop = 0 # """, # Output('scroll_top', 'run'), # [Input('forward_button', 'n_clicks'), # Input('back_button', 'n_clicks')] # ) # Display knowledge graph app.clientside_callback(output=Output('viz', 'children'), inputs=[Input('input', 'value')], clientside_function=ClientsideFunction( namespace='clientside', function_name='draw')) @app.callback(Output('input', 'value'), [Input('url', 'search')]) def pre_populate_graph(search): parsed_url = urlparse(search) parsed_search = parse_qs(parsed_url.query, keep_blank_values=True) if parsed_search: print(str(list(parsed_search.keys())[0])) return str(list(parsed_search.keys())[0]) else: raise PreventUpdate @app.callback(Output('input', 'options'), [Input('input', 'value')])
return dash.no_update elif osq is not None: os.environ['osquery_socket'] = osq elif gl2 is not None: os.environ['geolite2_city_db'] = gl2 elif ak is not None: os.environ['abuseipdb_key'] = ak elif gk is not None: os.environ['greynoise_key'] = gk return osq, gl2, ak, gk #need to switch this to config file app.clientside_callback( #https://community.plotly.com/t/dash-bootstrap-theme-switcher/50798/2 """ function(theme) { var stylesheet = document.querySelector('link[rel=stylesheet][href^="https://stackpath"]') var name = theme.toLowerCase() if (name === 'bootstrap') { var link = 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' } else { var link = "https://stackpath.bootstrapcdn.com/bootswatch/4.5.0/" + name + "/bootstrap.min.css" } stylesheet.href = link } """, Output("placeholder", "children"), Input("themes", "value"), )
# -*- coding: utf-8 -*- """ Model page layout and callbacks for advance settings. Advance setting includes: - Integration density: Number of triangles along the edge of octahedron. - Integration volume: Enumeration with literals, 'octant', 'hemisphere'. - Number of sidebands: Number of sidebands to evaluate. """ from dash.dependencies import Input from dash.dependencies import Output from app import app app.clientside_callback( """function (data) { if (data == null) { throw window.dash_clientside.PreventUpdate; } return data.auto_update.toString(); }""", Output("auto-update", "children"), Input("user-config", "data"), prevent_initial_call=True, )
return mapa.layout # if not recognised, return home page return Home.layout # create callback for modifying navbar @app.callback(Output("navbar", "className"), [Input("url", "pathname")]) def display_navbar(pathname): # Navbar white if home if pathname == "/": return 'div-for-nav-white' # Else navbar white return 'div-for-nav-white' # Changing name of app.clientside_callback( """ function(pathname) { if (pathname === '/') { document.title = 'Demo2 - Home' } else if (pathname === '/mapa') { document.title = 'Demo2 - Mapa' } else if (pathname === '/h/') { document.title = 'Demo2 - Home' } } """, Output('blank-output', 'children'), [Input("url", "pathname")]) if __name__ == "__main__": app.run_server(debug=True)
import plotly.express as px import plotly.graph_objs as go from plotly.subplots import make_subplots from app import app from layouts import layout_load_tab, layout_plot_tab # Default Mint Categories cat_path = r"\assets\categories.csv" categories_df = pd.read_csv(cat_path) category_list = list(categories_df.columns) ###### Callback Functions ###### app.clientside_callback( ClientsideFunction(namespace="clientside", function_name="resize"), Output("output-clientside", "children"), [Input("count_graph", "figure")], ) # Update tabs @app.callback([ Output('tabs-content-inline', 'children'), Output('update-btn', 'n_clicks') ], [Input('tabs-styled-with-inline', 'value')]) def display_page(tab): if tab == "Load": layout = layout_load_tab click = 0 elif tab == "Plot": layout = layout_plot_tab
app.clientside_callback( """ function(x) { return getLocation(); } var lat = 0; var lon = 0; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { showPosition('error'); } //return lat+","+lon; return [lat,lon,""]; } function showPosition(position) { if (position=='error') { lat = 0; lon = 0; } else { lat = position.coords.latitude; lon = position.coords.longitude; } } """, Output(component_id='clientside_callback_storage', component_property='data'), [Input(component_id='geojs_lookup_button', component_property='n_clicks')])
"select-method": post_sim_UI.on_method_select, "trigger-sim": simulate_spectrum, "trigger-fit": least_squares_fit, "make-lmfit-params": make_params, } # # convert client-side function # @app.callback( # Output("select-method", "options"), # Input("local-mrsim-data", "data"), # prevent_initial_call=True, # ) # def update_list_of_methods(data): # """Updates the options for selecting a method in the methods tab""" # if data is None: # raise PreventUpdate # if data["methods"] is None: # raise PreventUpdate # options = [ # {"label": f'Method-{i} (Channel-{", ".join(k["channels"])})', "value": i} # for i, k in enumerate(data["methods"]) # ] # return options app.clientside_callback( ClientsideFunction(namespace="clientside", function_name="onReload"), Output("temp0", "children"), Input("local-mrsim-data", "data"), prevent_initial_call=True, )
app.clientside_callback( """ function(pathname) { if (pathname === '/Homepage') { document.title = "Homepage - GLEON GMA Project" } else if (pathname === '/') { document.title = "Homepage - GLEON GMA Project" } else if (pathname === '/FilterData') { document.title = "Filter Graphs - GLEON GMA Project" } else if (pathname === '/About') { document.title = "About - GLEON GMA Project" } else if (pathname === '/Data') { document.title = "Data - GLEON GMA Project" } else if (pathname === '/Contact') { document.title = "Contact - GLEON GMA Project" } else if (pathname === '/Login') { document.title = "Login - GLEON GMA Project" } else if (pathname === '/Upload') { document.title = "Upload - GLEON GMA Project" } else if (pathname === '/UserPage') { document.title = "User's Page - GLEON GMA Project" } else { document.title = "Homepage - GLEON GMA Project" } } """, Output('blank-output', 'children'), [Input('url', 'pathname')] )
]), ]), html.Br(), html.Div(id='page-content'), html.Br(), html.Div(desc.footer, id='footer-text'), html.Div(id='window-width'), html.Div(id='window-height'), ]) # Updates window width div on page update app.clientside_callback( """ function() { return window.innerWidth; } """, Output('window-width', 'children'), Input('url', 'search'), ) # Updates window height div on page update app.clientside_callback( """ function() { return window.innerHeight; } """, Output('window-height', 'children'), Input('url', 'search'), )
report.getLayout(samplePath, isSample=True, name="Sample.txt"), html.Div("sample", id="report-div-type", hidden=True) ] elif ctx.triggered[0]["prop_id"] == "upload-data.contents": dataframes = parse_contents(contents, filename, returnDataframe=True, ukformat=ukformat) return [ report.getLayout(dataframes, name=filename, isDataframes=True), html.Div("uploaded", id="report-div-type", hidden=True) ] else: print("Error reached end of load sample") app.clientside_callback(""" function(clicks, click2, elemid) { document.getElementById(elemid).scrollIntoView({ behavior: 'smooth' }); } """, Output('garbage', 'children'), Input('upload-data', 'contents'), Input("load-sample", "n_clicks"), State('report_div', 'id'), prevent_initial_call=True)
className="tab-scroll method") def signal_processing_tab_ui(): return dbc.Tab( label="Signal Processing", children=post_simulation_ui(1), className="tab-scroll method", ) app.clientside_callback( """function(val) { if (val === 'tab-0') { return [{'display': 'none'}, {'display': 'block'}]; } if (val === 'tab-1') { return [{'display': 'block'}, {'display': 'none'}]; } }""", Output("signal-processor-div", "style"), Output("apply-method-div", "style"), Input("method-tabs", "active_tab"), prevent_initial_call=True, ) def display(): comment = html.H5("Load methods or start creating") icon = html.I(className="fas fa-cube fa-4x") sub_text = html.H6("Add a method") title = html.Span([icon, sub_text], id="open-edit_method") return html.Div([comment, title], className="blank-display") def scrollable():