コード例 #1
0
ファイル: model_page.py プロジェクト: Magier/Aetia
def show(state: SessionState):
    st.checkbox("toggle")
    sample_name = st.selectbox("Sample Model",
                               list(SAMPLE_DAGS.keys()),
                               index=0)
    if "model" not in state or st.button(f"Load {sample_name} model"):
        model = load_sample_model(sample_name)
        st.write(model)
        state.model = model
    else:
        model = state.model

    backdoor_check = identify.check_backdoor_criterion(model, model.treatment,
                                                       model.outcome,
                                                       model.adjusted)
    st.write(f"all backdoor paths blocked: {backdoor_check}")

    elements, style, layout, ctx_menu = utils.get_cytoscape_params_from_model(
        model)
    cy_event = st_cytoscape_builder(elements,
                                    style,
                                    layout,
                                    context_menu=ctx_menu,
                                    height=800)
    if cy_event is not None:
        if handle_cytoscape_event(cy_event, model):
            st.experimental_rerun()
コード例 #2
0
def webrtc_streamer(
    key: str,
    mode: WebRtcMode = WebRtcMode.SENDRECV,
    client_settings: Optional[ClientSettings] = None,
    player_factory: Optional[MediaPlayerFactory] = None,
    in_recorder_factory: Optional[MediaRecorderFactory] = None,
    out_recorder_factory: Optional[MediaRecorderFactory] = None,
    video_transformer_factory: Optional[VideoTransformerFactory] = None,
    async_transform: bool = True,
) -> WebRtcStreamerContext:
    webrtc_worker = _get_webrtc_worker(key)

    sdp_answer_json = None
    if webrtc_worker:
        sdp_answer_json = json.dumps({
            "sdp":
            webrtc_worker.pc.localDescription.sdp,
            "type":
            webrtc_worker.pc.localDescription.type,
        })

    component_value: Union[Dict, None] = _component_func(
        key=key,
        sdp_answer_json=sdp_answer_json,
        mode=mode.name,
        settings=client_settings,
    )

    playing = False
    if component_value:
        playing = component_value.get("playing", False)
        sdp_offer = component_value.get("sdpOffer")

        if webrtc_worker:
            if not playing:
                webrtc_worker.stop()
                _unset_webrtc_worker(key)
                webrtc_worker = None
        else:
            if sdp_offer:
                webrtc_worker = WebRtcWorker(
                    mode=mode,
                    player_factory=player_factory,
                    in_recorder_factory=in_recorder_factory,
                    out_recorder_factory=out_recorder_factory,
                    video_transformer_factory=video_transformer_factory,
                    async_transform=async_transform,
                )
                webrtc_worker.process_offer(sdp_offer["sdp"],
                                            sdp_offer["type"])
                _set_webrtc_worker(key, webrtc_worker)
                st.experimental_rerun(
                )  # Rerun to send the SDP answer to frontend

    ctx = WebRtcStreamerContext(
        state=WebRtcStreamerState(playing=playing),
        worker=webrtc_worker,
    )

    return ctx
コード例 #3
0
ファイル: app.py プロジェクト: ctgk/bayesian
def classification(model):
    action = st.selectbox('Action:', (
        'Click to add positive data points',
        'Click to add negative data points',
        'Double click to delete data points',
    ))
    x_train, y_train = get_xy_from_canvas(
        'yellow' if 'positive' in action else 'purple', action, False)
    cache = get_cache()
    if ((cache['model'] != model)
            or (cache['x'] != x_train)
            or (cache['y'] != y_train)):
        cache['x'] = x_train
        cache['y'] = y_train
        cache['model'] = model
        with RendererAgg.lock:
            fig, ax = get_fig_ax()
            if len(y_train) > 0:
                model.fit(x_train, y_train)
                cache['model'] = model
                x = np.linspace(-1, 1, 100)
                x1, x2 = np.meshgrid(x, x)
                x = np.array([x1, x2]).reshape(2, -1).T
                y = model.proba(x).reshape(100, 100)
                ax.contourf(x1, x2, y, alpha=0.2)
                ax.clabel(
                    ax.contour(x1, x2, y, linestyles='dotted'), colors='black')
            cache['bg'] = figure_to_img(fig)
            plt.clf()
        st.experimental_rerun()
