コード例 #1
0
                ],
                id="testtableright")
        ],
        id="overall_table")
])


#CALLBACKSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
@app.callback(
    Output("remind-collapse", "is_open"),
    [
        Input("remind_table", "selected_cells"),
        Input("remind_table", "n_clicks"),
        Input("left", "n_clicks")
    ],
    [State("remind-collapse", "is_open")],
)
def toggle_left(d1, d2, btn, is_open):
    if d1:
        return not is_open

    if btn:
        return not is_open
    return is_open


@app.callback(Output("c_remind_table", "data"), [
    Input("remind_table", "selected_cells"),
    Input("remind_table", "derived_virtual_data")
])
def client_remind_table_link(t1, t2):
コード例 #2
0
@app.callback(
    Output('output-serverside', 'children'),
    [Input('eventloop', 'n_intervals')])
def update_output(value):
    return f'Server says {datetime.datetime.now().isoformat()}'



app.clientside_callback(
    ClientsideFunction(
        namespace='clientside',
        function_name='update_timer'
    ),
    Output('output-clientside', 'children'),
    [Input('eventloop', 'n_intervals')]
)

app.clientside_callback(
    ClientsideFunction(
        namespace='clientside',
        function_name='uuid'
    ),
    Output('uuid', 'children'),
    [Input('eventloop', 'n_intervals')],
    [State('uuid', 'children')])



if __name__ == "__main__":
    app_state(app, )
    app.run_server(port=8070)
コード例 #3
0
            dcc.Dropdown(
                id='dropdown-db',
                # optionss=[],
                placeholder="Databases",
                value=None),
            html.Button(id='connect-to-db', type='Connect', children='Load DB')
        ],
        className='row'),
    html.Div(children=[], id='db-infobox'),
])


@app.callback(
    Output('dropdown-db', 'options'),
    [Input('connect-to-mongo', 'n_clicks')],
    [State('databaseName', 'value')],
)
def update_connection(n, v):
    db.MONGO_URL = v
    # print("db url", db.MONGO_URL)
    db.connect_client()
    # print('dbclient', db.MONGO_CL)
    if db.MONGO_CL is not None:
        dropdowns = [{
            'label': i['name'],
            'value': i['name']
        } for i in db.MONGO_CL.list_databases()]
    else:
        dropdowns = [{'label': " ", 'value': 0}]
    # print(dropdowns)
    return dropdowns
コード例 #4
0
        dash_table.DataTable(
            data=df.to_dict('records'),
            columns=[{'name': i, 'id': i} for i in df.columns]
        ),

        html.Hr(),  # horizontal line

        # For debugging, display the raw contents provided by the web browser
        html.Div('Raw Content'),
        html.Pre(contents[0:200] + '...', style={
            'whiteSpace': 'pre-wrap',
            'wordBreak': 'break-all'
        })
    ])


@app.callback(Output('output-data-upload', 'children'),
              Input('upload-data', 'contents'),
              State('upload-data', 'filename'),
              State('upload-data', 'last_modified'))
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)]
        return children



if __name__ == '__main__':
    app.run_server(debug=True)
コード例 #5
0
                    dcc.Input(placeholder='Enter your password',
                              type='password',
                              id='pwd-box'),
                    html.Button(children='Login',
                                n_clicks=0,
                                type='submit',
                                id='login-button'),
                    html.Div(children='', id='output-state')
                ]),
        ])
])


@app.callback(Output('url_login',
                     'pathname'), [Input('login-button', 'n_clicks')],
              [State('uname-box', 'value'),
               State('pwd-box', 'value')])
def sucess(n_clicks, input1, input2):
    user = User.query.filter_by(username=input1).first()
    if user:
        if check_password_hash(user.password, input2):
            login_user(user)
            return '/success'
        else:
            pass
    else:
        pass


@app.callback(Output('output-state',
                     'children'), [Input('login-button', 'n_clicks')],
コード例 #6
0
               target='_blank',
               children=html.Img(
                   id='bmac-image',
                   src="https://i.ibb.co/x6KTCf9/bmc-icon-black.png",
                   width=58,
                   height=40))
    ]),
    dcc.Store(
        id='session',
        storage_type='session',
        data={'last_click': datetime.datetime.now().timestamp() - CLICK_DELAY})
])


@app.callback(Output('session', 'data'), Input('update-button', 'n_clicks'),
              State('session', 'data'))
def update_button_timer(n_clicks, data):
    """Checks if enough time has passed between update requests

    Args:
        n_clicks: how many updates requested by user
        data: dictionary of json data stored in user's browser - in this case it stores the time the last click was
              requested, and it was accepted.

    Raises
        dash.exceptions.PreventUpdate: If not enough time has passed between requests and updates

    Returns:
        Dictionary with key 'last_click' and the timestamp of the last click that was allowed
    """
    if n_clicks is None:
コード例 #7
0
ファイル: app.py プロジェクト: djbiega/MFP-Dash-App
        html.Div(
            [
                build_line_plot_container(),
                build_data_table_container(), 
                html.P(id='blank-space', style={'height': '300px'}),
                html.Div(id='hidden-data', style={'display': 'none'})
            ]
        )
    ]
)

@app.callback(
    [Output('dbc-validate-username', 'children'),
    Output('dbc-validate-username', 'is_open')],
    [Input('submit-button', 'n_clicks')],
    state=[State('mfp-username', 'value')]
)
def check_username(click, username):
    if not click or not username:
        raise PreventUpdate
    valid = only_public_profiles.check_username(username)
    if valid:
        return username, False
    return 'Invalid Username', True


@app.callback(
    Output('hidden-data', 'children'),
    [Input('dbc-validate-username', 'children'),
    Input('submit-button', 'n_clicks')],
    state=[
コード例 #8
0
ファイル: app.py プロジェクト: Cradoux/target_attention
})

