Beispiel #1
0
def service_requests():
    service = sidebar()
    # service = st.text_input('Service name', 'performFindItem')
    service = st.text_input('Service name', service)
    st.write('The current service is', service)
    # json_str = st.text_area(label="Request parameters to execute",
    #                         value=default_request,
    #                         height=180,
    #                         )
    json_str = st_ace(
        language="json",
        font_size=11,
        # theme="chrome",
        theme="chaos",
        keybinding="sublime",
        value=default_request,
        height=180,
    )
    if st.button("Execute Request"):
        if len(service.strip()) > 0:
            resp = backend.invoke_srv(service.strip(), json.loads(json_str))
            st.markdown(f"service response status code: *{resp.status_code}*")
            try:
                json_obj = resp.json()
                st.json(json_obj)
            except ValueError as e:
                print("not json format")
                st.write(resp.text)
Beispiel #2
0
def editor():
    from streamlit_ace import st_ace
    yaml = st.sidebar.file_uploader("Upload Configuration YAML", type="yaml")
    yaml_content = ""
    if yaml is not None:
        yaml_content = yaml.read().decode('utf-8')
    content = st_ace(language='yaml', value=yaml_content)
Beispiel #3
0
def main():
    st.sidebar.title(":memo: Ace editor")

    content = st_ace(
        placeholder=st.sidebar.text_input("Editor placeholder",
                                          value="Some placeholder."),
        language=st.sidebar.selectbox("Language mode",
                                      options=LANGUAGES,
                                      index=121),
        theme=st.sidebar.selectbox("Theme", options=THEMES, index=31),
        keybinding=st.sidebar.selectbox("Keybinding mode",
                                        options=KEYBINDINGS,
                                        index=3),
        font_size=st.sidebar.slider("Font size", 5, 24, 12),
        tab_size=st.sidebar.slider("Tab size", 1, 8, 4),
        show_gutter=st.sidebar.checkbox("Show gutter", value=True),
        show_print_margin=st.sidebar.checkbox("Show print margin", value=True),
        wrap=st.sidebar.checkbox("Wrap enabled", value=False),
        auto_update=st.sidebar.checkbox("Auto update", value=False),
        readonly=st.sidebar.checkbox("Read-only",
                                     value=False,
                                     key="ace-editor"),
        key="ace-editor")

    st.write(content)
Beispiel #4
0
    def __init__(self):

        st.set_page_config(page_title="Typing Tutor", layout="wide")

        self.tokenizer, self.model = _load_model()

        self.session_state = SessionState.get(
            name="typingSession",
            start_time=0,
            end_time=0,
            num_chars=0,
            text="",
            content="",
        )

        st.markdown(
            "<h1 style='text-align: center; color: black;'>Typing Tutor</h1>",
            unsafe_allow_html=True,
        )

        self.col1, self.col2 = st.beta_columns(2)
        placeholder = st.empty()

        with self.col1:
            self.start_button = st.button("Start!", key="start_button")
            st.subheader("Text to write")

            with placeholder.beta_container():
                st.subheader("Steps to check your Typing speed")
                st.write(
                    "1. When you are ready, click on the start button which will generate code for you to write on the left hand side. A point to note that the timer starts as soon as you click on the start button"
                )
                st.write(
                    "2. Start writing the same code on the code window given on the right hand side. When you're done - press 'CTRL + ENTER' to save your code. **Remember to do this as this ensures that the code you have written is ready for submission**"
                )
                st.write(
                    "3. Lastly, click on Check Speed button to check you writing accuracy and the writing speed. Good luck!"
                )

        with self.col2:
            self.eval_button = st.button("Check Speed", key="eval_button")
            st.subheader("Text Input")
            st.write("")

            self.session_state.content = st_ace(
                placeholder="Start typing here ...",
                language="python",
                theme="solarized_light",
                keybinding="sublime",
                font_size=20,
                tab_size=4,
                show_gutter=True,
                show_print_margin=True,
                wrap=True,
                readonly=False,
                auto_update=False,
                key="ace-editor",
            )