コード例 #4
0
def render_item(entry, postpone_df):
    st.write(f"### {entry.content}")
    st.write(f"Expiring on: {entry.expiration_date}")
    st.write(f"{entry.servings} servings in the {entry.storage_location}")
    if st.button("I ate it", key=entry.row_id):
        cell_name = get_cell_name(entry, "servings")
        inventory_ws.update(cell_name, str(entry.servings - 1), raw=False)
        st.experimental_rerun()
    if st.button("Postpone", key=entry.row_id):
        postpone_df = postpone_df.append(
            {
                "expiration_date":
                entry.expiration_date,
                "content":
                entry.content,
                "postpone_until":
                datetime.date.today() + datetime.timedelta(days=21),
            },
            ignore_index=True,
        )
        postpone_ws.clear()
        postpone_ws.update(
            "A1:C",
            [postpone_df.columns.tolist()] +
            postpone_df.astype(str).values.tolist(),
            raw=False,
        )
        st.experimental_rerun()
コード例 #5
0
def login_widget():
    st.markdown("<div class='spacediv'></div>", unsafe_allow_html=True)
    st.markdown("<div class='spacediv'></div>", unsafe_allow_html=True)
    st.markdown("<div class='spacediv'></div>", unsafe_allow_html=True)
    with st.beta_container():
        lph, title, rph = st.beta_columns((1, 2, 1))
        with title:
            st.header('Login')
    with st.beta_container():
        lph, title, rph = st.beta_columns((1, 2, 1))
        with title:
            session_id = load_session_id()
            cookie = st.text_input('Cookie', session_id)
    with st.beta_container():
        lph, but, rph = st.beta_columns((10, 1, 10))
        with but:
            if st.button('Entrar'):
                state.cookie = cookie
                state.authorized = connect_database()
                if state.authorized:
                    load_data()
                st.experimental_rerun()
    st.markdown("<div class='spacediv'></div>", unsafe_allow_html=True)
    st.markdown("<div class='spacediv'></div>", unsafe_allow_html=True)
    st.markdown("<div class='spacediv'></div>", unsafe_allow_html=True)
コード例 #6
0
def app():
    st.markdown("""
        # Create Strategy

        Here you can create your strategy!

        You will need to create a function called `strategy` that takes in a
        dictionary named `bot_positions` (e.g. `{"Bot1": 1, "Bot2": 3}`) as argument
        and should return either *"walk"* or *"sabotage"*.

        See the ***Example page*** for examples.

        You can either:
        """)

    with st.beta_expander("Write Code Directly"):
        bot_name = st.text_input(label="Bot Name")
        strategy_code = st.text_area(
            label="Strategy Code: ",
            value=inspect.cleandoc("""
        import random
            
        def strategy(bot_positions):
            return random.choice(["walk", "sabotage"])
        """),
            height=320,
        )
        if st.button("Submit"):
            if bot_name:
                fp = util.save_code_to_file(code=strategy_code,
                                            filename=bot_name)
                util.validate_file(fp)
                st.success("File uploaded and validated successfully, "
                           "go to `Race Page` to run the Game")
            else:
                st.error("Please provide a name for the Bot")

    with st.beta_expander("Upload a file"):
        file_buffer = st.file_uploader(
            "Upload a strategy file (.py)",
            help="The filename will be used to name the Bot",
        )
        if file_buffer:
            fp = util.save_file(filename=file_buffer.name,
                                filebytes=file_buffer.getvalue())
            util.validate_file(fp)
            st.success("File uploaded and validated successfully, "
                       "go to `Race Page` to run the Game")

    st.markdown(f"## Current Competitors:")
    competitors = util.build_all_bots()
    if competitors:
        st.markdown("\n".join([f"\t- {c}" for c in competitors]))
    else:
        st.markdown("no competitors saved yet")

    if st.button("Add example bots"):
        util.add_example_bots()
        st.experimental_rerun()