app.css.append_css({
    'external_url': (
        "https://codepen.io/mikesmith1611/pen/QOKgpG.css"
    )

})

app.layout = serve_layout()


@app.callback(
    Output('overview', 'figure'),
    [Input('subbutton', 'n_clicks'), Input('overview', 'clickData')],
    [State('peak_current', 'value'), State('category-filter', 'value')])
def filter(n_clicks, selected_value, range_value, category_filter):
    if selected_value is None:
        filter_li = category_filter
        filter_li = [f for f in filter_li if f is not None]
        df_filtered = df_targets[
            (df_targets['peak_to_current'] > range_value[0]) & (df_targets['peak_to_current'] < range_value[1])]
    else:
        target = selected_value['points'][0]['text'].split('\n')[0]
        filter_li = [target]
        df_filtered = df_targets
    figure = create_figure(
        df_filtered,
        filter_li if len(filter_li) > 0 else None,
        skip_labels=['-'],
        min_val=range_value[0],
コード例 #9
0
ファイル: app.py プロジェクト: ToniVinuales/linaxrepoup
            l=40
        ),
        showlegend=False,
        radialaxis=dict(
            range=[0, max(max(df['Speed']), 40)]
        ),
        angularaxis=dict(
            showline=False,
            tickcolor='white'
        ),
        orientation=270,
    )
    return Figure(data=[trace, trace1, trace2], layout=layout)
@app.callback(Output('wind-histogram', 'figure'),
              [],
              [State('wind-speed', 'figure'),
               State('bin-slider', 'value'),
               State('bin-auto', 'values')],
              [Event('wind-speed-update', 'interval')])
def gen_wind_histogram(wind_speed_figure, sliderValue, auto_state):
#def gen_wind_histogram(wind_speed_figure, sliderValue):
    wind_val = []
    # Check to see whether wind-speed has been plotted yet
    if wind_speed_figure is not None:
        wind_val = wind_speed_figure['data'][0]['y']
    if 'Auto' in auto_state:
        bin_val = np.histogram(wind_val, bins=range(int(round(min(wind_val))),
                               int(round(max(wind_val)))))
    else:
        bin_val = np.histogram(wind_val, bins=sliderValue)
コード例 #10
0
#     if data:
#         print("TSTING SESSION")
#         print(data["test"])
#         return data["test"]


#Metrics Banners
@app.callback([
    Output("ytd", "children"),
    Output("1d", "children"),
    Output("5d", "children"),
    Output("1m", "children"),
    Output("6m", "children"),
    Output("12m", "children")
], [Input("session", "data"),
    Input("search-button", "n_clicks")], [State("input", "value")])
def banner(ses_data, search_btn, search):
    if search_btn:
        tdf = yf.Ticker(search)
    elif ses_data:
        tdf = yf.Ticker(ses_data["test"])
    else:
        tdf = yf.Ticker("aapl")

    hist = tdf.history(period="1mo", interval="1d")
    d1 = ((hist["Close"].iloc[-1] - hist["Close"].iloc[-2]) /
          hist["Close"].iloc[-1] * 100).round(2)
    d5 = ((hist["Close"].iloc[-1] - hist["Close"].iloc[-6]) /
          hist["Close"].iloc[-1] * 100).round(2)
    m1 = ((hist["Close"].iloc[-1] - hist["Close"].iloc[1]) /
          hist["Close"].iloc[-1] * 100).round(2)
コード例 #11
0
ファイル: consensustable.py プロジェクト: meoke/pangtreevis
    return partial_consensustable_data.to_dict("rows")


@app.callback(Output(id_consensuses_table, 'columns'),
              [Input(id_partial_consensustable_hidden, 'children')])
def update_columns(jsonified_partial_consensustable):
    if not jsonified_partial_consensustable:
        return [{}]
    partial_consensustable_data = tools.unjsonify_df(
        jsonified_partial_consensustable)
    return [{"name": i, "id": i} for i in partial_consensustable_data.columns]


@app.callback(Output(id_consensuses_table, 'style_data_conditional'),
              [Input(id_partial_consensustable_hidden, 'children')],
              [State(id_full_consensustree_hidden, 'children')])
def color_consensuses_table_cells(jsonified_partial_consensustable,
                                  jsonified_consensus_tree):
    if not jsonified_partial_consensustable or not jsonified_consensus_tree:
        return []
    partial_consensustable_data = tools.unjsonify_df(
        jsonified_partial_consensustable)
    consensustree_data = tools.unjsonify_builtin_types(
        jsonified_consensus_tree)
    tree = consensustree.dict_to_tree(consensustree_data)

    return consensustable.get_cells_styling(tree, partial_consensustable_data)


@app.callback(Output("consensus_table_container", 'style'),
              [Input(id_full_consensustable_hidden, 'children')])
コード例 #12
0

@app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
    if pathname in ["/", "/page-1"]:
        return html.P("This is the content of page 1!")
    elif pathname == "/page-2":
        return html.P("This is the content of page 2. Yay!")
    elif pathname == "/page-3":
        return html.P("Oh cool, this is page 3!")
    # 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("collapse", "is_open"),
    [Input("toggle", "n_clicks")],
    [State("collapse", "is_open")],
)
def toggle_collapse(n, is_open):
    if n:
        return not is_open
    return is_open


if __name__ == "__main__":
    app.run_server(debug=True)
コード例 #13
0
            #print(insertSQL)
            #this can then be executed with an INSERT INTO statement to insert data into said table
            countAdd = cursor.execute(insertSQL)
            connectionAdd.commit()
            #after the commit it needs to be closed as well as the connection
            cursor.close()
            connectionAdd.close()
            return "Your account has been created! Click Back to login"

    return