Beispiel #5
0
def render_file(wavfile, transcript_path, PathToFixed):

    TranscriptFile = os.path.join(
        transcript_path,
        wavfile.split(DELIM)[-1].replace(".wav", ".txt"))

    with open(TranscriptFile, 'r', encoding='utf-8') as f:
        data = f.read()
    key = wavfile.split(DELIM)[-1]

    st.subheader("Name of File = " + key)
    st.audio(open(wavfile, 'rb').read(), format='audio/wav')
    content = st_ace(value=data,
                     theme=st.sidebar.selectbox("Theme.",
                                                options=THEMES,
                                                key=key),
                     font_size=st.sidebar.slider("Font size.",
                                                 5,
                                                 24,
                                                 24,
                                                 key=key),
                     tab_size=st.sidebar.slider("Tab size.", 1, 8, 4, key=key),
                     show_gutter=st.sidebar.checkbox("Show gutter.",
                                                     value=True,
                                                     key=key),
                     show_print_margin=st.sidebar.checkbox(
                         "Show print margin.", value=True, key=key),
                     wrap=st.sidebar.checkbox("Wrap enabled.",
                                              value=True,
                                              key=key),
                     key=key)
    st.title(content)

    if st.sidebar.button("Reject"):
        print("Reject", key)
        SessionState.get().current_index += 1
        SessionState.sync()
        SavePickleState(SessionState.get().current_index,
                        key.replace(".wav", ".txt"))
        return

    if st.sidebar.button("Go to next file"):

        FixedTranscript = os.path.join(PathToFixed,
                                       key.replace(".wav", ".txt"))
        print(FixedTranscript)
        open(FixedTranscript, "w", encoding="utf-8").write(content)
        SessionState.get().current_index += 1
        SessionState.sync()
        SavePickleState(SessionState.get().current_index)
def show_source(proj, contract_name):
    from streamlit_ace import st_ace
    sources = proj._sources
    src = sources.get(contract_name)
    content = st_ace(placeholder=st.sidebar.text_input("Editor placeholder.",
                                                       value=''),
                     language='solidity',
                     theme='xcode',
                     keybinding="sublime",
                     font_size=st.sidebar.slider("Font size.", 5, 24, 12),
                     tab_size=st.sidebar.slider("Tab size.", 1, 8, 4),
                     show_gutter=True,
                     show_print_margin=True,
                     wrap=st.sidebar.checkbox("Wrap enabled.", value=False),
                     readonly=st.sidebar.checkbox("Read-only.",
                                                  value=False,
                                                  key="ace-editor"),
                     key="ace-editor")
Beispiel #7
0
def main():
    st.title("Composer")
    st.text('Compose workflows')
    panel = app_panels()

    if panel == 'Service Requests':
        service_requests()
    elif panel == 'Main Entity':
        main_entity(main_ent=st.sidebar.text_input(label='Main entity name',
                                                   value='Person'))
    elif panel == 'Service Meta':
        service_meta(srv_name=st.sidebar.text_input(label='Service Name',
                                                    value='createPerson'))
    else:
        content = st_ace(
            language="json",
            font_size=11,
            theme=st.sidebar.selectbox("Theme", options=THEMES, index=31),
            value=default_request,
        )
Beispiel #8
0
def tutorial(page):
    '''Tutorial to learn how to run Streamlit commands'''
    st.title(page)
    st.write(
        "Now you can have a chance to try yourself! Combine things together and see what you get!"
    )
    st.write("## Happy Streamlit-ing! :tada: :clap:")

    # make a container to hold the st_ace editor, so that the pages can be desplayed below as sample code
    # may not need this but going to try and see
    container = st.beta_container()
    with container:
        trial_code = st_ace('st.balloons()',
                            font_size=15,
                            theme="dawn",
                            language="python")
        # need to save the work of people who input stuff
        # checkbox to save work?
        # button to put it back to start
        exec(trial_code)

    # choose to display any of the pages to see code
    # duplicate widget id NOT fixed, possible solutions:
    # create new functions to display basic commands what have unique keys??? will allow put in columns
    # could add note at the top from people to change their code
    st.markdown("---")
    st.write('Pick the page you want displayed below to list commands')
    page = st.radio('Navigation',
                    ['Basic Commands', 'Layout Commands', 'Advanced Commands'])
    if page == 'Basic Commands':
        basic(page)
    elif page == 'Layout Commands':
        layout(page)
    elif page == 'Advanced Commands':
        advanced(page)
    return