コード例 #7
0
def main():
    try:
        st.set_page_config(page_title="Hyperactive Progress Board",
                           layout="wide")
    except:
        pass

    progress_ids = sys.argv[1:]
    backend = StreamlitBackend(progress_ids)
    lock_files = []

    for progress_id in progress_ids:
        search_id = progress_id.rsplit(":")[0]

        st.title(search_id)
        st.components.v1.html(
            """<hr style="height:1px;border:none;color:#333;background-color:#333;" /> """,
            height=10,
        )
        st.write(" ")

        _, col_2, _, col_4 = st.beta_columns([0.1, 0.9, 0.1, 2])
        col1, col2 = st.beta_columns([1, 2])

        progress_data = backend.get_progress_data(progress_id)

        pyplot_fig = backend.pyplot(progress_data)
        plotly_fig = backend.plotly(progress_data, progress_id)

        if pyplot_fig is not None:
            col_2.header("Best score progression")
            col1.pyplot(pyplot_fig)
        if plotly_fig is not None:
            col_4.header("Parallel Coordinates")
            col2.plotly_chart(plotly_fig, use_container_width=True)

        last_best = backend.create_info(progress_id)

        if last_best is not None:
            plotly_table = backend.table_plotly(last_best)
            st.plotly_chart(plotly_table, use_container_width=True)

        for _ in range(3):
            st.write(" ")

        lock_file = backend._io_.get_lock_file_path(progress_id)
        lock_files.append(os.path.isfile(lock_file))

    time.sleep(3)
    if all(lock_file is False for lock_file in lock_files):
        print("\n --- Deleting progress- and filter-files --- \n")

        for progress_id in progress_ids:
            backend._io_.remove_progress(progress_id)
            backend._io_.remove_filter(progress_id)

    else:
        print("\n --- Rerun streamlit --- \n")
        st.experimental_rerun()
コード例 #8
0
ファイル: streamlit_ui.py プロジェクト: xpanfan/opyrator
def render_streamlit_ui(opyrator: Opyrator) -> None:
    session_state = streamlit_utils.get_session_state()

    title = opyrator.name
    if "opyrator" not in opyrator.name.lower():
        title += " - Opyrator"

    # Page config can only be setup once
    # st.set_page_config(page_title="Opyrator", page_icon=":arrow_forward:")

    st.title(title)

    # Add custom css settings
    st.markdown(f"<style>{CUSTOM_STREAMLIT_CSS}</style>",
                unsafe_allow_html=True)

    if opyrator.description:
        st.markdown(opyrator.description)

    InputUI(session_state=session_state,
            input_class=opyrator.input_type).render_ui()

    st.markdown("---")

    clear_col, execute_col = st.beta_columns([1, 2])

    with clear_col:
        if st.button("Clear"):
            # Clear all state
            session_state.clear()
            st.experimental_rerun()

    with execute_col:
        execute_selected = st.button("Execute")

    if execute_selected:
        with st.spinner("Executing operation. Please wait..."):
            try:
                input_data_obj = parse_obj_as(opyrator.input_type,
                                              session_state.input_data)
                session_state.output_data = opyrator(input=input_data_obj)
                session_state.latest_operation_input = input_data_obj  # should this really be saved as additional session object?
            except ValidationError as ex:
                st.error(ex)
            else:
                # st.success("Operation executed successfully.")
                pass

    if session_state.output_data:
        OutputUI(session_state.output_data,
                 session_state.latest_operation_input).render_ui()

        st.markdown("---")

        show_json = st.empty()
        # with st.beta_expander(label="Show JSON Output", expanded=False):
        if show_json.button("Show JSON Output"):
            # Shows json if button is selected
            show_json.json(session_state.output_data.json())