#createExercise page callbacks
@fitman.callback(dash.dependencies.Output('form-end', 'children'),
                 [Input('submit-btn', 'n_clicks')], [
                     State('createExercise-exercise', 'value'),
                     State('createExercise-date-picker', 'date'),
                     State('createExercise-length-slider', 'value'),
                     State('createExercise-intensity-slider', 'value')
                 ])
#state refers to the state of the str and orders them
def addExerciseToDatabase(n_clicks, exerciseValue, dateStr, lengthValue,
                          intensityValue):

    if n_clicks > 0:

        connectionAdd = sqlite3.connect("C:\\Users\\Duugz\\FitMan\\fitman.db")
        cursor = connectionAdd.cursor()

        #not really sure why this works, but sometimes the date would appear with time. This stopped that.
コード例 #14
0
    if end_date.date() < datetime.today().date():
        print('The update is needless for the data selected.')
        return 'no'
    else:
        no_update


# Dash can't have the same Input and Output
# Save the data as json file in cache
@app.callback([
    Output('before-log-storage', 'children'),
    Output('num-before-storage', 'children')
], [
    Input('date_range', 'start_date'),
    Input('date_range', 'end_date'),
    State('before-log-storage', 'children'),
    State('num-before-storage', 'children')
])
def get_before_log(start_date, end_date, before, num_before):
    try:
        end_date = datetime.strptime(end_date, r'%Y-%m-%d')
        start_date = datetime.strptime(start_date, r'%Y-%m-%d')
    except TypeError as error:
        print(error)
        print("Start day and end day have wrong filetype.")
        return no_update, no_update
    else:
        try:
            if end_date.date() < datetime.today().date():
                storage_end_date = end_date
                run_log_df = get_data_str(start_date, storage_end_date,
コード例 #15
0
@app.callback(Output('output-data-upload-new', 'children'), [
    Input('upload-data-new', 'contents'),
    Input('upload-data-new', 'filename')
])
def print_output_new(contents, filename):
    """
    Callback Function to print the output of the uploaded data. 
    Calls parse_data to return the output
    """
    return [parse_data(contents, filename)]


@app.callback(Output('export-files-button', 'children'),
              [Input('button-export', 'n_clicks')],
              state=[State('input-learning-cycle', 'value')])
def XCS_Export(n_clicks, value):
    """
    Callback Function to export the Result file and Rule population. 
    Executed from the button and takes input the iteration Input
    """

    while n_clicks > 0:
        pd.DataFrame(result, index=[0]).to_csv(u'Export\Results.csv')
        print 'Accuracy file exported'
        #Figure out the iteration stops for evaluation, and the max iterations.
        iterList, lastIter = iterFunc(value)

        txtToExcel(textData='PopulationOutput.%d.txt' % lastIter,
                   excelData='Export\PopulationOutput_%d_run.xlsx' % n_clicks,
                   excelSheet='%d_run' % n_clicks)
コード例 #16
0
    else:
        return ""

#Bruger mediawiki API wbgetclaims til at hente claims fra en item
@app.callback(
    Output("properties-output", "children"),
    Input("input-2", "value"),
)
def extract_properties(input2):
    return retrieve_properties(input2)

#Properties and Values Input: https://dash.plotly.com/dash-core-components/dropdown (Dynamic Options)
@app.callback(
    Output("properties_dropdown-container", "children"),
    Input("add-filter", "n_clicks"),
    State('properties_dropdown-container', 'children'),
)
def display_dropdowns_properties(n_clicks, children):
    new_dropdown = dcc.Dropdown(
            id={
                'type': 'property_filter-dropdown',
                'index': n_clicks
            },
            options=[{"label": i, "value": i} for i in ["P31", "P17", "P51", "P69", "P420"]],
            placeholder = "Select a Property...",
            style={"margin-top": "5px"}
        )
    children.append(new_dropdown)
    return children

@app.callback(
コード例 #17
0
ファイル: project.py プロジェクト: rohilzalke1995/dash-plotly
body = html.Div(
    dbc.Row([
        dbc.Col(html.Div(card)),
        dbc.Col(html.Div(cardtwo)),
        dbc.Col(html.Div(card3))
    ]))

#main layout
app.layout = html.Div([navbar, body])


#navbar
@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


#dropdown call back
@app.callback(Output('output-container', 'children'),
              [Input('my-dropdown', 'value')])
def update_output(value):
    NYC_img = enconde_image(
        'https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fcincoveces.files.wordpress.com%2F2011%2F08%2Fnycpan2.jpg&f=1&nofb=1'
    )
    TX_img = enconde_image(
コード例 #18
0
ファイル: app.py プロジェクト: romanshaimar/dash-sample-apps2
                )
    else:
        for study in study_data.study_id.unique():
            options.append({"label": study, "value": study})

    options.sort(key=lambda item: item["label"])
    value = options[0]["value"] if options else None

    return error_status, error_message, options, value


# Callback to generate study data
@app.callback(
    Output("plot", "figure"),
    [Input("chart-type", "value"), Input("study-dropdown", "value")],
    [State("upload-data", "contents"), State("error", "data")],
)
def update_output(chart_type, study, contents, error):
    if study is None:
        return {}

    if error or not contents:
        study_data = default_study_data
    else:
        content_type, content_string = contents.split(",")
        decoded = base64.b64decode(content_string)
        study_data = pd.read_csv(io.StringIO(decoded.decode("utf-8")))

    study_data["reading_value"] = pd.to_numeric(
        study_data["reading_value"], errors="coerce"
    )
コード例 #19
0
ファイル: __main__.py プロジェクト: bmeg/grip-query
    if pathname == "/" or pathname == "/query":
        return query_view.setup(graphs)
    elif pathname == "/facet":
        return facet_view.setup(graphs)

    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):
    '''Side menu state'''
    if n and classname == "":
        return "collapsed"
    return ""


@app.callback(Output("collapse",
                     "is_open"), [Input("navbar-toggle", "n_clicks")],
              [State("collapse", "is_open")])
def toggle_collapse(n, is_open):
    '''Side menu'''
    if n:
        return not is_open
    return is_open
コード例 #20
0
ファイル: app.py プロジェクト: HiIamJeff/covid19-curves-in-US
        output2 = create_real_map()
    return output2


## outdated
# def goplot2(button_info):
#     changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
#     output2 = create_real_map()
#     return output2


@app.callback(
    Output(component_id='output-graph3', component_property='figure'),
    # [Input('button1', 'n_clicks'), Input('button2', 'n_clicks')],
    [Input('button', 'n_clicks')],
    [State(component_id='state_selection', component_property='value')],
)
def goplot3(button, state_selection):
    # make sure it won't generate blank plot by itself and show error
    if not state_selection:
        return no_update  # This is prevent the web run the function without any input
    else:
        output3 = create_trend_line(df_case_std_row, state_selection)
    return output3


# n_clicks is required for click event
if __name__ == '__main__':
    app.run_server(debug=True)

#### NOTE ####
コード例 #21
0
ファイル: power.py プロジェクト: snowind/fitly
# Group power profiles
@app.callback([Output('power-profile-5-chart', 'figure'),
               Output('power-profile-60-chart', 'figure'),
               Output('power-profile-300-chart', 'figure'),
               Output('power-profile-1200-chart', 'figure'),
               Output('day-button', 'style'),
               Output('week-button', 'style'),
               Output('month-button', 'style'),
               Output('year-button', 'style'), ],
              [Input('activity-type-toggle', 'value'),
               Input('power-unit-toggle', 'value'),
               Input('day-button', 'n_clicks'),
               Input('week-button', 'n_clicks'),
               Input('month-button', 'n_clicks'),
               Input('year-button', 'n_clicks')],
              [State('day-button', 'n_clicks_timestamp'),
               State('week-button', 'n_clicks_timestamp'),
               State('month-button', 'n_clicks_timestamp'),
               State('year-button', 'n_clicks_timestamp')]
              )
def update_power_profiles(activity_type, power_unit, day_n_clicks, week_n_clicks, month_n_clicks, year_n_clicks,
                          day_n_clicks_timestamp, week_n_clicks_timestamp, month_n_clicks_timestamp,
                          year_n_clicks_timestamp):
    latest = 'month'
    power_unit = 'watts_per_kg' if power_unit else 'mmp'
    activity_type = 'run' if activity_type else 'ride'

    day_style, week_style, month_style, year_style = {'marginRight': '1%'}, {'marginRight': '1%'}, {
        'marginRight': '1%'}, {'marginRight': '1%'}
    day_n_clicks_timestamp = 0 if not day_n_clicks_timestamp else day_n_clicks_timestamp
    week_n_clicks_timestamp = 0 if not week_n_clicks_timestamp else week_n_clicks_timestamp
コード例 #22
0
ファイル: test_integration.py プロジェクト: zuoxiaolei/dash
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
コード例 #23
0
                    style={
                        'fontSize': 24,
                        'marginLeft': '30px'
                    }),
    ],
             style={'display': 'inline-block'}),
    dcc.Graph(id='my_graph', figure={'data': [{
        'x': [1, 2],
        'y': [3, 1]
    }]})
])