Beispiel #9
0
    elif intent == "list_reverse":
        return f"reverse_list={entity}.reverse()"
    else:
        return "#Instruct with text"


st.title('FB Wit.ai App - DevCoder')
st.sidebar.title(":memo:Code Editor Settings")
st.text('Editor')
content = st_ace(placeholder="Enter your code",
                 height=250,
                 language=st.sidebar.selectbox("Select Language.",
                                               options=LANGUAGES),
                 theme=st.sidebar.selectbox("Editor Theme.", options=THEMES),
                 keybinding=st.sidebar.selectbox("Keybinding mode.",
                                                 options=KEYBINDINGS),
                 font_size=st.sidebar.slider("Font size.", 5, 24, 12),
                 tab_size=st.sidebar.slider("Tab size.", 1, 8, 4),
                 show_gutter=st.sidebar.checkbox("Show gutter.", value=True),
                 show_print_margin=st.sidebar.checkbox("Show print margin.",
                                                       value=True),
                 key="ace-editor1",
                 wrap=True)

MyText = st.text_input("Enter prompt", "Ex: Sort the list 'elements'")
try:
    if st.button('Get Code'):
        response = client.message(MyText)
        intent = response['intents'][0]['name']
        entity = response['entities']['list_name:list_name'][0]['value']

except:
Beispiel #10
0
import streamlit as st
from streamlit_ace import st_ace

"""
# Advent of Code 2020 in Streamlit - 01
"""

"""
## Input
"""

# Load the input
problem_input = st_ace()

# Parse it into a an array of integers.
problem_input = [int(line) for line in problem_input.split('\n') if line]
st.write(problem_input)

# Solve the problem
for i in range(len(problem_input)):
    x = problem_input[i]
    for j in range(i+1, len(problem_input)):
        y = problem_input[j]
        for k in range(j+1, len(problem_input)):
            z = problem_input[k]
            if x + y + z == 2020:
                st.write(f"The answer is `{x} * {y} * {z} = {x * y * z}`")
                st.stop()
st.warning("No answer could be found.")
Beispiel #11
0
        bin_repr = x
    assert len(bin_repr) == 36, "String length must be 36."

    # Add a little counter below for reference
    counter = ''.join(reversed([str(x % 10) for x in range(36)]))

    # All done!
    st.text(f"{sep_by_10s(bin_repr)} {metadata}\n{sep_by_10s(counter)}")


"""
## Input
"""

# Load the input
problem_input = st_ace(height=150)
show_debug_output = st.checkbox("Show debug output")
"""
## Output
"""

memory: Memory = {}
assigmnet_expr = re.compile(r"mem\[(?P<loc>\d+)\] = (?P<val>\d+)$")
for line_num, line in enumerate(problem_input.split('\n')):
    # If in debug mode, show the line.
    if show_debug_output:
        st.write(f'`{line_num}`: line=`"{line}"`')

    # Parse a mask update line
    if line.startswith("mask"):
        mask = line[7:]
def execbox_side(
    body="",
    button_label="Run",
    autorun=False,
    height=None,
    line_numbers=False,
    key=None,
):
    """Display a button widget.
    Parameters
    ----------
    body : str
        The initial code to show in the execbox.
    button_label : str
        The label to use for the "Run" button.
    autorun : bool
        Whether the code should execute with each keystroke.
    height : int or None
        The height of the execbox, in pixels. If None, calculates the height smartly to fill the
        content and a couple more lines.
    line_numbers : bool
        Whether to show line numbers.
    key : str or None
        An optional string to use as the unique key for the widget. If this is omitted, a key will
        be generated for the widget based on its content. Multiple widgets of the same type may not
        share the same key.
    Returns
    -------
    str
        The source code in the execbox.
    """

    body = body.strip()

    if height is None:
        nlines = body.count("\n")
        if nlines < 3:
            nlines = 3
        height = (FONT_SIZE + 2) * (nlines + 1 + EXTRA_LINES)

    kwargs = dict(
        value=body,
        language="python",
        theme="dawn",
        keybinding="vscode",
        font_size=FONT_SIZE,
        height=height,
        show_gutter=line_numbers,
        key=key,
    )

    left_pane, right_pane = st.beta_columns(2)

    # TODO: Find some way to enter small text so we can show a label above the editor, just like
    # Streamlit's normal components.
    # TODO: Make this collapsible.
    with right_pane:
        content = st_ace(**kwargs)

    # TODO: Change AceEditor (or use our own editor frontend) so we don't rerun the script on every
    # keystroke when autorun is False.
    if autorun:
        run = True
    else:
        autokey = hash(
            (body, button_label, autorun, height, line_numbers, key))
        run = st.button(button_label, key=autokey)

    if run:
        # TODO: Allow people to set their own local_scope (so two execboxes call share scopes!). For
        # this we'll likely need to use session state, though.
        local_scope = _new_sandbox()

        with left_pane:
            try:
                # TODO: Add a new container and a `with` block here!
                exec(content, local_scope)
            except Exception as e:
                st.exception(e)

    return content