コード例 #9
0
def disconnect_database():
    state.authorized = False
    state.cookie = None
    state.users = None
    state.procs = None
    state.cirgs = None
    state.sched = None
    st.experimental_rerun()
コード例 #10
0
def swap_app(app):
    st.experimental_set_query_params(app=app)
    session_state.app = app

    # Not sure why this is needed. The `set_query_params` doesn't
    # appear to work if a rerun is undergone immediately afterwards.
    time.sleep(0.01)
    st.experimental_rerun()
コード例 #11
0
ファイル: FundConfig.py プロジェクト: zuoxiaolei/LiLiFund
def config_app():
    '''
    设置fund app界面
    :return:
    '''
    st.header(title)
    st.subheader("编辑基金列表")

    # 加载基金列表数据
    select_fund_set = joblib.load(task.SELECT_FUND_LIST_CODE_FILE)
    all_fund_list_df = joblib.load(task.ALL_MARKET_FUND_INFO_FILE)
    all_fund_set = set(all_fund_list_df["基金代码"].tolist())
    fund_list = all_fund_list_df.loc[
        all_fund_list_df["基金代码"].isin(select_fund_set),
        ['基金代码', '基金简称', '基金类型']].values.tolist()
    fund_num = len(fund_list)

    count = 0
    for code, name, type in fund_list:
        count += 1
        col1, col2, col3, col4 = st.beta_columns(4)
        with col1:
            st.text(code)
        with col2:
            st.text(name)
        with col3:
            st.text(type)
        with col4:
            command_delete = st.button("删除", key="删除" + str(count))
            if command_delete:
                if fund_num > 1:
                    select_fund_set.remove(code)
                    joblib.dump(select_fund_set,
                                task.SELECT_FUND_LIST_CODE_FILE)
                    st.experimental_rerun()
                else:
                    st.warning("只有最后一个基金了,请添加基金")

    col1, col2 = st.beta_columns(2)
    with col1:
        code = st.text_input("添加基金代码", max_chars=6)

    with col2:
        st.header(" ")
        is_add = st.button("添加")
        if is_add:
            if code not in select_fund_set and len(code) == 6:
                if code in all_fund_set:
                    select_fund_set.add(code)
                    joblib.dump(select_fund_set,
                                task.SELECT_FUND_LIST_CODE_FILE)
                    st.info("添加基金: {}成功".format(code))
                    st.experimental_rerun()
                else:
                    st.error("添加基金: {}失败".format(code))
            else:
                st.error("基金{}已经存在".format(code))
コード例 #12
0
def run(**kwargs):
    session_state = SessionState.get(is_login=False, welcome=False)

    try:
        encryption_key = kwargs["encryption_file"]
        database_file = kwargs["database_file"]
    except KeyError:
        from wms import cli

        encryption_key = cli.ENCRYPTION_KEY
        database_file = cli.DATABASE_FILE

    with open(encryption_key, "rb") as f:
        hashed_password = f.read()

    st.set_page_config(page_title="Wholesale Management System", layout="wide")

    main_page = gui.MainPage()
    main_page.call()

    if not session_state.is_login:
        gui.intro()

        st.sidebar.header("LOGIN SECTION")
        st.sidebar.subheader("**WARNING: AUTHORIZED ACCESS ONLY**")
        st.sidebar.write("""
                        Input your privileged password on the left sidebar, then click **Sign in** or press **Enter** to login.
                    """)
        session_state.input_password = st.sidebar.text_input("Input privileged password: "******"password",
                                                             value=session_state.input_password or "")

        if st.sidebar.button("Sign in") or session_state.input_password:
            if not bcrypt.checkpw(base64.b64encode(hashlib.sha512(session_state.input_password.encode()).digest()),
                                  hashed_password):
                st.sidebar.warning("Wrong password!")
                st.stop()
            else:
                session_state.is_login = True
                st.experimental_rerun()
    else:
        if not session_state.welcome:
            st.balloons()
            session_state.welcome = True

        menu = gui.Menu(db_file=database_file,
                        csv_zip=os.path.join(os.path.dirname(wms.__file__), "hello/dummy/dummy_data.zip"))

        menu.display_option()

        st.sidebar.markdown("---")
        st.sidebar.write(f"*Current session ID: {session_state.get_id()}*")
        if st.sidebar.button("Sign out"):
            session_state.clear()

        gui.info()

    session_state.sync()