@app.callback(Output('my_graph', 'figure'),
              [Input('submit-button', 'n_clicks')], [
                  State('my_ticker_symbol', 'value'),
                  State('my_date_picker', 'start_date'),
                  State('my_date_picker', 'end_date')
              ])
def update_graph(n_clicks, stock_ticker, start_date, end_date):
    start = datetime.strptime(start_date[:10], '%Y-%m-%d')
    end = datetime.strptime(end_date[:10], '%Y-%m-%d')
    traces = []
    for tic in stock_ticker:
        df = web.get_data_tiingo(
            tic,
            start,
            end,
            api_key="efcb8226f45a832dae79835ef5d42dd427a53cfb")
        traces.append({
            'x': df.index.get_level_values(1),
コード例 #24
0
ファイル: test_integration.py プロジェクト: zuoxiaolei/dash
def test_inin013_no_update_chains(dash_duo):
    app = Dash(__name__)

    app.layout = html.Div([
        dcc.Input(id="a_in", value="a"),
        dcc.Input(id="b_in", value="b"),
        html.P("", id="a_out"),
        html.P("", id="a_out_short"),
        html.P("", id="b_out"),
        html.P("", id="ab_out"),
    ])

    @app.callback(
        [Output("a_out", "children"),
         Output("a_out_short", "children")],
        [Input("a_in", "value")],
    )
    def a_out(a):
        return (a, a if len(a) < 3 else no_update)

    @app.callback(Output("b_out", "children"), [Input("b_in", "value")])
    def b_out(b):
        return b

    @app.callback(
        Output("ab_out", "children"),
        [Input("a_out_short", "children")],
        [State("b_out", "children")],
    )
    def ab_out(a, b):
        return a + " " + b

    dash_duo.start_server(app)

    a_in = dash_duo.find_element("#a_in")
    b_in = dash_duo.find_element("#b_in")

    b_in.send_keys("b")
    a_in.send_keys("a")
    dash_duo.wait_for_text_to_equal("#a_out", "aa")
    dash_duo.wait_for_text_to_equal("#b_out", "bb")
    dash_duo.wait_for_text_to_equal("#a_out_short", "aa")
    dash_duo.wait_for_text_to_equal("#ab_out", "aa bb")

    b_in.send_keys("b")
    a_in.send_keys("a")
    dash_duo.wait_for_text_to_equal("#a_out", "aaa")
    dash_duo.wait_for_text_to_equal("#b_out", "bbb")
    dash_duo.wait_for_text_to_equal("#a_out_short", "aa")
    # ab_out has not been triggered because a_out_short received no_update
    dash_duo.wait_for_text_to_equal("#ab_out", "aa bb")

    b_in.send_keys("b")
    a_in.send_keys(Keys.END)
    a_in.send_keys(Keys.BACKSPACE)
    dash_duo.wait_for_text_to_equal("#a_out", "aa")
    dash_duo.wait_for_text_to_equal("#b_out", "bbbb")
    dash_duo.wait_for_text_to_equal("#a_out_short", "aa")
    # now ab_out *is* triggered - a_out_short got a new value
    # even though that value is the same as the last value it got
    dash_duo.wait_for_text_to_equal("#ab_out", "aa bbbb")
コード例 #25
0
    ),
]