Beispiel #13
0
        </div>
        """,
                unsafe_allow_html=True)

    st.subheader(":memo: Python ")
    st.text("\n")
    content = st_ace(placeholder='Enter Your Code Here...',
                     language="python",
                     theme=st.sidebar.selectbox("Theme",
                                                options=THEMES,
                                                index=11),
                     keybinding=st.sidebar.selectbox("Keybinding mode",
                                                     options=KEYBINDINGS,
                                                     index=3),
                     font_size=st.sidebar.slider("Font size", 5, 24, 16),
                     tab_size=st.sidebar.slider("Tab size", 1, 8, 4),
                     show_gutter=st.sidebar.checkbox("Show gutter",
                                                     value=True),
                     show_print_margin=st.sidebar.checkbox("Show print margin",
                                                           value=True),
                     wrap=st.sidebar.checkbox("Wrap enabled", value=True),
                     auto_update=True,
                     readonly=st.sidebar.checkbox("Read-only",
                                                  value=False,
                                                  key="ace-editor"),
                     key="ace-editor")

    #sys.base_exec_prefix('90')

    # with stdoutIO() as s:
    #     try:
    #         #sys.exec_prefix(98)
Beispiel #14
0
st.write('### Code editor')
with io.open('strategy-default.py', 'r', encoding='utf8') as f:
    text = f.read()
st.sidebar.title(":memo: Editor settings")
st.write('Hit `CTRL+ENTER` to retest')
st.write('*Remember to save your code separately!*')
content = st_ace(height=1000,
                 value=text,
                 language="python",
                 theme=st.sidebar.selectbox("Theme", options=THEMES, index=6),
                 keybinding=st.sidebar.selectbox("Keybinding mode",
                                                 options=KEYBINDINGS,
                                                 index=3),
                 font_size=st.sidebar.slider("Font size", 5, 24, 15),
                 tab_size=4,
                 show_gutter=st.sidebar.checkbox("Show gutter", value=True),
                 show_print_margin=st.sidebar.checkbox("Show print margin",
                                                       value=True),
                 wrap=st.sidebar.checkbox("Wrap enabled", value=True),
                 readonly=st.sidebar.checkbox("Read-only",
                                              value=False,
                                              key="ace-editor"),
                 auto_update=False,
                 key="ace-editor")
time.sleep(10)
#save content into temporary py and load its strategy
strategy_name = 'temp-' + ''.join(
    random.choices(string.ascii_letters + string.digits, k=8))
with open(strategy_name + '.py', 'w', encoding="utf-8") as the_file:
    the_file.write(content)
                            linkedin_url=linkedin,
                            p1=p1,
                            p2=p2,
                            p3=p3,
                            p4=p4,
                            skills=user_skills,
                            twitter_url=twitter,
                            medium_url=medium,
                            portfolio_url=portfolio,
                            isWaka=isWaka,
                            github_stats_theme=github_stats_theme,
                            isJoke=isJoke,
                            joke_theme=joke_theme,
                            img_url=img_url,
                            img_width=img_width,
                            img_height=img_height)
        st.markdown(download_readme(code), unsafe_allow_html=True)
        st.markdown("---")
        st.markdown(f'''
        ```{code}```
        ''')
        st.markdown("---")
        st.markdown(code, unsafe_allow_html=True)

if page == 'Editor':
    st.subheader("Please Ignore the red cross marks")
    content = st_ace(language='html', theme='cobalt', wrap=True)
    st.markdown(download_readme(content), unsafe_allow_html=True)
    st.markdown('---')
    st.markdown(content, unsafe_allow_html=True)
Beispiel #16
0
            elif col_sum == 12:
                return st.beta_columns(spec)
            if col_sum < 12:
                final_col_width = 12 - col_sum
                extended_columns = tuple(spec) + (final_col_width, )
            return st.beta_columns(extended_columns)[:-1]


"## Try It Out"

default_exec_str = (textwrap.dedent("""
col1, col2, col3 = bootstrap_columns((3, 4, 5))
col1.bar_chart(np.random.rand(10), height=200)
col2.bar_chart(np.random.rand(10), height=200)
col3.bar_chart(np.random.rand(10), height=200)
""".strip()))

exec_str = st_ace(value=default_exec_str,
                  language='python',
                  auto_update=True,
                  height=150)
exec(exec_str)

"## Documentation"

with st.beta_expander('Show bootstrap_columns'):
    st.help(bootstrap_columns)

with st.beta_expander('Show beta_columns'):
    st.help(st.beta_columns)
Beispiel #17
0
    resp = AgGrid(
        df,
        theme="streamlit",
        gridOptions=gb.build(),
        update_mode="MODEL_CHANGED",
        fit_columns_on_grid_load=False,
    )

    st.caption("Click on a row above to learn more about a rule.")
    if len(resp["selected_rows"]):
        code, desc = parse_rule(resp["selected_rows"][0])

        st.subheader("Source")
        st.code(code, language="yaml")

        st.subheader("Example")

        m = re.search(RE_DESC, desc, re.MULTILINE | re.DOTALL)
        example = m.group(3)

        alerts = lint(example, resp["selected_rows"][0])

        st_ace(
            value=example,
            theme="kuroir",
            language="markdown",
            show_gutter=True,
            readonly=True,
            annotations=annotate(alerts),
        )
Beispiel #18
0
    kornia.augmentation.RandomGrayscale(p=0.5),
)
""",
]