コード例 #13
0
def st_rerun() -> None:
    st.markdown("---")
    st.header("🔄 Rerun Streamlit App from Top")
    st.markdown("""
        Here you can trigger a manual rerun of the whole Streamlit App from the top.<br>
        Just for testing purposes.
        """,
                unsafe_allow_html=True)
    if st.button('Rerun Streamlit App'):
        st.experimental_rerun()
コード例 #14
0
ファイル: main.py プロジェクト: data-hydenv/hydenv-database
def main_app(connection=None, measurementId="G-RLF2LDRQSR", debug=False):
    st.set_page_config(page_title="Excercises by hydrocode", layout="wide")
    
    # hydrocode branding
    l, r = st.sidebar.columns((1,4))
    l.image('https://firebasestorage.googleapis.com/v0/b/hydrocode-website.appspot.com/o/public%2Flogo.png?alt=media&token=8dda885c-0a7d-4d66-b5f6-072ddabf3b02', use_column_width=True)
    r.title('hydrocode powered')
    # set the measurementId
    if 'measurementId' not in st.session_state:
        st.session_state.measurementId = measurementId
    
    if 'debug' not in st.session_state:
        st.session_state.debug = debug

    # check if there is need for install
    db = get_db_con()

    # checkout the app page
    page_name = st.session_state.get('page_name')
    if page_name is None:
        st.session_state.page_name = 'home'
        page_name = 'home'
    # pageview event
    pageview()

    # back button
    if st.session_state.get('connection', False) and page_name != 'home':
        back = st.sidebar.button('Back GUI overview')
        if back:
            st.session_state.page_name = 'home'
            st.experimental_rerun()
    
    # check if a table tree was loaded
    if 'table_tree' in st.session_state:
        st.sidebar.markdown('### DATABASE TABLES')
        st.sidebar.json(st.session_state.table_tree)

    if page_name == 'home':
        home_page(db)
    elif page_name == 'exercise':
        # load the list of solved exercises
        load_solved_list()
        
        # get the tracks and select the exercise
        tracks = get_base_data()
        exercise = manage_session(tracks)

        exercise_page(tracks, db)
    elif page_name == 'install':
        install_page()
    
    elif page_name.startswith('example_'):
        example_page(db)
コード例 #15
0
def basic_annotator(get_dataset, display, selector_elements=None):
    state = SessionState.get(username=secrets.token_hex(16),
                             key=secrets.token_hex(128),
                             assignments={},
                             get_next=True)
    username = state.username

    if selector_elements is not None:
        values = selector_elements()
    else:
        values = {}

    dataset: Dict[str, Any] = get_dataset(**values)

    if state.get_next:
        assignments: Dict[str,
                          bool] = get_history(dataset_idx=list(dataset.keys()),
                                              username=username)
        state.assignments = assignments
        state.get_next = False
    else:
        assignments = state.assignments

    format_func = lambda x: (u"✅ " if assignments[x] else "❌ ") + x
    selected_assignment = st.sidebar.selectbox(label="Assignments",
                                               options=list(
                                                   assignments.keys()),
                                               format_func=format_func)

    with st.spinner("Loading document"):
        annotations = annotation_block(
            page=display(dataset[selected_assignment],
                         username=username,
                         assignment=selected_assignment,
                         key=state.key),
            key=state.key,
        )

        print("=" * 50)
        print(annotations)
        print("=" * 50)

    if annotations is not None:
        save(annotations["values"])

        if annotations["next"] == True:
            if assignments[selected_assignment] == False:
                update_history(assignment=selected_assignment,
                               username=username)
            state.get_next = True

        state.key = secrets.token_hex(128)
        st.experimental_rerun()