app.layout = html.Div(grid)
server = app.server  # for deployment


@app.callback(
    [
        Output("company-profile-card", "children"),
        Output("company-summary-card", "children"),
        Output("period-radio-item", "value"),
        Output("company-tick-graph", "selectedData"),
    ],
    [Input("symbol-input", "value")],
    State("period-radio-item", "value"),
)
def symbol_input(symbol, curr_radio):

    ticker = yf.Ticker(symbol)

    name = ticker.info.get("longName", "")
    location = f"{ticker.info.get('city', '')}, {ticker.info.get('state', '')}"
    logo_url = ticker.info.get(
        "logo_url",
        "https://dash-bootstrap-components.opensource.faculty.ai/static/images/placeholder286x180.png",
    )
    if logo_url == "":
        logo_url = "https://dash-bootstrap-components.opensource.faculty.ai/static/images/placeholder286x180.png"
    summary = ticker.info.get("longBusinessSummary", "")
    company_card = make_company_card(name, location, logo_url, summary)
コード例 #26
0
    return outputs

@app.callback(Output('file-download-csv', 'href'),
              [Input('output-data-id', 'data')])
def file_download_csv_href(fileid):
    return url_for('data.download_file', fileid=fileid, format='csv')

@app.callback(Output('file-download-excel', 'href'),
              [Input('output-data-id', 'data')])
def file_download_excel_href(fileid):
    return url_for('data.download_file', fileid=fileid, format='xlsx')


@app.callback(Output('whats-next', 'children'),
              [Input('dashboard-output', 'children')],
              [State('output-data-id', 'data')])
def what_next_missing_fields(_, fileid):
    df = get_filtered_df(fileid)

    if df is None:
        return []

    missing = []
    if (df["__geo_ctry"].count() + df["__geo_rgn"].count()) == 0:
        missing.append(["postcodes or other geo data",
                        "https://postcodes.findthatcharity.uk/"])

    org_type = CHARTS['org_type']['get_results'](df)
    if "Identifier not recognised" in org_type.index and len(org_type.index)==1:
        missing.append(["external organisation identifiers, like charity numbers",
                        'http://standard.threesixtygiving.org/en/latest/identifiers/#id2'])
コード例 #27
0
ファイル: app.py プロジェクト: nitinai/MoneyMantra
                        A('Twitter',
                          href=
                          'https://twitter.com/intent/tweet?source=webclient&text=%40_nitinp',
                          target='_blank')
                    ]),
                ],
                id='my-footer',
            ),
        ],
        className="all_content"),  # excluding the title bar
])


@app.callback(Output('world_countries_table', 'data'),
              [Input('editing-rows-button', 'n_clicks')], [
                  State('world_countries_table', 'data'),
                  State('world_countries_table', 'columns')
              ])
def add_row(n_clicks, rows, columns):
    if n_clicks > 0:
        rows.append({c['id']: '' for c in columns})
    return rows


@app.callback(Output('save_table_btn_msg', 'children'),
              [Input('save_table_button', 'n_clicks')], [
                  State('world_countries_table', 'data'),
                  State('world_countries_table', 'columns')
              ])
def add_row(n_clicks, data, columns):
    msg = ""
