Beispiel #1
0
    def __init__(self, mode="default", **kwargs):
        external_stylesheets = [BOOTSTRAP]
        if mode == "jupyter":
            self.app = JupyterDash(external_stylesheets=external_stylesheets)
        else:
            self.app = Dash(
                external_stylesheets=external_stylesheets,
                prevent_initial_callbacks=True,
            )

        app = self.app  # For referencing with the decorator (see line below)
        app.title = "CEHS Uganda"

        @app.server.route("/static/<asset_type>/<path>")
        def static_file(asset_type, path):
            return send_from_directory(here / "static" / asset_type, path)
import dash_html_components as html
from dash_extensions.enrich import Output, Dash, Trigger

app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
    html.Button("Left", id="left"), html.Button("Right", id="right"), html.Div(id="log"),
])


@app.callback(Output("log", "children"), Trigger("left", "n_clicks"), group="lr")  # targets same output as right
def left():
    return "left"


@app.callback(Output("log", "children"), Trigger("right", "n_clicks"), group="lr")  # targets same output as left
def right():
    return "right"


if __name__ == '__main__':
    app.run_server()

import dash_html_components as html
from dash.dependencies import ClientsideFunction
from dash_extensions.enrich import Dash, Input

app = Dash(__name__, prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Click me", id="btn")])


@app.callback(Input("btn", "n_clicks"))  # no Output is OK
def func(n_clicks):
    print(f"Click count = {n_clicks}")


# Clientside callback with literal JS code.
f = "function(n_clicks){console.log('Hello world! Click count = ' + n_clicks);}"
app.clientside_callback(f, Input("btn", "n_clicks"))  # no Output is OK

# Clientside callback reference to JS asset function.
app.clientside_callback(
    ClientsideFunction(namespace="clientside", function_name="hello"),
    Input("btn", "n_clicks"),  # no Output is OK
)

if __name__ == '__main__':
    app.run_server(port=7777)
Beispiel #4
0
fapp.config['USER_ENABLE_USERNAME'] = True
fapp.config['USER_EMAIL_SENDER_NAME'] = 'Booking'
fapp.config['USER_EMAIL_SENDER_EMAIL'] = '*****@*****.**'

fapp.config['USER_AFTER_REGISTER_ENDPOINT'] = 'user.resend_email_confirmation'

# fapp.config['USER_ENABLE_CONFIRM_EMAIL'] = False
fapp.config['USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL'] = True
# fapp.config['USER_SEND_REGISTERED_EMAIL'] = False

app = Dash(
    __name__,
    server=fapp,
    external_stylesheets=[
        'https://pro.fontawesome.com/releases/v5.10.0/css/all.css',
        dbc.themes.BOOTSTRAP
    ],
    title="Booking",
    update_title=None,
    suppress_callback_exceptions=True,
)

init_flask_admin(fapp)
user_manager = CustomUserManager(fapp, db, UserClass=User)
migrate = Migrate(fapp, db)
init_db(fapp, user_manager)

for view_func in fapp.view_functions:
    if view_func.startswith('/'):
        fapp.view_functions[view_func] = allow_unconfirmed_email(
            login_required(fapp.view_functions[view_func]))
        vid = open(fn_pre, 'rb')
        base64_data = b64encode(vid.read())
        base64_string = base64_data.decode('utf-8')
        return [html.Video(src=f'data:video/webm;base64,{base64_string}', controls=True)], f'/{ffname}', False


    return app


if __name__ == '__main__':

    external_stylesheets = [
        dbc.themes.BOOTSTRAP,
    ]

    server = Flask(__name__)
    app = Dash(__name__, server=server, external_stylesheets=external_stylesheets)
    app.config['suppress_callback_exceptions'] = True

    @app.server.route('/downloads/<path:path>')
    def serve_static(path):
        return send_from_directory(
            Path("downloads"), path, as_attachment=True
        )

    du.configure_upload(app, Path.cwd() / Path("temp"))

    app.layout = layout
    app = add_dash(app)
    app.run_server(debug=True)
import dash_html_components as html
from dash_extensions.enrich import Output, Dash, Input

app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Click me", id="btn")])


@app.callback(Input("btn", "n_clicks"))  # not Output is OK
def func(n_clicks):
    print(f"Click count = {n_clicks}")


if __name__ == '__main__':
    app.run_server()
Beispiel #7
0
import rfind_monitor.const as const
from rfind_monitor.utils.redis import numpy_from_Redis

# h5f = h5py.File(const.SOURCE_H5,'r')
redis_client = redis.Redis(host=const.REDIS_IP, port=const.REDIS_PORT, db=0)

y_range = [20, 60]

start_spec = np.zeros((const.WATERFALL_HEIGHT, const.SPEC_WIDTH),
                      dtype=const.DTYPE)
start_freqs = np.linspace(0, 2e9, const.SPEC_WIDTH)

app = Dash(
    __name__,
    requests_pathname_prefix=const.DASH_PREFIX,
    title='RFInd Monitor',
    update_title=None,
    prevent_initial_callbacks=True,
    assets_folder=const.ASSETS_DIR,
)


def serve_layout():

    return html.Div(
        [
            dcc.Store(id='userServerStore'),
            dcc.Interval(id='check_for_data',
                         interval=const.UPDATE_STORE_RATE),
            dcc.Interval(id='update_gui', interval=const.UPDATE_GUI_RATE),
            dcc.Graph(id='spec',
                      responsive=True,
import time
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash_extensions.enrich import Dash, Output, Input, State, ServersideOutput

app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
    html.Button("Query data", id="btn"),
    dcc.Dropdown(id="dd"),
    dcc.Graph(id="graph"),
    dcc.Loading(dcc.Store(id='store'), fullscreen=True, type="dot")
])


@app.callback(ServersideOutput("store", "data"), Input("btn", "n_clicks"))
def query_data(n_clicks):
    time.sleep(1)
    return px.data.gapminder()  # no JSON serialization here


@app.callback(Input("store", "data"), Output("dd", "options"))
def update_dd(df):
    return [{
        "label": column,
        "value": column
    } for column in df["year"]]  # no JSON de-serialization here


@app.callback(
    Output("graph", "figure"),
Beispiel #9
0
                    gas_price_grade)
                columns = list(set(['date'] + list(df_cols.col.values)))
                # make date the first column
                columns = ['date'] + [c for c in columns if c != 'date']
                columns = columns[:num_displayable_columns]

            df_ret = df_main_store_data[columns]
            ret_columns = [{'label': c, 'id': c} for c in columns]

            dict_ret = df_ret.to_dict('records')
            return dict_ret, ret_columns

        self.eia_cat_div.register_app(theapp)
        self.logger.info('registered eia_access')


app_port = 8813

url_base_pathname = f'/app{app_port}/'
app = Dash(prevent_initial_callbacks=True, url_base_pathname=url_base_pathname)
app.title = 'Eia Viewer'

eia_access = EiaAccess('eia_access')
app_layout = dcc.Loading(children=[eia_access], fullscreen=True, type="dot")

app.layout = app_layout
eia_access.register_app(app)

if __name__ == '__main__':
    app.run_server(port=app_port, debug=False)
Beispiel #10
0
        fig.add_trace(go.Scatter(x=df.index, y=df[col]))
    return fig


def make_layout(tag):
    return [
        dcc.Graph(id=f"graph_{tag}"),
        html.Button(f"Update [{tag}]", id=f"btn_{tag}")
    ]


tags = ["default", "memoize", "prejson"]
memoize = dict(default=None, memoize=True, prejson=plotly_jsonify)
# Create dummy data.
df = pd.DataFrame(index=pd.date_range("2020-01", "2021-01", freq="H"),
                  columns=list("ABCDEFGHIJK"),
                  data=pd.np.nan)
df[:] = np.random.random(df.values.shape)
# Create example app.
app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div(
    list(itertools.chain.from_iterable([make_layout(tag) for tag in tags])))
# Attach callbacks.
for t in tags:
    app.callback(Output(f"graph_{t}", "figure"),
                 Trigger(f"btn_{t}", "n_clicks"),
                 memoize=memoize[t])(make_figure)

if __name__ == '__main__':
    app.run_server(port=8877, debug=True)
Beispiel #11
0
class Dashboard:
    """This is abstract dashboard method
    Every nested class should implement following abstract methods:
        - _set_layout: to set dash.app.layout property
    # TODO: expand the class with default layout
    # TODO: expand the class with default styling
    """
    def __init__(self, mode="default", **kwargs):
        external_stylesheets = [BOOTSTRAP]
        if mode == "jupyter":
            self.app = JupyterDash(external_stylesheets=external_stylesheets)
        else:
            self.app = Dash(
                external_stylesheets=external_stylesheets,
                prevent_initial_callbacks=True,
            )

        app = self.app  # For referencing with the decorator (see line below)
        app.title = "CEHS Uganda"

        @app.server.route("/static/<asset_type>/<path>")
        def static_file(asset_type, path):
            return send_from_directory(here / "static" / asset_type, path)

    ################
    #    LAYOUT    #
    ################

    def _set_layout(self):
        """Method is left deliberately empty. Every child class should implement this class"""
        raise NotImplementedError(
            "Every child class should implement __set_layout method!")

    ###################
    #    EXECUTION    #
    ###################

    def run(self, dev=False, **kwargs):
        self._set_layout()
        self._define_callbacks()
        self.app.run_server(debug=dev, use_reloader=dev, **kwargs)

    def switch_data_set(self, data):
        for x in self.data_cards:
            try:
                if isinstance(x, DataCard) or getattr(x, "data") is not None:
                    x.data = data
                    # x.figure = x._get_figure(x.data)
            except AttributeError as e:
                print(e)

    ###################
    #    CALLBACKS    #
    ###################

    def _define_callbacks(self):
        # TODO: self.data_cards is property of datastory... Move this to datastory or data_cards to dashboard?
        # Datacard level
        for x in self.data_cards:
            if x._requires_dropdown():
                for callback in x.callbacks:
                    self.register_callback(
                        function=callback.get("func"),
                        input_element_params=callback.get("input", []),
                        output_elements_params=callback.get("output", []),
                    )
        for x in self.ind_elements:  # FIXME
            if x._requires_dropdown():
                for callback in x.callbacks:
                    self.register_callback(
                        function=callback.get("func"),
                        input_element_params=callback.get("input", []),
                        output_elements_params=callback.get("output", []),
                    )

    def register_callback(
        self,
        function,
        input_element_params,
        output_elements_params=[],
        download_elements_params=[],
    ):
        callback_set = self.__define_callback_set(input_element_params,
                                                  output_elements_params)

        callback_function = self.__process_callback_function(function)

        self.app.callback(*callback_set)(callback_function)

    def __process_callback_function(self, function):
        def callback_wrapper(*input_values):
            value = function(*input_values)
            return value

        return callback_wrapper

    def __define_callback_set(self,
                              input_element_id_prop: list,
                              output_elements_id_prop: list = []):

        callback_set_outputs = [
            Output(component_id=component_id,
                   component_property=component_prop)
            for component_id, component_prop in output_elements_id_prop
        ]

        callback_set_input = [
            Input(component_id=component_id, component_property=component_prop)
            for component_id, component_prop in input_element_id_prop
        ]

        callback_set = [
            x for x in [callback_set_outputs, callback_set_input] if len(x) > 0
        ]

        return callback_set
Beispiel #12
0
from dash_extensions.enrich import Dash
from flask import Flask
import dash_html_components as html

from dash.dependencies import ALL, MATCH
from dash_extensions.enrich import Input, Output

fapp = Flask(__name__)
app = Dash(__name__, server=fapp)
app.suppress_callback_exceptions = True


@app.callback(Output("all", "children"),
              Input(dict(type="btn", id=ALL), "n_clicks"), group="A")
def all(args):
    print("ALL")
    return args


@app.callback(Output(dict(type="MATCH", id=MATCH), "children"),
              Input(dict(type="btn", id=MATCH), "n_clicks"), group="C")
def match(args):
    print("MATCH")
    return args


ids = [1, 2, 3]
app.layout = html.Div(
    [html.Button(f"Button{id}", id=dict(type="btn", id=id)) for id in ids] +
    [html.Div(children="ALL"), html.Div(id="all", children="all")] +
    [html.Div(children="MATCH")] +
                  width=650,
                  margin=dict(l=50, r=50, b=50, t=50, pad=4))
# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
external_stylesheets = [
    "https://unpkg.com/[email protected]/css/tachyons.min.css"
]

app = Dash(
    __name__,
    external_stylesheets=external_stylesheets,
    meta_tags=[{
        'name':
        'PredictCarbon COVID',
        'content':
        'This is a group project completed for the course Applied Machine Intelligence at the Technical University of Munich'
    }, {
        'http-equiv': 'X-UA-Compatible',
        'content': 'IE=edge'
    }, {
        'name': 'viewport',
        'content': 'width=device-width, initial-scale=1.0'
    }],
    title='PredictCarbon COVID',
    update_title='Calculating')

country_names = np.array(
    pd.ExcelFile('dataset/features/Modified_Stringency_Data.xlsx').sheet_names)
country_list = [{'label': i, 'value': i} for i in country_names]

# Pie Diagram
# df = pickle.load(open('/dataset/Country_population_co2.pkl', 'rb'))
Beispiel #14
0
'''
Created on Aug 9, 2020

@author: bperlman1
'''
from dash_extensions.enrich import Dash

app_port = 8812

url_base_pathname = f'/app{app_port}/'
app = Dash(prevent_initial_callbacks=True, url_base_pathname=url_base_pathname)
app.title = 'db_table_access'
server = app.server
Beispiel #15
0
import base64
import os
import io
import dash_core_components as dcc
import dash_cytoscape as cyto
import dash_html_components as html

from data_processing_utils._processing_funcs import ResultProcessing
from dash.exceptions import PreventUpdate

from dash_extensions.enrich import Dash, Output, Input, State, Trigger, ServersideOutput

app = Dash(
    __name__,
    meta_tags=[{
        "name": "viewport",
        "content": "width=device-width"
    }],
    prevent_initial_callbacks=True,
)

# Load extra layouts
cyto.load_extra_layouts()

app.title = 'SMILE'

server = app.server

app.config['suppress_callback_exceptions'] = True

# -------------  html layout code    ------------------
app.layout = html.Div(
Beispiel #16
0
from dash.exceptions import PreventUpdate
from flask import Flask
from cl.tasks import take_a_nap, celery_app
from celery.result import result_from_tuple
from dash_extensions.enrich import Dash, Output, Input, State, dcc, html

# Create app.
server = Flask(__name__)
app = Dash(server=server, prevent_initial_callbacks=True)
app.layout = html.Div([
    # User input (how many second to nap).
    dcc.Input(id="nap-duration", type="number", min=0, max=10, value=1),
    # Button for launching async job (a nap).
    html.Button(id="btn-run", children="Take a nap"),
    # Container for storing the result of the async job.
    html.Div(id="div-result"),
    # Container for storing a reference to the async job.
    dcc.Store(id="result-tuple"),
    # Interval component for polling updates on the status of the async job.
    dcc.Interval(id="poller", max_intervals=0),
])


@app.callback([
    Output("btn-run", "disabled"),
    Output("btn-run", "children"),
    Output("result-tuple", "data"),
    Output("poller", "max_intervals")
], [Input("btn-run", "n_clicks")], [State("nap-duration", "value")])
def launch_job(n_clicks, value):
    # Run the job asynchronously (note the .delay syntax).