コード例 #16
0
def main():
    try:
        st.set_page_config(page_title="Hyperactive Progress Board",
                           layout="wide")
    except:
        pass

    search_ids = sys.argv[1:]
    backend = StreamlitBackend(search_ids)
    lock_files = []

    for search_id in search_ids:
        st.title(search_id)
        st.components.v1.html(
            """<hr style="height:1px;border:none;color:#333;background-color:#333;" /> """,
            height=10,
        )
        col1, col2 = st.beta_columns([1, 2])

        progress_data = backend.get_progress_data(search_id)

        pyplot_fig = backend.pyplot(progress_data)
        plotly_fig = backend.plotly(progress_data, search_id)

        if pyplot_fig is not None:
            col1.pyplot(pyplot_fig)
        if plotly_fig is not None:
            col2.plotly_chart(plotly_fig)

        last_best = backend.create_info(search_id)
        if last_best is not None:
            last_best = last_best.assign(hack="").set_index("hack")
            st.table(last_best)

        for _ in range(3):
            st.write(" ")

        lock_file = backend._io_.get_lock_file_path(search_id)
        lock_files.append(os.path.isfile(lock_file))

    time.sleep(1)
    if all(lock_file is False for lock_file in lock_files):
        print("\n --- Deleting progress- and filter-files --- \n")

        for search_id in search_ids:
            backend._io_.remove_progress(search_id)
            backend._io_.remove_filter(search_id)

    else:
        print("\n --- Rerun streamlit --- \n")
        st.experimental_rerun()
コード例 #17
0
def create_new_project():
    st.markdown(f"""
            - *Необходимо дать название проекту*
            - *В описании проекта стоит указать цель исследования*
        """)
    name = st.text_input('Название')
    description = st.text_area('Описание')
    save_button = st.button('Сохранить')
    if save_button:
        if _save_project(name, description):
            st.info('Сохранено')
            time.sleep(1)
            session_state.subpage = None
            st.experimental_rerun()
コード例 #18
0
def infopage():
    if not os.path.exists("data/data.json"):
        name_text = st.text_input("Please Enter your name", )
        load_button = st.button("Save")
        if load_button and len(name_text) > 3:
            with open("data/data.json", "w") as f:
                json.dump(
                    {
                        "name": name_text,
                    },
                    f,
                )
                st.experimental_rerun()
                return None
コード例 #19
0
    def recupera_sessione(self):
        scelta = st.text_input("Inserisci il codice")

        if st.button("RECUPERA"):
            #controllo che esista
            trovato = False
            with open("log.json", "r") as fp:
                data = json.load(fp)
                if scelta in data:
                    trovato = True
            if trovato:
                self.status[get_session_id()] = data[scelta]
                st.experimental_rerun()

            else:
                st.error("Sessione inesistente")
コード例 #20
0
def apply_theme_from_session_state():
    """Retrieve theme from session state and apply it to streamlit config."""
    # Only apply if theme in state differs from the current config. This is important
    # to not trigger rerun repeatedly.
    if st.config.get_option(
            "theme.primaryColor") != st.session_state.primaryColor:
        st.config.set_option("theme.primaryColor",
                             st.session_state.primaryColor)
        st.config.set_option("theme.backgroundColor",
                             st.session_state.backgroundColor)
        st.config.set_option("theme.secondaryBackgroundColor",
                             st.session_state.secondaryBackgroundColor)
        st.config.set_option("theme.textColor", st.session_state.textColor)

        # Trigger manual rerun (required to actually apply the theme to the app).
        st.experimental_rerun()
