html.Div( className='row', children=[html.Div(id='output-state', className='col col-12')]), html.Div(className='row', children=[html.Div(id='output-plot', className='col col-12')]) ]) @app.callback( [ Output("loading-1", "loading_state"), Output('output-state', 'children'), Output('output-plot', 'children'), ], [Input('submit-button', 'n_clicks')], [State('search-input', 'value')], ) def update_output_div(n_clicks, input_value): if not input_value: return ({'is_loading': False}, '', '') all_results = search_products_in_mercadolibre({'q': input_value}) USDARS = get_precio_dolar(blue=True, tipo='venta') df_list = [] for result in all_results: if result['currency_id'] == 'ARS': price_in_pesos = result['price'] else: price_in_pesos = result['price'] * USDARS df_list.append({ "id": result["id"],
@app.callback(Output('latency-graph', 'figure'), [Input('update-ticker', 'n_intervals')]) def update_latency(n_intervals): return create_latency_figure() @app.callback(Output('rate-graph', 'figure'), [Input('update-ticker', 'n_intervals')]) def update_rate(n_intervals): return create_rate_figure() @app.callback(Output('coordinate-display', 'children'), [Input('map-graph', 'relayoutData')], [State('coordinate-display', 'children')]) def update_latitude(relayoutData, old_val): if relayoutData and 'mapbox.center' in relayoutData: return 'Coord ({:.3f}, {:.3f})'.format( relayoutData['mapbox.center']['lat'], relayoutData['mapbox.center']['lon']) return old_val @app.callback(Output('map-graph', 'figure'), [ Input('map-graph', 'relayoutData'), Input('update-ticker', 'n_intervals'), Input('category-dropdown', 'value') ], [State('map-graph', 'figure')]) def update_points(relayoutData, n_intervals, category, figure): if relayoutData and 'mapbox.center' in relayoutData:
def states(self): return [State(k, self._states[k]) for k in self._states_order]
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div([ dcc.Input(id='input-1-state', type='text', value='Montréal'), dcc.Input(id='input-2-state', type='text', value='Canada'), html.Button(id='submit-button', n_clicks=0, children='Submit'), html.Div(id='output-state') ]) @app.callback(Output('output-state', 'children'), [Input('submit-button', 'n_clicks')], [State('input-1-state', 'value'), State('input-2-state', 'value')]) def update_output(n_clicks, input2, input1): return u''' The Button has been pressed {} times, Input 1 is "{}", and Input 2 is "{}" '''.format(n_clicks, input1, input2) if __name__ == '__main__': app.run_server(debug=True)
selected_technics = np.array(df_max_salary[tech] == 1) selected_technics_list_max.append(selected_technics) max_filter_list = [ selected_big_occupations_max, selected_small_occupations_max, selected_big_industries_max, selected_small_industries_max ] max_filter_list.extend(selected_technics_list_max) return df_max_salary[np.all(max_filter_list, axis=0)] @app.callback( Output(component_id='display-filter', component_property='children'), [Input(component_id='submit-button', component_property='n_clicks')], [ State('dropdown-big-occupations', 'value'), State('dropdown-small-occupations', 'value'), State('dropdown-big-industries', 'value'), State('dropdown-small-industries', 'value'), State('technics', 'value') ]) def display_filter(n_clicks, big_occupations, small_occupations, big_industries, small_industries, technics): if n_clicks == 0: raise PreventUpdate else: techs = ",".join(technics) return html.Div([ html.H3(children='検索条件'), html.Table(
@app.callback( [ Output("card_img_headwear", "src"), Output("card_img_topwear", "src"), Output("card_img_bottomwear", "src"), Output("card_img_footwear", "src"), Output("store_items_id", "data"), ], [ Input("button_headwear_randomise", "n_clicks"), Input("button_topwear_randomise", "n_clicks"), Input("button_bottomwear_randomise", "n_clicks"), Input("button_footwear_randomise", "n_clicks"), Input("button_generate", "n_clicks"), ], State("store_items_id", "data"), ) def randomise( # when randomise button of one of four cards is clicked button_headwear_randomise_n_clicks, button_topwear_randomise_n_clicks, button_bottomwear_randomise_n_clicks, button_footwear_randomise_n_clicks, button_generate_n_clicks, store_items_id_data, ): if ( # if any of the four randomise buttons are clicked button_headwear_randomise_n_clicks or button_topwear_randomise_n_clicks or button_bottomwear_randomise_n_clicks or
error_message = ( f'The word "{word}" is not in the vocabulary. Please change it.' ) if word == "": error_message = "Input is empty. Please write something." return True, error_message return False, None @app.callback( Output("graph-distance", "figure"), [Input("cytoscape", "tapNodeData"), Input("button-run", "n_clicks")], [ State("input-start", "value"), State("input-plus", "value"), State("input-minus", "value"), ], ) def update_bar(node, n_clicks, start, plus, minus): ctx = dash.callback_context if not ctx.triggered: return None if ctx.triggered[0]["prop_id"] == "button-run.n_clicks": node = {"id": "final", "label": f"{start} - {minus} + {plus}"} if node is None: return px.bar(title="Please tap on a node")
def interactive_layout(app): layout = html.Div([ dcc.Markdown( 'Generate materials properties using propnet in your browser, ' 'without needing to download any code.'), dcc.Markdown('## input data'), dcc.Markdown( 'You can also pre-populate input data from the Materials Project ' 'database by entering a formula or Materials Project ID:'), html.Div([dcc.Input( placeholder='Enter a formula or mp-id...', type='text', value='', id='query-input', style={"width": "40%", "display": "inline-block", "vertical-align": "middle"} ), html.Button('Load data from Materials Project', id='submit-query', style={"display": "inline-block", "vertical-align": "middle"}), html.Button('Clear', id='clear-mp', style={"display": "inline-block", "vertical-align": "middle"}) ]), html.Br(), html.Div(children=[dt.DataTable(id='mp-table', rows=[{'Property': None, 'Materials Project Value': None}], editable=False)], id='mp-container'), dcc.Store(id='mp-data', storage_type='memory'), html.Br(), dcc.Markdown( 'You can also enter your own values of properties below. If units are not ' 'specified, default propnet units will be assigned, but you can ' 'also enter your own units.'), dt.DataTable(id='input-table', rows=DEFAULT_ROWS), html.Br(), dcc.Markdown('## propnet-derived output'), dcc.Markdown('Properties derived by propnet will be show below. If there are multiple ' 'values for the same property, you can choose to aggregate them together.' '' '' 'In the graph, input properties are in green and derived properties in ' 'yellow. Properties shown in grey require additional information to derive.'), dcc.Checklist(id='aggregate', options=[{'label': 'Aggregate', 'value': 'aggregate'}], values=['aggregate'], style={'display': 'inline-block'}), html.Br(), html.Div(id='propnet-output') ]) @app.callback(Output('mp-data', 'data'), [Input('submit-query', 'n_clicks'), Input('query-input', 'n_submit')], [State('query-input', 'value')]) def retrieve_material(n_clicks, n_submit, query): if (n_clicks is None) and (n_submit is None): raise PreventUpdate if query.startswith("mp-") or query.startswith("mvc-"): mpid = query else: mpid = MPR.get_mpid_from_formula(query) material = MPR.get_material_for_mpid(mpid) if not material: raise PreventUpdate logger.info("Retrieved material {} for formula {}".format( mpid, material['pretty_formula'])) mp_quantities = {quantity.symbol.display_names[0]: quantity.as_dict() for quantity in material.get_quantities()} return json.dumps(mp_quantities, cls=MontyEncoder) @app.callback( Output('mp-container', 'style'), [Input('mp-data', 'data')] ) def show_mp_table(data): if (data is None) or (len(data) == 0): return {'display': 'none'} else: return {} @app.callback( Output('mp-table', 'rows'), [Input('mp-data', 'data')] ) def show_mp_table(data): if (data is None) or (len(data) == 0): raise PreventUpdate mp_quantities = json.loads(data, cls=MontyDecoder) output_rows = [ { 'Property': symbol_string, 'Materials Project Value': quantity.pretty_string(3) } for symbol_string, quantity in mp_quantities.items() ] return output_rows @app.callback(Output('storage', 'clear_data'), [Input('clear-mp', 'n_clicks')]) def clear_data(n_clicks): if n_clicks is None: raise PreventUpdate return True @app.callback( Output('propnet-output', 'children'), [Input('input-table', 'rows'), Input('mp-data', 'data'), Input('aggregate', 'values')] ) def evaluate(input_rows, data, aggregate): quantities = [Quantity(symbol_type=ROW_IDX_TO_SYMBOL_NAME[idx], value=ureg.parse_expression(row['Editable Value'])) for idx, row in enumerate(input_rows) if row['Editable Value']] if data and len(data) > 0: quantities += json.loads(data, cls=MontyDecoder).values() if not quantities: raise PreventUpdate material = Material() for quantity in quantities: material.add_quantity(quantity) graph = Graph() output_material = graph.evaluate(material) if aggregate: output_quantities = output_material.get_aggregated_quantities().values() else: output_quantities = output_material.get_quantities() output_rows = [{ 'Property': quantity.symbol.display_names[0], 'Value': quantity.pretty_string(3) } for quantity in output_quantities] output_table = dt.DataTable(id='output-table', rows=output_rows, editable=False) # TODO: clean up input_quantity_names = [q.symbol.name for q in quantities] derived_quantity_names = set( [q.symbol.name for q in output_quantities]) - \ set(input_quantity_names) material_graph_data = graph_conversion( graph.get_networkx_graph(), nodes_to_highlight_green=input_quantity_names, nodes_to_highlight_yellow=list(derived_quantity_names)) options = AESTHETICS['global_options'] options['edges']['color'] = '#000000' output_graph = html.Div(GraphComponent( id='material-graph', graph=material_graph_data, options=options ), style={'width': '100%', 'height': '400px'}) return [ output_graph, html.Br(), output_table ] return layout
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State app = dash.Dash() app.layout = html.Div([ dcc.Input( id='number-in', value=1, style={'fontSize':28} ), html.Button( id='submit-button', n_clicks=0, children='Submit', style={'fontSize':28} ), html.H1(id='number-out') ]) @app.callback( Output('number-out', 'children'), [Input('submit-button', 'n_clicks')], [State('number-in', 'value')]) def output(n_clicks, number): return number if __name__ == '__main__': app.run_server()
# if isinstance(value, dict): # return value['hex'] # else: # return value #@app.callback(Output('canvas-color', 'lineWidth'), # [Input('bg-width-slider', 'value')]) #def update_canvas_linewidth(value): # return value @app.callback([Output('download-a', 'href'), Output('download-a', 'download')], [Input('download-a', 'n_clicks')], [State('memory', 'data')]) def download(inp, data): if (inp is None) or (inp%3==0): raise PreventUpdate df = pd.DataFrame(data) csv_string = df.to_csv(encoding='utf-8', float_format='%.4g') csv_string = "data:text/csv;charset=utf-8,%EF%BB%BF" + urllib.parse.quote(csv_string) return csv_string, f"{time.strftime('%m/%d_%H:%M:%S')}.csv" @app.callback([Output('memory', 'data'), Output('canvas-table', 'data')], [Input('canvas', 'json_data')]) def update_data(string): if string: data = json.loads(string)
'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold', 'fontSize':16 }, style_table={ 'maxHeight': '55ex', 'overflowY': 'scroll', 'width': '100%' },) ]) @app.callback( [Output('trends_over_time','figure'), Output('keyword_correlations','figure')], [Input('submit_trends','n_clicks')], [State('keyword_list','value'), State('timeframe','value'), State('geo','value')]) def update_trends_and_corrs(n_clicks,kw_list,timeframe,geo): if n_clicks is not None: keywords = [a.strip() for a in kw_list.split(',')] df_trends = get_trends_over_time(keywords,timeframe,geo) df_corr = get_keyword_correlations(keywords,timeframe,geo) mylayout_trends = go.Layout(title="Google Search Trends - {}".format(geo), yaxis_title='Index Ranking') fig_trends = go.Figure(layout=mylayout_trends) for keyword in df_trends['keyword'].unique(): fig_trends.add_scatter(x = df_trends[df_trends['keyword'] == keyword]['date'], y = df_trends[df_trends['keyword'] == keyword]['value'], name = keyword, mode = 'lines') x = list(df_corr.columns) y = list(df_corr.columns)
################################ # ---------------------------- # Data and Figures update callback # ---------------------------- @app.callback([ Output('histogram', 'figure'), Output('mediana-choque', component_property='children'), Output('lorenz', 'figure'), Output('pobreza-choque', component_property='children') ], [Input('apply-button', 'n_clicks'), Input('reference-lines', 'value')], state=[ State('sectores', 'value'), State('shock', 'value'), State('empresa', 'value'), State('formalidad', 'value'), State('contrato', 'value') ]) def update_tabs(n_clicks, reference_lines, selected_sectors, shock, empresa, formalidad, contrato): # descriptive statistics mediana_choque = 'No choque' texto_mediana = 'Mediana choque: {}'.format(mediana_choque) pobreza_choque = 'No choque' texto_pobreza = u'Índice de pobreza choque: {}'.format(pobreza_choque) # get context
}] value = 'stock' labelStyle = {'display': 'block'} return options, value, labelStyle @app.callback([ Output('dropdown1_label', 'children'), Output('dropdown1', 'options'), Output('dropdown1', 'value'), Output('dropdown2_label', 'children'), Output('dropdown2', 'options'), Output('dropdown2', 'value') ], [Input('categories', 'value'), Input('radio', 'value')], [State('dropdown1', 'value'), State('dropdown2', 'value')]) def update_dropdown_options(selected_category, selected_fin_type, drop1, drop2): if selected_category == 'cat-1': ### Twitter Sentiment if drop1 in queries[1:] or drop2 in moons[1:]: raise PreventUpdate else: dropdown1_label = 'Select a Twitter Search Phrase:' options1 = [{'label': i, 'value': i} for i in queries] value1 = '(no keywords entered)' dropdown2_label = 'Select a Moon Phase:' options2 = [{'label': i, 'value': i} for i in moons] value2 = 'No Phase' return dropdown1_label, options1, value1, dropdown2_label, options2, value2 elif selected_category == 'cat-2': ### Financial Markets
def multi_parameter_controller(parent: WebvizErtPluginABC, app: dash.Dash) -> None: @app.callback( Output({ "index": MATCH, "type": parent.uuid("bincount-store") }, "data"), [ Input({ "index": MATCH, "type": parent.uuid("hist-bincount") }, "value") ], [ State({ "index": MATCH, "type": parent.uuid("bincount-store") }, "data") ], ) def update_bincount(hist_bincount: int, store_bincount: int) -> int: if not isinstance(hist_bincount, int): raise PreventUpdate if hist_bincount < 2: raise PreventUpdate if hist_bincount == store_bincount: raise PreventUpdate return hist_bincount @app.callback( [ Output( { "index": MATCH, "id": parent.uuid("parameter-scatter"), "type": parent.uuid("graph"), }, "figure", ), Output({ "index": MATCH, "type": parent.uuid("hist-bincount") }, "value"), ], [ Input({ "index": MATCH, "type": parent.uuid("hist-check") }, "value"), Input( { "index": MATCH, "type": parent.uuid("bincount-store") }, "modified_timestamp", ), Input(parent.uuid("ensemble-selection-store"), "modified_timestamp"), Input(parent.uuid("param-label-check"), "value"), ], [ State(parent.uuid("ensemble-selection-store"), "data"), State({ "index": MATCH, "type": parent.uuid("parameter-id-store") }, "data"), State({ "index": MATCH, "type": parent.uuid("bincount-store") }, "data"), ], ) def update_histogram( hist_check_values: List[str], _: Any, __: Any, legend: List[str], selected_ensembles: Optional[Mapping[str, Dict]], parameter: str, bin_count: int, ) -> Tuple[go.Figure, int]: if not selected_ensembles: raise PreventUpdate data = {} colors = {} names = {} priors = {} for ensemble_id, color in selected_ensembles.items(): ensemble = load_ensemble(parent, ensemble_id) if ensemble.parameters and parameter in ensemble.parameters: key = str(ensemble) parameter_model = ensemble.parameters[parameter] data[key] = parameter_model.data_df() colors[key] = color["color"] names[key] = key if "label" in legend else "" if parameter_model.priors and "prior" in hist_check_values: priors[names[key]] = (parameter_model.priors, colors[key]) parameter_plot = MultiHistogramPlotModel( data, names=names, colors=colors, hist="hist" in hist_check_values, kde="kde" in hist_check_values, priors=priors, bin_count=bin_count, ) return parameter_plot.repr, parameter_plot.bin_count @app.callback( Output({ "index": MATCH, "type": parent.uuid("hist-check") }, "options"), [ Input({ "index": MATCH, "type": parent.uuid("parameter-id-store") }, "data"), ], [ State({ "index": MATCH, "type": parent.uuid("hist-check") }, "options"), State(parent.uuid("ensemble-selection-store"), "data"), ], ) def set_parameter_from_btn( parameter: str, plotting_options: List[Mapping[str, str]], selected_ensembles: Optional[Mapping[str, Dict]], ) -> List[Mapping[str, str]]: if not selected_ensembles: raise PreventUpdate has_priors = False for ensemble_id, _ in selected_ensembles.items(): ensemble = load_ensemble(parent, ensemble_id) if ensemble.parameters and parameter in ensemble.parameters: parameter_model = ensemble.parameters[parameter] if parameter_model.priors: has_priors = True break prior_option = {"label": "prior", "value": "prior"} if has_priors and prior_option not in plotting_options: plotting_options.append(prior_option) if not has_priors and prior_option in plotting_options: plotting_options.remove(prior_option) return plotting_options
def add_dash(server): # Setup the app app = dash.Dash( __name__, server=server, suppress_callback_exceptions=True, url_base_pathname=URL_BASE, meta_tags=[{ "name": "viewport", "content": "width=device-width" }], ) # get relative data folder PATH = pathlib.Path(__file__).parent DATA_PATH = PATH.joinpath("data").resolve() app.layout = html.Div( [ dcc.Store(id="click-output"), html.Div( [ html.Div([ html.Div([ html.Img( src=app.get_asset_url("dash-logo.png"), className="plotly-logo", ) ]), dcc.Markdown( """ ### A View of a Chart That Predicts The Economic Future: ### The Yield Curve """.replace(" ", ""), className="title", ), dcc.Markdown( """This interactive report is a rendition of a [New York Times original](https://www.nytimes.com/interactive/2015/03/19/upshot/3d-yield-curve-economic-growth.html).""" .replace(" ", ""), className="subtitle", ), ]), html.Div( [ html.A( html.Button("Learn More", className="learn-more-button"), href="https://plot.ly/dash/pricing/", target="_blank", ) ], className="info-button", ), html.Div( [ dcc.Slider( min=0, max=5, value=0, marks={i: "".format(i + 1) for i in range(6)}, id="slider", ) ], className="timeline-slider", ), html.Div( [ html.Button( "Back", id="back", style={"display": "inline-block"}, n_clicks=0, ), html.Button( "Next", id="next", style={ "display": "inline-block", "marginLeft": "10px" }, n_clicks=0, ), ], className="page-buttons", ), ], className="four columns sidebar", ), html.Div( [ html.Div([dcc.Markdown(id="text")], className="text-box"), dcc.Graph(id="graph", style={ "margin": "0px 20px", "height": "45vh" }), ], id="page", className="eight columns", ), ], className="row flex-display", style={"height": "100vh"}, ) df = pd.read_csv(DATA_PATH.joinpath("yield_curve.csv")) xlist = list(df["x"].dropna()) ylist = list(df["y"].dropna()) del df["x"] del df["y"] zlist = [] for row in df.iterrows(): index, data = row zlist.append(data.tolist()) UPS = { 0: dict(x=0, y=0, z=1), 1: dict(x=0, y=0, z=1), 2: dict(x=0, y=0, z=1), 3: dict(x=0, y=0, z=1), 4: dict(x=0, y=0, z=1), 5: dict(x=0, y=0, z=1), } CENTERS = { 0: dict(x=0.3, y=0.8, z=-0.5), 1: dict(x=0, y=0, z=-0.37), 2: dict(x=0, y=1.1, z=-1.3), 3: dict(x=0, y=-0.7, z=0), 4: dict(x=0, y=-0.2, z=0), 5: dict(x=-0.11, y=-0.5, z=0), } EYES = { 0: dict(x=2.7, y=2.7, z=0.3), 1: dict(x=0.01, y=3.8, z=-0.37), 2: dict(x=1.3, y=3, z=0), 3: dict(x=2.6, y=-1.6, z=0), 4: dict(x=3, y=-0.2, z=0), 5: dict(x=-0.1, y=-0.5, z=2.66), } TEXTS = { 0: """ ##### Yield curve 101 The yield curve shows how much it costs the federal government to borrow money for a given amount of time, revealing the relationship between long- and short-term interest rates. It is, inherently, a forecast for what the economy holds in the future — how much inflation there will be, for example, and how healthy growth will be over the years ahead — all embodied in the price of money today, tomorrow and many years from now. """.replace(" ", ""), 1: """ ##### Where we stand On Wednesday, both short-term and long-term rates were lower than they have been for most of history – a reflection of the continuing hangover from the financial crisis. The yield curve is fairly flat, which is a sign that investors expect mediocre growth in the years ahead. """.replace(" ", ""), 2: """ ##### Deep in the valley In response to the last recession, the Federal Reserve has kept short-term rates very low — near zero — since 2008. (Lower interest rates stimulate the economy, by making it cheaper for people to borrow money, but also spark inflation.) Now, the Fed is getting ready to raise rates again, possibly as early as June. """.replace(" ", ""), 3: """ ##### Last time, a puzzle The last time the Fed started raising rates was in 2004. From 2004 to 2006, short-term rates rose steadily. But long-term rates didn't rise very much. The Federal Reserve chairman called this phenomenon a “conundrum," and it raised questions about the ability of the Fed to guide the economy. Part of the reason long-term rates failed to rise was because of strong foreign demand. """.replace(" ", ""), 4: """ ##### Long-term rates are low now, too Foreign buyers have helped keep long-term rates low recently, too — as have new rules encouraging banks to hold government debt and expectations that economic growth could be weak for a long time. The 10-year Treasury yield was as low as it has ever been in July 2012 and has risen only modestly since. Some economists refer to the economic pessimism as “the new normal.” """.replace(" ", ""), 5: """ ##### Long-term rates are low now, too Here is the same chart viewed from above. """.replace(" ", ""), } ANNOTATIONS = { 0: [], 1: [ dict( showarrow=False, x="1-month", y="2015-03-18", z=0.046, text= "Short-term rates basically <br>follow the interest rates set <br>by the Federal Reserve.", xref="x", yref="y", zref="z", xanchor="left", yanchor="auto", ) ], 2: [], 3: [], 4: [], 5: [], } # Make 3d graph @app.callback(Output("graph", "figure"), [Input("slider", "value")]) def make_graph(value): if value is None: value = 0 if value in [0, 2, 3]: z_secondary_beginning = [z[1] for z in zlist if z[0] == "None"] z_secondary_end = [z[0] for z in zlist if z[0] != "None"] z_secondary = z_secondary_beginning + z_secondary_end x_secondary = ["3-month"] * len( z_secondary_beginning) + ["1-month"] * len(z_secondary_end) y_secondary = ylist opacity = 0.7 elif value == 1: x_secondary = xlist y_secondary = [ylist[-1] for i in xlist] z_secondary = zlist[-1] opacity = 0.7 elif value == 4: z_secondary = [z[8] for z in zlist] x_secondary = ["10-year" for i in z_secondary] y_secondary = ylist opacity = 0.25 if value in range(0, 5): trace1 = dict( type="surface", x=xlist, y=ylist, z=zlist, hoverinfo="x+y+z", lighting={ "ambient": 0.95, "diffuse": 0.99, "fresnel": 0.01, "roughness": 0.01, "specular": 0.01, }, colorscale=[ [0, "rgb(230,245,254)"], [0.4, "rgb(123,171,203)"], [0.8, "rgb(40,119,174)"], [1, "rgb(37,61,81)"], ], opacity=opacity, showscale=False, zmax=9.18, zmin=0, scene="scene", ) trace2 = dict( type="scatter3d", mode="lines", x=x_secondary, y=y_secondary, z=z_secondary, hoverinfo="x+y+z", line=dict(color="#444444"), ) data = [trace1, trace2] else: trace1 = dict( type="contour", x=ylist, y=xlist, z=np.array(zlist).T, colorscale=[ [0, "rgb(230,245,254)"], [0.4, "rgb(123,171,203)"], [0.8, "rgb(40,119,174)"], [1, "rgb(37,61,81)"], ], showscale=False, zmax=9.18, zmin=0, line=dict(smoothing=1, color="rgba(40,40,40,0.15)"), contours=dict(coloring="heatmap"), ) data = [trace1] layout = dict( autosize=True, font=dict(size=12, color="#CCCCCC"), margin=dict(t=5, l=5, b=5, r=5), showlegend=False, hovermode="closest", scene=dict( aspectmode="manual", aspectratio=dict(x=2, y=5, z=1.5), camera=dict(up=UPS[value], center=CENTERS[value], eye=EYES[value]), annotations=[ dict( showarrow=False, y="2015-03-18", x="1-month", z=0.046, text="Point 1", xanchor="left", xshift=10, opacity=0.7, ), dict( y="2015-03-18", x="3-month", z=0.048, text="Point 2", textangle=0, ax=0, ay=-75, font=dict(color="black", size=12), arrowcolor="black", arrowsize=3, arrowwidth=1, arrowhead=1, ), ], xaxis={ "showgrid": True, "title": "", "type": "category", "zeroline": False, "categoryorder": "array", "categoryarray": list(reversed(xlist)), }, yaxis={ "showgrid": True, "title": "", "type": "date", "zeroline": False, }, ), ) figure = dict(data=data, layout=layout) return figure # Make annotations @app.callback(Output("text", "children"), [Input("slider", "value")]) def make_text(value): if value is None: value = 0 return TEXTS[value] # Button controls @app.callback( [Output("slider", "value"), Output("click-output", "data")], [Input("back", "n_clicks"), Input("next", "n_clicks")], [State("slider", "value"), State("click-output", "data")], ) def advance_slider(back, nxt, slider, last_history): try: if back > last_history["back"]: last_history["back"] = back return max(0, slider - 1), last_history if nxt > last_history["next"]: last_history["next"] = nxt return min(5, slider + 1), last_history # if last_history store is None except Exception as error: last_history = {"back": 0, "next": 0} return slider, last_history return server
return {'display': 'block'} else: return {'display': 'none'} return display_tab for tab in ['tab-1', 'tab-2']: app.callback(Output(tab, 'style'), [Input('url', 'pathname')])(generate_display_tab(tab)) @app.callback( Output(component_id='output-graph', component_property='children'), [Input(component_id='input', component_property='value')], [State('input_url', 'value')]) def update_value(input1, input2): try: cleanid = get_vid_id(str(input2)) selenium_link = make_watch_link(cleanid) cache_lasttimestamp, cache_captionsd = search_cache(cleanid) if not cache_lasttimestamp and not cache_captionsd: print("we gots to runs seleny") pull_transcript(selenium_link, cleanid) # if captions_present == "No": # print('RRRRRRRRRRRRRRRRRRRrrr') # return html.P(children='Your word is not in the video.', style={ # 'textAlign': 'left', })
def parse_contents(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) if 'csv' in filename: # Assume that the user uploaded a CSV file return pd.read_csv(io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: # Assume that the user uploaded an excel file return pd.read_excel(io.BytesIO(decoded)) @app.callback(Output('datatable-upload-container', 'data'), [Input('datatable-upload', 'contents')], [State('datatable-upload', 'filename')]) def update_output(contents, filename): if contents is None: return [{}] df = parse_contents(contents, filename) return df.to_dict('rows') @app.callback(Output('datatable-upload-graph', 'figure'), [Input('datatable-upload-container', 'data')]) def display_graph(rows): df = pd.DataFrame(rows) return { 'data': [{ 'x': df[df.columns[0]], 'y': df[df.columns[1]],
elif pathname == "/map-analysis": return map_analysis.layout elif pathname == "/changepoint-analysis": return changepoint_analysis.layout # If the user tries to reach a different page, return a 404 message return dbc.Jumbotron([ html.H1("404: Not found", className="text-danger"), html.Hr(), html.P(f"The pathname {pathname} was not recognised..."), ]) @app.callback( Output("sidebar", "className"), [Input("sidebar-toggle", "n_clicks")], [State("sidebar", "className")], ) def toggle_classname(n, classname): if n and classname == "navbar-dark bg-primary": return "navbar-dark bg-primary collapsed" return "navbar-dark bg-primary" @app.callback( Output("collapse", "is_open"), [Input("navbar-toggle", "n_clicks")], [State("collapse", "is_open")], ) def toggle_collapse(n, is_open): if n: return not is_open
from dash.exceptions import PreventUpdate from grid2viz.app import app import pandas as pd from ..utils.graph_utils import relayout_callback, get_axis_relayout from ..utils import common_graph from grid2kpi.episode import observation_model, EpisodeTrace from ..manager import make_episode, best_agents @app.callback(Output("relayoutStoreOverview", "data"), [ Input("input_env_charts", "relayoutData"), Input("usage_rate_graph", "relayoutData"), Input("overflow_graph", "relayoutData") ], [State("relayoutStoreOverview", "data")]) def relayout_store_overview(*args): return relayout_callback(*args) @app.callback([ Output("input_assets_selector", "options"), Output("input_assets_selector", "value") ], [Input("scen_overview_ts_switch", "value")], [State('scenario', 'data')]) def update_ts_graph_avail_assets(kind, scenario): """ Change the selector's options according to the kind of trace selected. Triggered when user click on one of the input in the scen_overview_ts_switch component in overview layout. """
[search_bar],className="ml-auto", navbar=True ), id="navbar-collapse", navbar=True, ), ], fluid=True, ), color="#2c6693", dark=True, ) @app.callback( Output("navbar-collapse", "is_open"), [Input("navbar-toggler", "n_clicks")], [State("navbar-collapse", "is_open")], ) def toggle_navbar_collapse(n, is_open): if n: return not is_open return is_open # the style arguments for the sidebar. We use position:fixed and a fixed width SIDEBAR_STYLE = { "position": "fixed", "top": 60, "left": 0, "bottom": 0, "width": "16rem",
def create_callback(): # noqa: MC0001 global CALLBACK_CREATED if not CALLBACK_CREATED: @dash_app.callback(Output('trips_map', 'figure'), Output('consumption_fig', 'figure'), Output('consumption_fig_by_speed', 'figure'), Output('consumption_graph_by_temp', 'children'), Output('summary-cards', 'children'), Output('tab_trips_fig', 'children'), Output('tab_charge', 'children'), Output('date-slider', 'max'), Output('date-slider', 'step'), Output('date-slider', 'marks'), Input('date-slider', 'value')) def display_value(value): # pylint: disable=unused-variable mini = datetime.fromtimestamp(value[0], tz=timezone.utc) maxi = datetime.fromtimestamp(value[1], tz=timezone.utc) filtered_trips = Trips() for trip in trips: if mini <= trip.start_at <= maxi: filtered_trips.append(trip) filtered_chargings = Charging.get_chargings(mini, maxi) figures.get_figures(filtered_trips, filtered_chargings) return figures.trips_map, figures.consumption_fig, figures.consumption_fig_by_speed, \ figures.consumption_graph_by_temp, create_card(figures.SUMMARY_CARDS), \ figures.table_fig, figures.battery_table, max_millis, step, marks @dash_app.callback(Output(EMPTY_DIV, "children"), [Input("battery-table", "data_timestamp")], [State("battery-table", "data"), State("battery-table", "data_previous")]) def capture_diffs_in_battery_table(timestamp, data, data_previous): # pylint: disable=unused-variable if timestamp is None: raise PreventUpdate diff_data = diff_dashtable(data, data_previous, "start_at") for changed_line in diff_data: if changed_line['column_name'] == 'price': conn = Database.get_db() if not Database.set_chargings_price( conn, changed_line['start_at'], changed_line['current_value']): logger.error("Can't find line to update in the database") conn.close() return "" @dash_app.callback([Output("tab_battery_popup_graph", "children"), Output("tab_battery_popup", "is_open"), ], [Input("battery-table", "active_cell"), Input("tab_battery_popup-close", "n_clicks")], [State('battery-table', 'data'), State("tab_battery_popup", "is_open")]) def get_battery_curve(active_cell, close, data, is_open): # pylint: disable=unused-argument, unused-variable if is_open is None: is_open = False if active_cell is not None and active_cell["column_id"] in ["start_level", "end_level"] and not is_open: row = data[active_cell["row"]] return figures.get_battery_curve_fig(row, myp.vehicles_list[0]), True return "", False @dash_app.callback([Output("tab_trips_popup_graph", "children"), Output("tab_trips_popup", "is_open"), ], [Input("trips-table", "active_cell"), Input("tab_trips_popup-close", "n_clicks")], State("tab_trips_popup", "is_open")) def get_altitude(active_cell, close, is_open): # pylint: disable=unused-argument, unused-variable if is_open is None: is_open = False if active_cell is not None and active_cell["column_id"] in ["altitude_diff"] and not is_open: return figures.get_altitude_fig(trips[active_cell["row_id"] - 1]), True return "", False CALLBACK_CREATED = True
def create_figure(column_x, column_y, country): chart_type = px.line if column_x == 'year' else px.scatter return chart_type( df.query("country == '{}'".format(country)), x=column_x, y=column_y, )\ .update_layout( title='{} {} vs {}'.format(country, column_x, column_y), margin_l=10, margin_r=0, margin_b=30)\ .update_xaxes(title_text='').update_yaxes(title_text='') @app.callback( Output('container', 'children'), [Input('add-chart', 'n_clicks')], [State('container', 'children'), State('country', 'value')]) def display_dropdowns(n_clicks, children, country): default_column_x = 'year' default_column_y = 'gdpPercap' new_element = html.Div( style={'width': '23%', 'display': 'inline-block', 'outline': 'thin lightgrey solid', 'padding': 10}, children=[ dcc.Graph( id={ 'type': 'dynamic-output', 'index': n_clicks }, style={'height': 300}, figure=create_figure(default_column_x, default_column_y, country)
'background-color': '#f9f9f9', 'height': '30px', 'width': '100%', 'padding':' 8px 0 0', 'text-align':'center' }) ],style={}) @app.callback(Output('live-update-graph', 'children'), [Input(component_id="sub-btn",component_property="n_clicks" )], [State('my_inp','value')] ) def update_graph_live(n_clicks,n): if (len(n)!=0): global graph graph = tf.compat.v1.get_default_graph() model = load_model('Sentiment_LSTM_model.h5') MAX_SEQUENCE_LENGTH = 300 # Twitter auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth,wait_on_rate_limit=True) with open('tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle)
]) @app.callback(Output("button_code", "n_clicks"), [Input('url', 'pathname')]) def callbacks(none): return @app.callback([ Output("box_1", "children"), Output("box_2", "children"), Output("box_3", "children"), Output("box_4", "children"), Output("box_5", "children") ], [Input('button_code', 'n_clicks')], [State('year_slider', 'value'), State('country_drop', 'value')]) def callbacks(n_clicks_1, year, country_list): bot_year = year[0] top_year = year[1] boxes = f.cpv_box(bot_year, top_year, country_list) print('Queried cpv Boxes') box_1 = boxes[0] box_2 = boxes[1] box_3 = boxes[2] box_4 = boxes[3] box_5 = boxes[4] return str(box_1) + '€', \ str(box_2), \
Output(component_id, 'molStyles'), Output('pdb-dropdown', 'options'), Output('uploaded-files', 'data'), Output('pdb-dropdown', 'placeholder'), Output('warning_div', 'children'), Output('pdb-string', 'invalid') ], [ Input('pdb-dropdown', 'value'), Input('ngl-upload-data', 'contents'), Input('btn-pdbString', 'n_clicks'), Input('btn-resetView', 'n_clicks'), Input('molecules-representation-style', 'value'), ], [ State('pdb-string', 'value'), State('pdb-dropdown', 'options'), State('uploaded-files', 'data'), State('molecules-chain-color', 'value'), State('chosen-atoms-color', 'value'), State('chosen-atoms-radius', 'value'), State('molecules-xaxis-spacing', 'value'), State('sideByside-selector', 'value') ], ) def display_output(selection, uploaded_content, pdbString_clicks, resetView_clicks, molStyles_list, pdbString, dropdown_options, files, colors, chosenAtomsColor, chosenAtomsRadius, molSpacing_xAxis, sideByside_text): print('selection,pdbString_clicks,pdbString,type uploaded_content', 'files')
"angularaxis": { "showline": False, "tickcolor": "white" }, }, showlegend=False, ) return go.Figure(data=data, layout=layout) @app.callback( Output("wind-histogram", "figure"), [Input("wind-speed-update", "n_intervals")], [ State("wind-speed", "figure"), State("bin-slider", "value"), State("bin-auto", "values"), ], ) def gen_wind_histogram(interval, wind_speed_figure, slider_value, auto_state): """ Genererate wind histogram graph. :params interval: upadte the graph based on an interval :params wind_speed_figure: current wind speed graph :params slider_value: current slider value :params auto_state: current auto state """ wind_val = []
def generate_callbacks(self, app, cache): @app.callback( Output(self.id("graph"), "data"), [ Input(self.id("graph_generation_options"), "data"), Input(self.id("unit-cell-choice"), "value"), Input(self.id(), "data"), ], ) def update_graph(graph_generation_options, unit_cell_choice, struct_or_mol): if not struct_or_mol: raise PreventUpdate struct_or_mol = self.from_data(struct_or_mol) graph_generation_options = self.from_data(graph_generation_options) if isinstance(struct_or_mol, Structure): if unit_cell_choice != "input": if unit_cell_choice == "primitive": struct_or_mol = struct_or_mol.get_primitive_structure() elif unit_cell_choice == "conventional": sga = SpacegroupAnalyzer(struct_or_mol) struct_or_mol = sga.get_conventional_standard_structure( ) elif unit_cell_choice == "reduced": struct_or_mol = struct_or_mol.get_reduced_structure() graph = self._preprocess_input_to_graph( struct_or_mol, bonding_strategy=graph_generation_options["bonding_strategy"], bonding_strategy_kwargs=graph_generation_options[ "bonding_strategy_kwargs"], ) self.logger.debug("Constructed graph") return self.to_data(graph) @app.callback( Output(self.id("scene"), "data"), [ Input(self.id("graph"), "data"), Input(self.id("display_options"), "data"), ], ) def update_scene(graph, display_options): display_options = self.from_data(display_options) graph = self.from_data(graph) scene, legend = self.get_scene_and_legend(graph, **display_options) return scene.to_json() @app.callback( Output(self.id("legend_data"), "data"), [ Input(self.id("graph"), "data"), Input(self.id("display_options"), "data"), ], ) def update_legend(graph, display_options): # TODO: more cleanly split legend from scene generation display_options = self.from_data(display_options) graph = self.from_data(graph) struct_or_mol = self._get_struct_or_mol(graph) site_prop_types = self._analyze_site_props(struct_or_mol) colors, legend = self._get_display_colors_and_legend_for_sites( struct_or_mol, site_prop_types, color_scheme=display_options.get("color_scheme", None), color_scale=display_options.get("color_scale", None), ) return self.to_data(legend) @app.callback( Output(self.id("color-scheme"), "options"), [Input(self.id("graph"), "data")], ) def update_color_options(graph): options = [ { "label": "Jmol", "value": "Jmol" }, { "label": "VESTA", "value": "VESTA" }, { "label": "Colorblind-friendly", "value": "colorblind_friendly" }, ] graph = self.from_data(graph) struct_or_mol = self._get_struct_or_mol(graph) site_props = self._analyze_site_props(struct_or_mol) for site_prop_type in ("scalar", "categorical"): if site_prop_type in site_props: for prop in site_props[site_prop_type]: options += [{ "label": f"Site property: {prop}", "value": prop }] return options @app.callback( Output(self.id("display_options"), "data"), [ Input(self.id("color-scheme"), "value"), Input(self.id("radius_strategy"), "value"), Input(self.id("draw_options"), "value"), ], [State(self.id("display_options"), "data")], ) def update_display_options(color_scheme, radius_strategy, draw_options, display_options): display_options = self.from_data(display_options) display_options.update({"color_scheme": color_scheme}) display_options.update({"radius_strategy": radius_strategy}) display_options.update( {"draw_image_atoms": "draw_image_atoms" in draw_options}) display_options.update({ "bonded_sites_outside_unit_cell": "bonded_sites_outside_unit_cell" in draw_options }) display_options.update({ "hide_incomplete_bonds": "hide_incomplete_bonds" in draw_options }) if display_options == self.initial_display_options: raise PreventUpdate self.logger.debug("Display options updated") return self.to_data(display_options) @app.callback( Output(self.id("scene"), "downloadRequest"), [Input(self.id("screenshot_button"), "n_clicks")], [ State(self.id("scene"), "downloadRequest"), State(self.id(), "data") ], ) def screenshot_callback(n_clicks, current_requests, struct_or_mol): if n_clicks is None: raise PreventUpdate struct_or_mol = self.from_data(struct_or_mol) # TODO: this will break if store is structure/molecule graph ... formula = struct_or_mol.composition.reduced_formula if hasattr(struct_or_mol, "get_space_group_info"): spgrp = struct_or_mol.get_space_group_info()[0] else: spgrp = "" request_filename = "{}-{}-crystal-toolkit.png".format( formula, spgrp) if not current_requests: n_requests = 1 else: n_requests = current_requests["n_requests"] + 1 return { "n_requests": n_requests, "filename": request_filename, "filetype": "png", } @app.callback( Output(self.id("scene"), "toggleVisibility"), [Input(self.id("hide-show"), "value")], [State(self.id("hide-show"), "options")], ) def update_visibility(values, options): visibility = { opt["value"]: (opt["value"] in values) for opt in options } return visibility @app.callback( [ Output(self.id("legend_container"), "children"), Output(self.id("title_container"), "children"), ], [Input(self.id("legend_data"), "data")], ) def update_legend(legend): legend = self.from_data(legend) if legend == self.initial_legend: raise PreventUpdate return self._make_legend(legend), self._make_title(legend) @app.callback( Output(self.id("graph_generation_options"), "data"), [ Input(self.id("bonding_algorithm"), "value"), Input(self.id("bonding_algorithm_custom_cutoffs"), "data"), ], ) def update_structure_viewer_data(bonding_algorithm, custom_cutoffs_rows): graph_generation_options = { "bonding_strategy": bonding_algorithm, "bonding_strategy_kwargs": None, } if graph_generation_options == self.initial_graph_generation_options: raise PreventUpdate if bonding_algorithm == "CutOffDictNN": # this is not the format CutOffDictNN expects (since that is not JSON # serializable), so we store as a list of tuples instead # TODO: make CutOffDictNN args JSON serializable custom_cutoffs = [(row["A"], row["B"], float(row["A—B"])) for row in custom_cutoffs_rows] graph_generation_options["bonding_strategy_kwargs"] = { "cut_off_dict": custom_cutoffs } return self.to_data(graph_generation_options) @app.callback( [ Output(self.id("bonding_algorithm_custom_cutoffs"), "data"), Output(self.id("bonding_algorithm_custom_cutoffs_container"), "style"), ], [Input(self.id("bonding_algorithm"), "value")], [State(self.id("graph"), "data")], ) def update_custom_bond_options(bonding_algorithm, graph): if not graph: raise PreventUpdate if bonding_algorithm == "CutOffDictNN": style = {} else: style = {"display": "none"} graph = self.from_data(graph) struct_or_mol = self._get_struct_or_mol(graph) # can't use type_of_specie because it doesn't work with disordered structures species = set( map( str, chain.from_iterable([ list(c.keys()) for c in struct_or_mol.species_and_occu ]), )) rows = [{ "A": combination[0], "B": combination[1], "A—B": 0 } for combination in combinations_with_replacement(species, 2)] return rows, style
html.Div(children=[dcc.Graph(id='map')]), html.Div(children=[dcc.Graph(id='ward-bars')]), html.A('Download Data', id='download-link', download="rawdata.csv", href="", target="_blank"), html.Div(children=[ dash_table.DataTable(id='table', columns=FORMAT_COLS, sorting=True) ]) ]) @app.callback(Output('download-link', 'href'), [Input('my-id', 'n_submit'), Input('ward-select', 'value')], [State('my-id', 'value')]) def update_download_link(ns, ward_list, name_string): dff = generate_table(ward_list, name_string) csv_string = dff.to_csv(index=False, encoding='utf-8') csv_string = "data:text/csv;charset=utf-8," + urllib.parse.quote( csv_string) return csv_string @app.callback(Output('ward-bars', 'figure'), [Input('my-id', 'n_submit'), Input('ward-select', 'value')], [State('my-id', 'value')]) def update_bars(ns, ward_list, name_string): if ward_list == None: ward_list = all_wards
def callbacks(_app): @_app.callback( Output('oncoprint-store', 'data'), [ Input('oncoprint-padding-input', 'value'), Input('oncoprint-colorscale-mutation-dropdown', 'value'), Input('oncoprint-mutation-color', 'value'), ], [ State('oncoprint-store', 'data'), ], ) def update_data_store(padding_val, mut_type, mut_col, stored_data): if stored_data is None: stored_data = { PADDING_KEY: '', COLORSCALE_KEY: {}, TRIGGER_KEY: '', } if mut_col is None or 'hex' not in mut_col.keys(): mut_col = {'hex': stored_data[COLORSCALE_KEY][mut_type]} mut_col = mut_col['hex'] if padding_val != stored_data[PADDING_KEY]: stored_data[PADDING_KEY] = padding_val stored_data[TRIGGER_KEY] = PADDING_KEY if mut_type not in stored_data[COLORSCALE_KEY]: stored_data[COLORSCALE_KEY][mut_type] = mut_col else: if mut_col != stored_data[COLORSCALE_KEY][mut_type]: stored_data[COLORSCALE_KEY][mut_type] = mut_col stored_data[TRIGGER_KEY] = COLORSCALE_COL_KEY else: stored_data[TRIGGER_KEY] = COLORSCALE_MUT_KEY return stored_data # Handle event data @_app.callback( Output("oncoprint-events", "children"), [Input("oncoprint-chart", "eventDatum")], ) def event_data_select(data): if data is not None and len(str(data)) > 0: data = json.loads(data) return [ html.Div('{}: {}'.format( str( key.replace('eventType', 'event type').replace( 'curveNumber', 'curve number').title()), str(data[key]).replace('<br>', ' - '))) for key in data.keys() ] return 'Hover over or click on a data point on the graph \ to see it here.' # Render main chart @_app.callback( Output('oncoprint-chart', 'data'), [Input('oncoprint-dropdown', 'value')], ) def update_chart(dropdown): return DATASETS[dropdown] # Customization callbacks @_app.callback( Output('oncoprint-chart', 'showlegend'), [Input('oncoprint-show-legend', 'value')], ) def toggle_legend(val): return val @_app.callback( Output('oncoprint-chart', 'showoverview'), [Input('oncoprint-show-overview', 'value')], ) def toggle_overview(val): return val @_app.callback( Output('oncoprint-chart', 'backgroundcolor'), [Input('oncoprint-tracks-color', 'value')], ) def change_tracks_colors(val): if val is not None and 'hex' in val.keys(): return val['hex'] return '#AAAAAA' @_app.callback( Output('oncoprint-chart', 'padding'), [Input('oncoprint-store', 'data')], ) def change_padding(data): return data[PADDING_KEY] @_app.callback( Output('oncoprint-chart', 'colorscale'), [Input('oncoprint-store', 'data')], ) def update_colorscale(data): return data[COLORSCALE_KEY]
), dcc.Input( id='enddate-input', type='Date', value=dt.date.today() ), html.Button(id='submit-button', n_clicks=0, children='Submit'), dcc.Graph(id='task_bar_graph'), dcc.Graph(id='task_line_graph'), ]) # 日付を入力 @app.callback( Output('task_bar_graph', 'figure'), [Input('submit-button', 'n_clicks')], [State('startdate-input', 'value'), State('enddate-input', 'value')]) def update_task_bar_graph(n_clicks, start_date, end_date): df = get_jira_tasks(start_date, end_date) task_info = df.groupby(['name']).sum() graph = { 'data': [ { 'x': task_info.index, 'y': list(task_info.loc[:, "timeoriginalestimate"]), 'type': 'bar', 'name': '予' }, { 'x': task_info.index,