コード例 #28
0
ファイル: app_molecule3d.py プロジェクト: stjordanis/dash-bio
def callbacks(app):  # pylint: disable=redefined-outer-name
    @app.callback(Output('mol3d-data-info', 'children'),
                  [Input('dropdown-demostr', 'value')])
    def show_data(molecule_selected):
        if molecule_selected in data_info.keys():
            mol = data_info[molecule_selected]
            return [
                html.H4(mol['name']), mol['description'],
                html.A('(source)', href=mol['link'])
            ]
        return ''

    @app.callback(Output('dropdown-demostr',
                         'value'), [Input('mol3d-upload-data', 'contents')],
                  [State('dropdown-demostr', 'value')])
    def reset_dropdown(upload_content, dem):
        if upload_content is not None:
            return None
        return dem

    # Callback for updating dropdown options
    @app.callback(Output('mol3d-coloring-key', 'options'),
                  [Input('dropdown-style-color', 'value')])
    def update_color_options(mol_style):
        color_dict_keys = {
            'atom': list(sparser.ATOM_COLOR_DICT.keys()),
            'residue': list(sparser.RESIDUE_COLOR_DICT.keys()),
            'residue_type': list(sparser.RESIDUE_TYPE_COLOR_DICT.keys()),
            'chain': list(sparser.CHAIN_COLOR_DICT.keys())
        }

        options = [{
            'label': k.upper(),
            'value': k
        } for k in color_dict_keys[mol_style]]

        return options

    @app.callback(Output('mol3d-color-storage', 'data'), [
        Input('mol3d-coloring-value', 'value'),
        Input('dropdown-style-color', 'value')
    ],
                  state=[
                      State('mol3d-coloring-key', 'value'),
                      State('mol3d-color-storage', 'data')
                  ])
    def update_color_dict(color_value, color_style, color_key, current):

        if color_style is None:
            return {}

        if color_key is None or color_value is None:
            return current

        # clear the dict if the color style has changed
        if '{}_colors'.format(color_style) not in current.keys():
            current = {'{}_colors'.format(color_style): {}}

        # finally update the dict

        current['{}_colors'.format(
            color_style)][color_key] = color_value['hex']

        return current

    # Callback for molecule visualization based on uploaded PDB file
    @app.callback(
        Output('mol3d-biomolecule-viewer', 'children'),
        [
            Input('mol3d-upload-data', 'contents'),
            Input('dropdown-demostr', 'value'),
            Input('dropdown-styles', 'value'),
            Input('dropdown-style-color', 'value'),
            Input('mol3d-color-storage', 'modified_timestamp')
        ],
        [State('mol3d-color-storage', 'data')],
    )
    def use_upload(contents, demostr, mol_style, color_style, mt,
                   custom_colors):

        if demostr is not None:
            copy2(demostr, './str.pdb')
            fname = './str.pdb'
        elif contents is not None and demostr is None:
            try:
                content_type, content_string = str(contents).split(',')
                decoded_contents = base64.b64decode(content_string).decode(
                    "UTF-8")
                f = tempfile.NamedTemporaryFile(suffix=".pdb",
                                                delete=False,
                                                mode='w+')
                f.write(decoded_contents)
                fname = f.name
                f.close()
            except AttributeError:
                pass
        else:
            return 'demostr and contents are none'

        # Create the model data from the decoded contents
        modata = parser.create_data(fname)

        fmodel = files_data_style(modata)
        with open(fmodel) as fm:
            mdata = json.load(fm)

        # Create the cartoon style from the decoded contents
        datstyle = sparser.create_style(fname, mol_style, color_style,
                                        **custom_colors)

        fstyle = files_data_style(datstyle)
        with open(fstyle) as sf:
            data_style = json.load(sf)

        # Delete all the temporary files that were created
        for x in [fname, fmodel, fstyle]:
            if os.path.isfile(x):
                os.unlink(x)
            else:
                pass

        # Return the new molecule visualization container
        return dash_bio.Molecule3dViewer(
            id='mol-3d',
            selectionType='atom',
            modelData=mdata,
            styles=data_style,
            selectedAtomIds=[],
            backgroundOpacity='0',
            atomLabelsShown=False,
        )

    # Callback to print details of each selected atom of the biomolecule

    @app.callback(
        Output("mol3d-selection-output", "children"),
        [Input("mol-3d", "selectedAtomIds"),
         Input("mol-3d", "modelData")])
    def selout(selected_atom_ids, model_data):
        residue_summary = []
        for atom_id in selected_atom_ids:
            res_info = model_data['atoms'][atom_id]
            residues = {
                "residue": res_info['residue_name'],
                "atom": res_info['name'],
                "chain": res_info['chain'],
                "xyz": res_info['positions']
            }
            residue_summary += [
                html.P('{}: {}'.format(key, str(residues[key])))
                for key in residues
            ]
            residue_summary.append(html.Br())
        if len(residue_summary) == 0:
            residue_summary.append("No atoms have been selected. Click \
            on an atom to select it.")

        return html.Div(residue_summary)
コード例 #29
0
                            'fontSize': 24,
                            'marginLeft': '30px',
                            'color': colors['text']
                        }),
        ],
                 style={'display': 'inline-block'}),
        html.Div(id='output-graph'),
    ])


@app.callback(
    Output(component_id='output-graph', component_property='children'), [
        Input(component_id='input', component_property='value'),
        Input('submit-button', 'n_clicks')
    ], [
        State('my_date_picker', 'start_date'),
        State('my_date_picker', 'end_date')
    ])