コード例 #21
0
ファイル: main.py プロジェクト: data-hydenv/hydenv-database
def get_db_con(connection: str = None) -> HydenvDatabase:
    # check if the connection has peviously been set
    con = st.session_state.get('connection')
    if con is not None:
        return HydenvDatabase(connection=con)

    else:
        install_page()
    # in any other case
    db = _check_connection(connection=connection)
    if db:
        # if that worked, set the connection
        st.session_state.connection = db.unsafe_get_connection
        st.experimental_rerun()
    else:
        # force the install page
        install_page()
コード例 #22
0
ファイル: dataset.py プロジェクト: HuviX/aviah4ck
def create_dataset():
    st.markdown(
        f"""
        - *Необходимо дать название датасету и загрузить данные с метками или данные без меток*
        - *Данные в архиве формата `.tar`*
        - *Формат данных c метками*
        ```
        ├── {DatasetType.TRAIN}
        │   ├── img0.png
        │   ├── img1.png
        │   ├── img2.png
        │   └── labels.csv
        └── {DatasetType.TEST}
            ├── img3.png
            ├── img4.png
            ├── img5.png
            └── labels.csv
        ```
        - *Формат файла `labels.csv`*
        ```
        image	x	y	width	height
        0.png	70	19	100	    111
        1.png	108	91	89	    82
        2.png	90	19	115	    181
        ```
        - *Формат данных без меток*
        ```
        └── {DatasetType.UNLABELLED}
            ├── img0.png
            ├── img1.png
            └── img2.png
        ```
    """
    )
    name = st.text_input('Название')
    description = st.text_area('Описание')
    dataset = st.file_uploader('Архив c данными', type=['tar', 'tar.gz', 'tar.xz'])

    save_button = st.button('Сохранить')
    if save_button:
        if _save_dataset(name, description, dataset):
            st.info('Сохранено')
            time.sleep(1)
            session_state.subpage = None
            st.experimental_rerun()
コード例 #23
0
ファイル: main.py プロジェクト: data-hydenv/hydenv-database
def change_exercise(tracks, direction='next'):
    # get the current exercise
    session = get_session(tracks, st.session_state.track_id, st.session_state.session_id)
    exercises = session.get('exercises', [])
    ex_id = st.session_state.exercise['id']
    idx = [i for i, e in enumerate(exercises) if e['id']==ex_id].pop()

    # check if it was the last one
    if direction == 'next':
        if len(exercises) == idx + 1:
            idx = 0
        else:
            idx += 1
    else:
        idx = idx - 1 if idx > 1 else 0
    
    st.session_state.exercise = exercises[idx]
    st.experimental_rerun()
コード例 #24
0
    def drop_table(self, table_name: str):
        """
        Delete a table in SQLite3 database.

        Arguments:
        - table_name: The name of table that you want to delete.
        """
        logger.info({"message": "Droping table", "table_name": table_name})

        try:
            cursor = self.conn.cursor()
            cursor.execute("DROP TABLE {}".format(table_name))
            st.success("Table deleted.")
            time.sleep(0.3)
            st.experimental_rerun()
        except Exception as error:
            logger.error(error)
            st.sidebar.error(error)

        logger.info({"message": "Table dropped."})
コード例 #25
0
def stock_data(sym, date_of_data, end_date):
    try:
        ts = TimeSeries(key='SUXOFAIGXM6HEP9Y', output_format='pandas')
        data, meta_data = ts.get_daily_adjusted(symbol=sym, outputsize='full')
        data_date_changed = data[end_date:date_of_data]
        data_date_changed['Ticker'] = sym
        data_date_changed.sort_index(ascending=True, inplace=True)

        return data_date_changed
    except ValueError as ve:
        st.write(
            "Sorry Alpha vantage has a limit of 5 calls per minute, please wait..."
        )
        progress_bar = st.progress(0)
        progress_bar.progress(1)
        time.sleep(60)
        for i in range(99):
            # Update progress bar.
            progress_bar.progress(i + 1)
        st.experimental_rerun()