selected_transform = st.selectbox("Pick an augmentation pipeline example:",
                                  predefined_transforms)

st.write("Transform to apply:")
readonly = False
content = st_ace(
    value=selected_transform,
    height=150,
    language="python",
    keybinding="vscode",
    show_gutter=True,
    show_print_margin=True,
    wrap=False,
    auto_update=False,
    readonly=readonly,
)
if content:
    #     st.write(content)
    transform = set_transform(content)

# st.write(transform)

# with st.echo():
#     transform = nn.Sequential(
#        K.RandomAffine(360),
#        K.ColorJitter(0.2, 0.3, 0.2, 0.3)
import streamlit as st
from streamlit_ace import st_ace

st.title("Code Editor on Streamlit")

first, second = st.beta_columns(2)

with first:
    st.markdown("## Input")
    code = st_ace(language='python', theme='xcode')

with second:
    st.markdown("## Output")
    #st.markdown("``` python\n"+code+"```")
    st_ace(value=code,
           language='python',
           theme='pastel_on_dark',
           readonly=True)
Beispiel #20
0
def exercise_page(tracks, db: HydenvDatabase):
    # reset button
    reset = st.sidebar.button("Change Track & Session")
    if reset:
        reset_track()
        st.experimental_rerun()

    # main container
    #main = st.container()
    editor = st.sidebar.expander('EDITOR', expanded=True)
    layout = editor.radio('LAYOUT', options=['split', 'column'])
    if layout == 'split':
        main, right = st.columns(2)
    else:
        main = st.container()
        right = st.container()

    # get the exercise
    exercise = st.session_state['exercise']
    
    # build the page
    main.title(exercise['name'])
    body = main.expander('BODY', expanded=True)
    body.write(exercise['body'].get('content', '<i>No description found</i>'), unsafe_allow_html=True)

    # hint
    if 'hint' in exercise:
        hint = main.expander('HINT', expanded=False)
        hint.write(exercise['hint'], unsafe_allow_html=True)

    right.markdown('## Results')
    # main area
    with main.form('SQL input'):
        # check if there is prefill
        prefill = st.session_state.get(f"{exercise['id']}_prefill", exercise['body'].get('prefill', ''))
        
        code_theme = editor.selectbox('Editor theme', options=THEMES, index=2)
        size = editor.selectbox('Editor Size', options=['sm', 'md', 'lg'])
        sql_code = st_ace(
            value=prefill,
            placeholder='Put your SQL here', 
            height=600 if size == 'lg' else 450 if size == 'md' else 200,
            language='sql', 
            theme=code_theme, 
            auto_update=True
        )
        # compare mode


        do_run = st.form_submit_button('EXECUTE')

        if do_run:
            # save the query
            st.session_state[f"{exercise['id']}_prefill"] = sql_code
            
            # run
            result = db.execute(sql_code, json=True)
            solution = db.execute(exercise['solution']['content'], json=True)
            
            # save
            st.session_state.last_run = dict(exercise_id=exercise['id'], result=result)

            # here check if result correct
            res_hash = hashlib.sha256(str(result).encode()).hexdigest()
            sol_hash = hashlib.sha256(str(solution).encode()).hexdigest()
            main.code(f'Your hash:\t{res_hash}\nSolution hash:\t{sol_hash}')
            
            if res_hash == sol_hash:
                event('event', category='exercise_attempt', label=exercise['id'], exercise_id=exercise['id'], solved=True)
                right.success("**Great!** Your soultion was correct.")
                
                # TODO do more
                solved = st.session_state.get('solved_exercises', [])
                if exercise['id'] not in solved:
                    solved.append(exercise['id'])
                    
                    # update session state
                    st.session_state.solved_exercises = solved
                    cookie_manager = stx.CookieManager()
                    cookie_manager.set('solved_exercises', solved, expires_at=dt.now() + td(days=30), key='set_solved')
                    time.sleep(0.3)
            else:
                event('event', category='exercise_attempt', label=exercise['id'], exercise_id=exercise['id'], solved=False)
                right.error(f"Argh!. Not yet.")
    
    # indicate if this exercise has been solved before
    if exercise['id'] in st.session_state.solved_exercises:
        right.success('This task has already been solved')
    else:
        right.info('This task was not yet solved.')
    
    # right column
    run = st.session_state.get('last_run', {})
    if run.get('exercise_id', '-99') == exercise['id']:
        right.dataframe(run['result'])
        # right.json(run['result'])

    # solution
    solution_exp = main.expander('SOLUTION', expanded=False)
    solution_exp.code(exercise['solution'].get('content', ''), language='sql')
    
    # navigate buttons
    l, _, r = st.columns((1, 3, 1))
    go_prev = l.button('PREVIOUS EXCERCISE')
    go_next = r.button('NEXT EXCERCISE')
    if go_prev or go_next:
        change_exercise(tracks, direction='next' if go_next else 'previous')
st.write("Play with Streamlit live in the browser!")

table_data = {'Column 1': [1, 2], 'Column 2': [3, 4]}
st.write(pd.DataFrame(data=table_data))
"""

with editor:
    st.write('### Code editor')
    code = st_ace(value=INITIAL_CODE,
                  language="python",
                  placeholder="st.header('Hello world!')",
                  theme=st.sidebar.selectbox("Theme", options=THEMES,
                                             index=26),
                  keybinding=st.sidebar.selectbox("Keybinding mode",
                                                  options=KEYBINDINGS,
                                                  index=3),
                  font_size=st.sidebar.slider("Font size", 5, 24, 14),
                  tab_size=st.sidebar.slider("Tab size", 1, 8, 4),
                  wrap=st.sidebar.checkbox("Wrap lines", value=False),
                  show_gutter=True,
                  show_print_margin=True,
                  auto_update=False,
                  readonly=False,
                  key="ace-editor")
    st.write('Hit `CTRL+ENTER` to refresh')
    st.write('*Remember to save your code separately!*')

with display:
    exec(code)

with st.sidebar:
    libraries_available = st.beta_expander('Available Libraries')