def update_value(input_data, n_clicks, start_date, end_date):
    start = datetime.strptime(start_date[:10], '%Y-%m-%d')
    end = datetime.strptime(end_date[:10], '%Y-%m-%d')
    df = get_history(symbol=input_data, start=start, end=end)
    df.reset_index(inplace=True)
    df.set_index("Date", inplace=True)
    df = df.drop("Symbol", axis=1)

    return dcc.Graph(id='example-graph',
                     figure={
                         'data': [
                             {
                                 'x': df.index,
コード例 #30
0
ファイル: smart_app.py プロジェクト: vimcoper/shapash
    def callback_generator(self):
        app = self.app

        @app.callback([
            Output('dataset', 'data'),
            Output('dataset', 'columns'),
            Output('dataset', 'active_cell'),
        ], [
            Input('dataset', 'sort_by'),
            Input('dataset', "filter_query"),
            Input('modal', 'is_open')
        ], [State('rows', 'value'),
            State('name', 'value')])
        def update_datatable(sort_by, filter_query, is_open, rows, name):
            """
            update datatable according to sorting, filtering and settings modifications
            """
            ctx = dash.callback_context
            active_cell = no_update
            columns = self.components['table']['dataset'].columns
            if ctx.triggered[0]['prop_id'] == 'modal.is_open':
                if is_open:
                    raise PreventUpdate
                else:

                    self.settings['rows'] = rows
                    self.init_data()
                    active_cell = {
                        'row': 0,
                        'column': 0,
                        'column_id': '_index_'
                    }
                    self.settings_ini['rows'] = self.settings['rows']

                    if name == [1]:
                        columns = [
                                      {"name": '_index_', "id": '_index_'},
                                      {"name": '_predict_', "id": '_predict_'}] + \
                                  [{"name": self.explainer.features_dict[i], "id": i} for i in self.explainer.x_pred]

            if not filter_query:
                df = self.round_dataframe
            else:
                df = apply_filter(self.round_dataframe, filter_query)

            if len(sort_by):
                df = df.sort_values(
                    [col['column_id'] for col in sort_by],
                    ascending=[col['direction'] == 'asc' for col in sort_by],
                    inplace=False)
            self.components['table']['dataset'].data = df.to_dict('records')

            return self.components['table'][
                'dataset'].data, columns, active_cell

        @app.callback([
            Output('global_feature_importance', 'figure'),
            Output('global_feature_importance', 'clickData')
        ], [
            Input('select_label', 'value'),
            Input('dataset', 'data'),
            Input('modal', 'is_open')
        ], [
            State('global_feature_importance', 'clickData'),
            State('dataset', "filter_query"),
            State('features', 'value')
        ])
        def update_feature_importance(label, data, is_open, clickData,
                                      filter_query, features):
            """
            update feature importance plot according to selected label and dataset state.
            """
            ctx = dash.callback_context
            if ctx.triggered[0]['prop_id'] == 'modal.is_open':

                if is_open:
                    raise PreventUpdate
                else:

                    self.settings['features'] = features
                    self.settings_ini['features'] = self.settings['features']

            elif ctx.triggered[0]['prop_id'] == 'select_label.value':
                self.label = label
            elif ctx.triggered[0]['prop_id'] == 'dataset.data':
                self.list_index = [d['_index_'] for d in data]
            else:
                raise PreventUpdate

            selection = self.list_index if filter_query else None
            self.components['graph']['global_feature_importance'].figure = \
                self.explainer.plot.features_importance(max_features=features,
                                                        selection=selection,
                                                        label=self.label
                                                        )
            self.components['graph']['global_feature_importance'].adjust_graph(
            )
            self.components['graph'][
                'global_feature_importance'].figure.layout.clickmode = 'event+select'
            self.select_point('global_feature_importance', clickData)

            # font size can be adapted to screen size
            nb_car = max([
                len(self.components['graph']
                    ['global_feature_importance'].figure.data[0].y[i])
                for i in range(
                    len(self.components['graph']
                        ['global_feature_importance'].figure.data[0].y))
            ])
            self.components['graph'][
                'global_feature_importance'].figure.update_layout(yaxis=dict(
                    tickfont={'size': min(round(500 / nb_car), 12)}))

            return self.components['graph'][
                'global_feature_importance'].figure, clickData

        @app.callback(
            Output(component_id='feature_selector',
                   component_property='figure'), [
                       Input('global_feature_importance', 'clickData'),
                       Input('select_label', 'value'),
                       Input('modal', 'is_open')
                   ], [State('points', 'value'),
                       State('violin', 'value')])
        def update_feature_selector(feature, label, is_open, points, violin):
            """
            Update feature plot according to label, data, selected feature and settings modifications
            """
            ctx = dash.callback_context
            if ctx.triggered[0]['prop_id'] == 'modal.is_open':
                if is_open:
                    raise PreventUpdate
                else:
                    self.settings['points'] = points
                    self.settings_ini['points'] = self.settings['points']
                    self.settings['violin'] = violin
                    self.settings_ini['violin'] = self.settings['violin']

            elif ctx.triggered[0]['prop_id'] == 'select_label.value':
                self.label = label
            elif ctx.triggered[0][
                    'prop_id'] == 'global_feature_importance.clickData':
                if feature is not None:
                    self.selected_feature = feature['points'][0]['label']
                    if feature['points'][0]['curveNumber'] == 0 and \
                            len(self.components['graph']['global_feature_importance'].figure['data']) == 2:
                        self.subset = self.list_index
                    else:
                        self.subset = None
            else:
                raise PreventUpdate

            self.components['graph'][
                'feature_selector'].figure = self.explainer.plot.contribution_plot(
                    col=self.selected_feature,
                    selection=self.subset,
                    label=self.label,
                    violin_maxf=violin,
                    max_points=points)

            self.components['graph']['feature_selector'].figure[
                'layout'].clickmode = 'event'
            subset_graph = True if self.subset is not None else False
            self.components['graph']['feature_selector'].adjust_graph(
                subset_graph=subset_graph, title_size_adjust=True)

            return self.components['graph']['feature_selector'].figure

        @app.callback(
            [Output('index_id', 'value'),
             Output("index_id", "n_submit")],
            [
                Input('feature_selector', 'clickData'),
                Input('dataset', 'active_cell')
            ],
            [
                State('dataset', 'data'),
                State('index_id',
                      'value')  # Get the current value of the index
            ])
        def update_index_id(click_data, cell, data, current_index_id):
            """
            update index value according to active cell and click data on feature plot.
            """
            ctx = dash.callback_context
            if ctx.triggered[0]['prop_id'] != 'dataset.data':
                if ctx.triggered[0]['prop_id'] == 'feature_selector.clickData':
                    selected = click_data['points'][0]['customdata']
                    self.click_graph = True
                elif ctx.triggered[0]['prop_id'] == 'dataset.active_cell':
                    if cell is not None:
                        selected = data[cell['row']]['_index_']
                    else:
                        selected = current_index_id  # Get actual value in field to refresh the selected value
                elif ctx.triggered[0]['prop_id'] == '.':
                    selected = data[0]['_index_']
            else:
                raise PreventUpdate
            return selected, True

        @app.callback(Output('threshold_label', 'children'),
                      [Input('threshold_id', 'value')])
        def update_threshold_label(value):
            """
            update threshold label
            """
            return f'Threshold : {value}'

        @app.callback(Output('max_contrib_label', 'children'),
                      [Input('max_contrib_id', 'value')])
        def update_max_contrib_label(value):
            """
            update max_contrib label
            """
            self.components['filter']['max_contrib'][
                'max_contrib_id'].value = value
            return f'Features to display : {value}'

        @app.callback([
            Output('max_contrib_id', 'value'),
            Output('max_contrib_id', 'max'),
            Output('max_contrib_id', 'marks')
        ], [Input('modal', 'is_open')], [State('features', 'value')])
        def update_max_contrib_id(is_open, features):
            """
            update max contrib component layout after settings modifications
            """
            ctx = dash.callback_context
            if ctx.triggered[0]['prop_id'] == 'modal.is_open':
                if is_open:
                    raise PreventUpdate
                else:
                    max = min(features, len(self.dataframe.columns) - 2)
                    if max // 5 == max / 5:
                        nb_marks = min(int(max // 5), 10)
                    elif max // 4 == max / 4:
                        nb_marks = min(int(max // 4), 10)
                    elif max // 3 == max / 3:
                        nb_marks = min(int(max // 3), 10)
                    elif max // 7 == max / 7:
                        nb_marks = min(int(max // 6), 10)
                    else:
                        nb_marks = 2
                    marks = {
                        f'{round(max * feat / nb_marks)}':
                        f'{round(max * feat / nb_marks)}'
                        for feat in range(1, nb_marks + 1)
                    }
                    marks['1'] = '1'
                    if max < self.components['filter']['max_contrib'][
                            'max_contrib_id'].value:
                        value = max
                    else:
                        value = no_update

                    return value, max, marks

        @app.callback(
            Output(component_id='detail_feature', component_property='figure'),
            [
                Input('threshold_id', 'value'),
                Input('max_contrib_id', 'value'),
                Input('check_id_positive', 'value'),
                Input('check_id_negative', 'value'),
                Input('masked_contrib_id', 'value'),
                Input('select_label', 'value'),
                Input('dataset', 'active_cell'),
                Input('feature_selector', 'clickData'),
            ], [State('index_id', 'value'),
                State('dataset', 'data')])
        def update_detail_feature(threshold, max_contrib, positive, negative,
                                  masked, label, cell, click_data, index,
                                  data):
            """
            update local explanation plot according to app changes.
            """
            ctx = dash.callback_context
            selected = None
            if ctx.triggered[0]['prop_id'] == 'feature_selector.clickData':
                selected = click_data['points'][0]['customdata']
            elif ctx.triggered[0]['prop_id'] == 'threshold_id.value':
                selected = index
            elif ctx.triggered[0]['prop_id'] == 'dataset.active_cell':
                if cell:
                    selected = data[cell['row']]['_index_']
                else:
                    raise PreventUpdate

            if selected is None:
                if cell is not None:
                    selected = data[cell['row']]['_index_']
                else:
                    selected = index

            threshold = threshold if threshold != 0 else None
            if positive == [1]:
                sign = (None if negative == [1] else True)
            else:
                sign = (False if negative == [1] else None)

            self.explainer.filter(threshold=threshold,
                                  features_to_hide=masked,
                                  positive=sign,
                                  max_contrib=max_contrib)
            if np.issubdtype(type(self.explainer.x_pred.index[0]),
                             np.dtype(int).type):
                selected = int(selected)
            self.components['graph'][
                'detail_feature'].figure = self.explainer.plot.local_plot(
                    index=selected,
                    label=label,
                    show_masked=True,
                    yaxis_max_label=0)
            self.components['graph']['detail_feature'].adjust_graph(
                title_size_adjust=True)
            # font size can be adapted to screen size
            nb_car = max([
                len(self.components['graph']
                    ['detail_feature'].figure.data[i].y[0]) for i in range(
                        len(self.components['graph']
                            ['detail_feature'].figure.data))
            ])
            self.components['graph']['detail_feature'].figure.update_layout(
                yaxis=dict(tickfont={'size': min(round(500 / nb_car), 12)}))
            return self.components['graph']['detail_feature'].figure

        @app.callback(
            Output("validation", "n_clicks"),
            [Input("index_id", "n_submit")],
        )
        def click_validation(n_submit):
            """
            submit index selection
            """
            if n_submit:
                return 1
            else:
                raise PreventUpdate

        @app.callback([
            Output('dataset', 'style_data_conditional'),
            Output('dataset', 'style_filter_conditional'),
            Output('dataset', 'style_header_conditional'),
            Output('dataset', 'style_cell_conditional'),
        ], [Input("validation", "n_clicks")],
                      [State('dataset', 'data'),
                       State('index_id', 'value')])
        def datatable_layout(validation, data, index):
            ctx = dash.callback_context
            if ctx.triggered[0][
                    'prop_id'] == 'validation.n_clicks' and validation is not None:
                pass
            else:
                raise PreventUpdate

            style_data_conditional = [{
                'if': {
                    'row_index': 'odd'
                },
                'backgroundColor': 'rgb(248, 248, 248)'
            }]
            style_filter_conditional = []
            style_header_conditional = [{
                'if': {
                    'column_id': c
                },
                'fontWeight': 'bold'
            } for c in ['_index_', '_predict_']]
            style_cell_conditional = [{
                'if': {
                    'column_id': c
                },
                'width': '70px',
                'fontWeight': 'bold'
            } for c in ['_index_', '_predict_']]

            selected = check_row(data, index)
            if selected is not None:
                style_data_conditional += [{
                    "if": {
                        "row_index": selected
                    },
                    "backgroundColor": self.color
                }]

            return style_data_conditional, style_filter_conditional, style_header_conditional, style_cell_conditional