コード例 #26
0
ファイル: learn_structure.py プロジェクト: Magier/HalGA
def show():
    hp = st.sidebar.beta_expander("Hyperparameters", )
    pop_size = hp.number_input("Population Size",
                               min_value=2,
                               max_value=500,
                               value=50)
    num_elites = hp.number_input("Number of Elites",
                                 min_value=0,
                                 max_value=10,
                                 value=1)
    cx_pr = hp.slider("Crossover Rate", min_value=0.0, max_value=1.0, value=1.)
    mut_pr = hp.slider("Mutation Rate",
                       min_value=0.0,
                       max_value=1.0,
                       value=0.2)

    show_summary()

    if st.button("Start Search"):
        st.balloons()
        st.experimental_rerun()
コード例 #27
0
def rerun():
    st.write("""
        # Programatically rerun your app

        Thanks to a contribution from [SimonBiggs](https://github.com/SimonBiggs),
        you can now re-execute your script from the top to bottom. Please note,
        this is an
        [experimental feature](https://docs.streamlit.io/en/stable/api.html#experimental),
        and subject to change.

        Thanks again [SimonBiggs](https://github.com/SimonBiggs)!

        -----
        """)

    st.code("""
placeholder = st.empty()
stop = st.button("Stop rerunning")
if stop:
    st.stop()

for i in range(10):
    with placeholder:
        st.write(f"Getting ready to rerun in {10-i}")
        time.sleep(1)

st.experimental_rerun()
    """)

    placeholder = st.empty()
    stop = st.button("Stop rerunning")
    if stop:
        st.stop()

    for i in range(10):
        with placeholder:
            st.write(f"Getting ready to rerun in {10-i}")
            time.sleep(1)

    st.experimental_rerun()
コード例 #28
0
ファイル: main.py プロジェクト: data-hydenv/hydenv-database
def manage_session(tracks) -> dict:
    # load the track id
    track_id = st.session_state.get('track_id', False)

    # load the session id
    session_id = st.session_state.get('session_id', False)

    if not session_id or not track_id:
        # select a track
        TRACK = {t['id']: t['name'] for t in tracks}
        track_id = st.selectbox("Track", options=list(TRACK.keys()), format_func=lambda k: TRACK.get(k))

        # select a session
        track = [t for t in tracks if t['id'] == track_id].pop()
        SESSIONS = {s['name']: s['name'] for s in track.get('sessions', [])}
        session_id = st.selectbox("Session", options=list(SESSIONS.keys()), format_func=lambda k: SESSIONS.get(k))

        save = st.button("SELECT")
        if save:
            st.session_state.track_id = track_id
            st.session_state.session_id = session_id
            st.experimental_rerun()
        else:
            st.stop()

    # load the correct exercise
    exercise = st.session_state.get('exercise', None)
    if exercise is None:
        session = get_session(tracks, track_id, session_id)
        for e in session.get('exercises', []):
            if e['id'] in st.session_state.get('solved_exercises', []):
                continue
            else:
                exercise = e
                st.session_state.exercise = exercise
    if exercise is None:
        st.stop()
    return exercise
コード例 #29
0
    def add_table(self, df: pd.DataFrame, table_name: str, norm_dtypes: bool = True):
        """
        Add new table to SQLite3 database.

        Arguments:
        - df: DataFrame that will be converted to a table.
        - table_name: The table name in the database.
        """
        logger.info({"message": "Add new table", "df size": len(df),
                     "table_name": table_name, "norm_dtypes": norm_df_dtypes})

        try:
            if norm_dtypes:
                df = norm_df_dtypes(df)
            df.to_sql(table_name, self.conn, if_exists="replace", index=False)
            st.success("Table created.")
            time.sleep(0.3)
            st.experimental_rerun()
        except Exception as error:
            logger.error(error)
            st.sidebar.error(error)

        logger.info({"message": "New table added."})
コード例 #30
0
def rerun(*args, **kwargs):
    """
    Throws a RerunException
    :return: None

    Usage:

    ```
    from streamlit.callbacks.callbacks import later, rerun
    later(5.0, rerun)
    ```
    """

    raise experimental_rerun()