示例#1
0
def main():
    st.beta_set_page_config(page_title="IPO", page_icon="📈", layout="wide")
    st.title('Stock Charts of Last 100 IPOs')

    with st.spinner('Loading data...'):
        ipo_url = 'https://www.iposcoop.com/last-100-ipos/'
        r = requests.get(ipo_url)
        df_list = pd.read_html(r.text)
        df = df_list[0]
        st.dataframe(df)
    st.markdown('Data source: https://www.iposcoop.com/last-100-ipos')
    st.markdown('---')

    with st.spinner('Loading stock charts...'):
        for t in reversed(df.Symbol):
            url = f'https://finviz.com/chart.ashx?t={t}&ty=c&ta=1&p=d&s=l'
            st.image(url, use_column_width=True)

    st.markdown('---')
    st.markdown('Visualization: https://finviz.com/')

    # Hide footer
    hide_footer_style = """
    <style>
    .reportview-container .main footer {visibility: hidden;}
    """
    # Hide hamburger menu
    st.markdown(hide_footer_style, unsafe_allow_html=True)
    hide_menu_style = """
        <style>
        #MainMenu {visibility: hidden;}
        </style>
        """
    st.markdown(hide_menu_style, unsafe_allow_html=True)
示例#2
0
def main():
    title = "DeepL Indent Shaper"
    st.beta_set_page_config(page_title=title)
    st.title(title)

    sentence_from = st.text_area("Input sentence", height=300)
    sentence_to = shape_sentence(sentence_from)

    st.markdown("""
        ### Result
        ```
        {res}
        ```
    """.format(res=sentence_to))

    st.markdown("""
        <a href="{url}" style="font-size: 20px;" target="_blank">
            <button style="color: #FFFFFF; background: #0D2036; border-radius: 5px; width: 100%; height: 40px;">
                Translate in DeepL
            </button>
        </a>
    """.format(url=build_deepl_url(sentence_to, src="en", dst="ja")),
                unsafe_allow_html=True)

    st.markdown("""
        ---
        ### Links
        * Twitter: [@morio_prog](https://twitter.com/morio_prog)
        * GitHub: [morioprog/deepl_indent_shaper](https://github.com/morioprog/deepl_indent_shaper)
    """,
                unsafe_allow_html=True)
示例#3
0
def main(state=None):
    st.beta_set_page_config(
        page_title="MongoDB TimePass",
        layout="centered",
        initial_sidebar_state="auto",
    )

    logo_uri = get_base_64_img(
        Path(__file__).parent / "assets" / "timepass-logo.png")

    st.sidebar.markdown(logo_uri, unsafe_allow_html=True)

    CONN_URI = st.sidebar.text_input("Connection URI")

    if CONN_URI == "":
        st.sidebar.info("Input a connection URI")
        st.stop()

    current_page = st.sidebar.radio("Go To", list(PAGE_MAP))

    if state.db_client is None or state.CONN_URI != CONN_URI:
        # different sessions can have differnet DB Connections
        state.db_client = MongoDBClient(CONN_URI)
        state.CONN_URI = CONN_URI

    PAGE_MAP[current_page](state=state).write()
示例#4
0
def main():
    st.beta_set_page_config(
        page_title="PWP - Open Source",
        page_icon='https://user-images.githubusercontent.com/52009346/93438445-9c26e400-f8cd-11ea-9183-b6df80ddd318.png'
    )

    st.image('https://user-images.githubusercontent.com/52009346/69100304-2eb3e800-0a5d-11ea-9a3a-8e502af2120b.png',
             use_column_width=True)

    selection = main_selection()

    if selection == 'Wellbore 3D':
        add_well_profile_app()

    if selection == 'Data Collector':
        add_petrodc_app()

    if selection == 'Temperature Distribution':
        add_pwptemp_app()

    if selection == 'Load Cases':
        add_pwploads_app()

    if selection == 'Torque & Drag':
        add_torque_drag_app()

    if selection in ['Temperature Distribution', 'Load Cases']:
        under_construction()

    if selection == 'Visualize Well Logs':
        add_well_logs_app()

    add_footer()

    add_side_bar()
示例#5
0
def main():

    # Define as configurações da página
    st.beta_set_page_config(page_title="Trabalho 1 - Sistemas Operacionais", )

    st.title("Trabalho 1 - Escalonamento de Processos")
    st.write("---------------")
    st.write("**Disciplina:** Sistemas Operacionais")
    st.write("**Aluno:** Diego Santos Seabra")
    st.write("**Matrícula:** 0040251")
    st.write("---------------")
    visualizacao = st.selectbox(label='Escolha o que deseja visualizar',
                                options=opcoes)
    st.write("---------------")

    if visualizacao == '1. Apresentação':
        apresentacao()

    if visualizacao == '2. Definições e Conceitos':
        definicoes_conceitos()

    if visualizacao == '3. Round Robin - Vantagens e Desvantagens':
        vd_round_robin()

    if visualizacao == '4. Round Robin - Demonstração':
        algo_round_robin()

    if visualizacao == '5. Menor Primeiro - Vantagens e Desvantagens':
        vd_menor_primeiro()

    if visualizacao == '6. Menor Primeiro - Demonstração':
        algo_menor_primeiro()

    if visualizacao == '7. Obrigado!':
        obrigado()
def main():

    st.beta_set_page_config(page_title="SML Dashboard",
                            page_icon=None,
                            layout='wide',
                            initial_sidebar_state='auto')
    st.title("Social Media Listening Dashboard")
    st.sidebar.title("Login page")

    st.markdown("This application is a Streamlit dashboard used "
                "for Social Media Listening")
    st.sidebar.markdown("Please select Login and enter username & password")

    st.header("Login Status")

    menu = ["Home", "Login"]
    choice = st.sidebar.selectbox("Menu", menu)

    if choice == "Home":
        st.subheader("Home")
        st.info(
            "To access the dashboard select the login option in the sidebar")

    elif choice == "Login":

        username = st.sidebar.text_input("User Name")
        password = st.sidebar.text_input("Password", type='password')
        if st.sidebar.checkbox("Login"):

            known_hash = user_df['Password'][user_df['Username'] ==
                                             username].iloc[0]
            if pbkdf2_sha256.verify(password, known_hash):
                # the above line returns True or False. If True is returned, we show the main dashboard
                st.success("Logged in as {}".format(username))

                labels = [
                    "People who like streamlit",
                    "People who don't know about streamlit"
                ]
                values = [80, 20]

                # pull is given as a fraction of the pie radius
                fig = go.Figure(data=[
                    go.Pie(
                        labels=labels,
                        values=values,
                        textinfo='label+percent',
                        insidetextorientation='radial',
                        pull=[0, 0, 0.2, 0]  #,hole = 0.2
                    )
                ])

                fig.update_layout(title_text="Demo streamlit app")

                st.plotly_chart(fig, sharing='streamlit')

            else:
                st.warning("Incorrect Username/Password")
示例#7
0
def header():
    # Define as configurações da página
    st.beta_set_page_config(page_title="Trabalho 2 - Sistemas Operacionais", )

    st.title("Trabalho 2 - Substituição de Páginas")
    st.write("---------------")
    st.write("**Disciplina:** Sistemas Operacionais")
    st.write("**Aluno:** Diego Santos Seabra")
    st.write("**Matrícula:** 0040251")
    st.write("---------------")
示例#8
0
def main():
    st.beta_set_page_config(page_title="SRT Logs Analyzer")
    st.markdown("<h1 style='text-align: center;'>SRT Log Analyzer</h1>",
                unsafe_allow_html=True)
    st.markdown("### Upload And Analyse CSV Log File")

    file_buffer = st.file_uploader("Choose a CSV Log File...",
                                   type="csv",
                                   encoding=None)
    if file_buffer:
        uploaded_file = io.TextIOWrapper(file_buffer)
        if uploaded_file is not None:
            df = pd.read_csv(uploaded_file)
            # Checking if the number of the columns is 30
            if df.shape[1] != 30:
                st.warning(
                    f"The uploaded CSV file is not properly formatted SRT Log File."
                )
                st.warning(
                    f"The uploaded file has only {df.shape[1]} columns instead of 30!"
                )
            else:
                # Dropping the SocketID column, since it is not informative
                df.drop(["SocketID"], axis=1, inplace=True)

            # Checking if the log file is for sender or receiving device
            if df.byteSent.iloc[0] != 0:
                sender = True
                st.markdown("### SRT Sender Log:")
            else:
                sender = False
                st.write("### SRT Receiver Log:")

            # Removing redundant columns
            df, num_rows, num_cols = df_format(df, sender)
            min_rtt, max_rtt, avg_rtt = rtt_calc(df)

            # Printing some general stats of the line
            st.write(f"Number of Columns: {num_cols}")
            st.write(f"Number of Rows: {num_rows}")
            st.write(f"Log Duration: {df.Time.iloc[-1]}")
            st.write(f"Defined Latency: {df.RCVLATENCYms.iloc[-1]} ms")
            st.write(f"Minimal RTT: {min_rtt} ms")
            st.write(f"Maximal RTT: {max_rtt} ms")
            st.write(f"Average RTT: {avg_rtt} ms")

            # Generating the Drop-Down Menu with the Different Analysis
            drop_down_menu(df, sender)
示例#9
0
def css_widget(file_name,
               logo_file_name,
               page_title='MyAPP',
               page_icon='🛠',
               layout='centered'):
    st.beta_set_page_config(page_title=page_title,
                            page_icon=page_icon,
                            layout=layout,
                            initial_sidebar_state='auto')
    style = '<style>{}</style>'.format(load_file(file_name))
    style = style.replace('LOGO_WIDE', encode_file(logo_file_name,
                                                   'image/png'))
    style_materials = "<style><link href='https://fonts.googleapis.com/icon?family=Material+Icons' rel='stylesheet'></style>"
    style_showcontrols = """<style>.toolbar, .instructions{ visibility: visible;display: block;}</style>"""
    st.markdown(style + style_materials + style_showcontrols,
                unsafe_allow_html=True)
示例#10
0
文件: main.py 项目: saeeeeru/Last-Row
def main():
    # parse argument
    args = parse_args()

    if args.env == "local":
        base_dir = os.path.join(".")
    elif args.env == "heroku":
        base_dir = os.path.join("https://raw.githubusercontent.com",
                                "saeeeeru", "Last-Row", "master")
    else:
        exit(9)

    # get image
    image_path = os.path.join(base_dir, "reports", "figure", "profile.JPG")
    md_path = os.path.join(base_dir, "scripts", "PROFILE.md")
    if args.env == "local":
        image = Image.open(image_path)
        with open(md_path, "r") as fi:
            profile_md = fi.read()
    else:
        profile_md = requests.get(md_path).content.decode(encoding="utf-8")
        image = requests.get(image_path).content

    # set layout
    st.beta_set_page_config(
        page_title="LiverpoolAnalyzer",
        page_icon=image,
        # layout="wide",
        initial_sidebar_state="expanded")

    # set sidebar
    mode, play = set_sidebar(base_dir, args)

    # instance class
    liverpool_analyzer = LiverpoolAnalyzer(mode, play, base_dir, args)

    if mode == "Annimation with Stretch Index":
        liverpool_analyzer.plot_pitch_control()
    elif mode == "Player Pitch Control Impact":
        liverpool_analyzer.plot_pitch_control()
        liverpool_analyzer.player_pitch_control_impact()
    elif mode == "Analysis Report":
        liverpool_analyzer.show_analysis_report()
    else:
        exit()
示例#11
0
def main():
    st.beta_set_page_config(page_title="DWD Stations")

    st.write("# DWD stations near IMK-IFU/ KIT 🏔🌦")

    data_resolution = select_data_resolution()
    max_station_distance = select_max_station_distance()
    observation_years = select_observation_years()

    closest_stations = find_close_stations(
        dist=max_station_distance, res=data_resolution
    )
    filtered_stations = filter_by_dates(closest_stations, *observation_years)

    st.write(f"Number of stations: {len(filtered_stations)}")

    station_map = create_map(filtered_stations, tereno_stations, max_station_distance)
    folium_static(station_map)
示例#12
0
def main():
    """
    function responsable for run streamlit app
    """
    st.beta_set_page_config(page_title='Mann Kendall')

    st.title(body='Mann Kendall Solution')

    file_upload = st.sidebar.file_uploader(label="Upload Excel File",
                                           encoding=None,
                                           type=["xlsx", "xls"])

    if file_upload:

        results, df = cache_generate_mann_kendall(file_upload)

        st.sidebar.markdown(get_table_download_link(results),
                            unsafe_allow_html=True)

        plot_online(results, df)
示例#13
0
def main():
    """A calculator app with Streamlit components"""

    st.beta_set_page_config(
        page_title=
        "Fx",  # String or None. Strings get appended with "• Streamlit". 
        page_icon="📼",  # String, anything supported by st.image, or None.
        layout=
        "centered",  # Can be "centered" or "wide". In the future also "dashboard", etc.
        initial_sidebar_state="auto")  # Can be "auto", "expanded", "collapsed"

    # ================== Using st.beta_columns ================== #
    col1, col2 = st.beta_columns([3, 1])  # first column 3x the size of second

    choice = "Simple"

    with col2:  # Need to run selections first!
        choice = st.radio("", ["Simple", "Advanced"])

    with col1:
        if choice == "Simple":
            st.header("📠 Simple Calculator")
            html_component(path="html/simple_calc.html")

        elif choice == "Advanced":
            st.header("📺 Video Stream")
            html_component(path="html/webcam2.html", width=500, height=800)

    st.subheader("random dataframe")

    # ================== Mutate data with st.table() ================== #

    df1 = create_df(size=(1, 5))
    my_table = st.table(df1)

    if st.button('add rows'):
        df2 = pd.DataFrame(np.random.randn(3, 5),
                           columns=(f'col{i}' for i in range(5)))
        my_table.add_rows(df2)
示例#14
0
文件: webcam.py 项目: lukexyz/iris
def main():
    st.beta_set_page_config(
        page_title=
        "Video capture",  # String or None. Strings get appended with "• Streamlit". 
        page_icon="📼",  # String, anything supported by st.image, or None.
        layout=
        "centered",  # Can be "centered" or "wide". In the future also "dashboard", etc.
        initial_sidebar_state="auto")  # Can be "auto", "expanded", "collapsed"

    # ================== Using st.beta_columns ================== #
    col1, col2 = st.beta_columns([4, 1])  # first column 4x the size of second

    with col2:
        st.button("refresh")

    with col1:
        st.header("📺 Video Stream")
        st.text(
            'Jeremy Ellis - Webcam capture on Codepen\nhttps://codepen.io/rocksetta/pen/BPbaxQ'
        )
        st.text('Streamlit html component below')
    html_component(path="webcam2.html", width=600, height=600)
示例#15
0
def main():
    st.beta_set_page_config(
        page_title='Assessing the Readiness', page_icon='https://i.ibb.co/vxwPL94/image.png></a>', layout='wide')
    # Download external dependencies.
    # Create a text element and let the reader know the data is loading.
    data_load_state = st.text('Loading... It might takes a while')
    # Load 10,000 rows of data into the dataframe.
    data = load_data()
    # Notify the reader that the data was successfully loaded.
    data_load_state.text("")

    # Render the readme as markdown using st.markdown.
    # readme_text = st.markdown("Make sure it has the structure as seen below with the exact same column names"
    #                         ", same structure for scoring points, same structure for players that participated, and "
    #                          "make sure to use the same date format. Any changes to this structure will break the "
    #                         "application. ")

    # Once we have the dependencies, add a selector for the app mode on the sidebar.
    st.sidebar.title("Menu")
    option = st.sidebar.selectbox('Please select a page',
                                  ('Home', 'Problem Statistics', 'Content Statistics', 'User Statistics', 'User Activities', 'Check Proficiency'))

    if option == "Home":
        home.load(data)
    elif option == "Problem Statistics":
        # with st.spinner('Cleaning data...'):
        #    data = data_preprocessing.clean(data)
        problem_statistics.load(data)
    elif option == "Content Statistics":
        content_statistics.load(data)
    elif option == "User Statistics":
        user_statistics.load(data)
    elif option == "User Activities":
        user_activities.load(data)
    elif option == "Check Proficiency":
        predictions.load(data)
示例#16
0
    )"""

    st.dataframe(DF_meals()
        .loc[dates]
        .pipe(select_level, nutrition_detail_levels[nutrition_detail_level])
        [nutrition_information_kinds[nutrition_information_kind]]
        )

    st.dataframe(DF_calisthenics()
        .loc[dates]
        )

    st.plotly_chart(
        Plot_body(rolling_window), 
        use_container_width=True, 
        )
    st.plotly_chart(
        Plot_nutrition(nutrition_information_kind, rolling_window), 
        use_container_width=True, 
        )

if __name__ == '__main__':

    st.beta_set_page_config(
        page_title='Lifestyle', 
        page_icon=None, 
        layout='wide', 
        initial_sidebar_state='auto'
        )

    main()
"""

import base64
import datetime
import os
from math import ceil, floor
from os import cpu_count
from typing import List, Tuple

import pandas as pd
import streamlit as st
from PIL import Image

from get_azure_data import calculate_price, get_table

st.beta_set_page_config(layout="wide")

st.title("ACT Now! Estimated Azure Costing Tool for Bonsai Experiments")
pd.set_option("display.float_format", lambda x: "%.3f" % x)


@st.cache
def load_image(img):
    im = Image.open(os.path.join(img))
    return im


st.image(load_image("imgs/bonsai-logo.png"), width=70)

st.markdown(
    """_This is a simple calculator for running Azure Batch Jobs with [`batch-orchestration`](https://github.com/BonsaiAI/batch-orchestration)._ It relies on the public pricing information available on [azureprice.net](https://azureprice.net/)."""
示例#18
0
import streamlit as st  # <3
import pickle
from sklearn.feature_extraction.text import CountVectorizer  # processamento de textos

# Lendo os picles que tirei do hambúrguer
model = pickle.load(open('model_clf.pkl', 'rb'))
count_vect = pickle.load(open('count_vect.pkl', 'rb'))

# Configurações gerais da página
st.beta_set_page_config(
    page_title="EM | Previsão de Categoria de Ebooks Infantis",
    page_icon="📚",  # polimento e chiquezas
    layout="centered",
    initial_sidebar_state="expanded",
)


# Funções para formatação html (arquivo .css)
def local_css(file_name):
    with open(file_name) as f:
        st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True
                    )  # último parâmetro: permite formatação html


def remote_css(url):
    st.markdown(f'<link href="{url}" rel="stylesheet">',
                unsafe_allow_html=True)


#local_css("style.css")
#remote_css('https://fonts.googleapis.com/icon?family=Material+Icons')
示例#19
0
import numpy as np
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
import adjustText
from adjustText import adjust_text
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import gseapy as gp
from gseapy.plot import gseaplot, heatmap
import matplotlib.gridspec as gridspec

st.beta_set_page_config(layout="centered")
initial_sidebar_state = "expanded"


def _max_width_():
    max_width_str = f"max-width: 1300px;"
    st.markdown(
        f"""
    <style>
    .reportview-container .main .block-container{{
        {max_width_str}
    }}
    </style>    
    """,
        unsafe_allow_html=True,
    )
示例#20
0
def main():
    st.beta_set_page_config(page_title='Lights Out!',
                            page_icon="💡",
                            initial_sidebar_state='collapsed')
    update_style()

    st.markdown("""<h1 style="text-align:center">Lights Out!</h1>""",
                unsafe_allow_html=True)

    st.markdown("""
        <p style="text-align:justify">Street lighting comprises of 14.8% (9,935 GJ)
         of total energy used by the City of Hobart, and is a major contributor 
         to electrical and greenhouse gas usage in all cities. The City of Hobart 
         spends approximately $1.5 - $2 million dollars a year and would like to 
         investigate strategies to reduce their energy costs and light pollution.</p>
        <p style="text-align:justify">There are over 5,000 street lights in the City 
        of Hobart, where only 300 are managed by the city. The rest of the lights are 
        managed by TasNetworks and are unmetered. This means regardless if the light 
        is on, off, or dimmed, the council pays the full 10 hours a day.</p>
        <p style="text-align:justify">We wanted to investigate 4 main ideas:</p>
        <li>Which bulbs are the most effective, and is it cost-effective to swap bulbs?</li>
        <li>Is it worth metering individual poles to reduce electricity costs from 
        dimming with and without sensors?</li>
        <li>Are solar poles worth the cost?</li>
        <li>Can we make use of IoT and wireless technologies to make our community more 
        sustainable?</li>
        <p style="text-align:justify">To investigate this, we looked into street 
        light data set from the City of Hobart, data on historical energy 
        usage and foot traffic in the CBD, as well as potentially intergrate street 
        into a Smart City.</p>
        """,
                unsafe_allow_html=True)

    LIGHT_FILE = 'light.csv'
    light = pd.read_csv(LIGHT_FILE)

    st.markdown(
        """<h2 style="text-align:center">Idea 1: Phasing out old MV lamps</h2>""",
        unsafe_allow_html=True)
    st.write("""
    <p style="text-align:justify">We wanted to evaluate each type of bulb for their 
    operational cost over 25,000 hours by standardising their wattage to 1700 lumens. 
    Assuming an electrical cost of $0.4/kWh, we can see the LED and HPS bulbs are 
    twice as efficient as MV and CFL bulbs. MV and CFL bulbs are the prime candida
    tes for replacement given their wattage to lumens inefficiency.</p>
    <p style="text-align:justify">Assuming the fixed cost of changing a bulb to a 
    different type is $700 and that we hope to recoup our expenses in 5 years, we 
    would need a wattage difference of 96 W to justify swapping to a more 
    efficient LED bulb.</p>
    """,
             unsafe_allow_html=True)
    st.plotly_chart(plot_cost(), use_container_width=True)

    st.header('Lighting Map')
    st.write(""" 
    <p style="text-align:justify">We visualised each street light in Hobart to 
    identify trends. We noticed that high wattage HPS and WV lights were used 
    on highways and major roads, with LED and CFL mainly used on minor roads 
    in residential areas.</p>
    <p style="text-align:justify">We recommend swapping out 400 W MV to 250 W 
    LED bulbs on major roads.</p>
    <p style="text-align:justify">We recommend swapping out 125 W and 150 W MV 
    to 18W LED bulbs on minor roads.</p>
    <p style="text-align:justify">Possible MV to LED swap outs have been 
    located in the map below.</p>
    """,
             unsafe_allow_html=True)
    st.plotly_chart(plot_lighting_map(light), use_container_width=True)

    st.markdown(
        'Below you can select which lamp type to view its distribution in Hobart:'
    )
    lamp_type = st.selectbox('', ['MV', 'CFL', 'LED', 'HPS'])
    lamp_type_desc_dict = {
        'MV':
        """
        <p style="text-align:justify">MV bulbs are the least efficient 
        and we recommend swapping them when applicable.</p>
        <p style="text-align:justify">We recommend swapping 400 W MV to 
        250 W LED bulbs on major roads. This is assuming that 250 W LED 
        lights have the equivalent luminosity to 250 W HPS lights. This 
        has the potential saving of $219 in electrical costs per annum, 
        and there are 155 possible replacements.</p>
        <p style="text-align:justify">We recommend swapping out 125W and 
        150 W MV to 18 W LED bulbs on minor roads.</p>

        """,
        'CFL':
        """
        <p style="text-align:justify">Due to the low wattage of CFL bulbs, 
        there are no gains from swapping them out into LEDs.</p>
        """,
        'LED':
        """
        <p style="text-align:justify">LED lights are our lights of choice 
        due to efficiency, life-span and ability to be dimmed. They are 
        the most used lights in smart cities and is the recommended light 
        for future-proofing. The light is directed to the ground with 
        minimal light pollution. For these reasons we recommend swapping 
        into LED lamps.</p>
        """,
        'HPS':
        """
        <p style="text-align:justify">The efficiency of HPS and LED lamps 
        are similar, there is no cost-benefit of swapping them to LEDs. 
        Dimming is not ideal for HPS bulbs as they take time to reach 
        maximum luminosity and it may reduce their life-span.</p>
        """
    }
    st.markdown(lamp_type_desc_dict[lamp_type], unsafe_allow_html=True)
    st.plotly_chart(plot_lamp_hist(light, lamp_type), use_container_width=True)

    st.markdown(
        """<h2 style="text-align:center">Idea 2: Metering, dimming and sensors</h2>""",
        unsafe_allow_html=True)

    st.markdown("""
    <p style="text-align:justify">For the council to see monetary benefit 
    from dimming with or without sensors, individual metering would need 
    to be installed on each light pole. We have focused our attention on 
    dimming in residential areas, as they are most likely the areas with 
    the most downtime at night. We have chosen not to consider dimming on 
    highways and major roads due to safety reasons.</p>
    <p style="text-align:justify">Dimming already efficient 18 W LED lights in 
    residential areas have minuscule gains of 3 hours saved per night. This is 
    an annual saving of $8 per meter installed per year. Given an expensive 
    upfront meter box installation cost, we cannot recommend dimming with or 
    without sensors on a purely financial level. However, dimming can reduce 
    greenhouse gas emissions, improve lightbulb lifespan and reduce light pollution.</p>

    """,
                unsafe_allow_html=True)

    st.markdown(
        """<h2 style="text-align:center">Idea 3: Adapting to solar</h2>""",
        unsafe_allow_html=True)

    st.markdown("""
    <p style="text-align:justify">Solar poles are powered by sun, a renewable
     energy source.</p>
    <p style="text-align:justify">We wanted to investigate and weigh up the 
    benefits and costs of installing solar poles as a permanent electrical 
    solution.</p>
    <p style="text-align:justify">Advantages:</p>
    <li>Solar poles take street lights off the grid permanently, which means 
    permanent electricity savings from usage per kilowatt hour as well as 
    network charges</li>
    <li>The lights are invulnerable to electricity outages, which provides 
    added safety to the city</li>
    <li>Solar poles have an average lifespan of 20 years and have low maintenance 
    costs associated with it</li>
    <li>Some solar poles also have a sensor option available, which can reduce 
    light pollution in areas that are deserted at night</li>
    <p style="text-align:justify">Disadvantages:</p>
    <li>High upfront cost</li>
    <li>Solar energy is dependant on weather factors such as UV index, cloud 
    coverage and daylight hours</li>

    <p style="text-align:justify">Our recommendation plan is a 4 phase solar 
    pole rollout for the City of Hobart. We looked at major foot traffic 
    areas to help determine which locations would provide the greatest 
    social benefit to help attract people towards the city centre. We 
    also made sure each phase was within the City of Hobart's annual 
    street light budget, making this a realistic plan. Using this information, 
    we created a visualization that shows the streets involved during each 
    phase and the annual savings from reduced energy and network costs.</p> 
    """,
                unsafe_allow_html=True)

    year_dict = {
        'Year 1': [1],
        'Year 2': [2],
        'Year 3': [3],
        'Year 4': [4],
        'All Years': [1, 2, 3, 4],
    }
    st.markdown("""
    <p style="text-align:justify">In the drop down box you can select the 
    phases to see the spread of solar poles in the city, as well as the 
    annual savings per pole.</p>
    """,
                unsafe_allow_html=True)
    year_select = st.selectbox('', list(year_dict.keys()))
    solar_df = pd.read_csv('./solar_pole_table.csv')
    st.plotly_chart(plot_solar(solar_df, year_select),
                    use_container_width=True)
    solar_df = solar_df.drop(['Longitude', 'Latitude'],
                             axis=1)[solar_df['Implementation year'].isin(
                                 year_dict[year_select])]
    solar_df = df_float_formatter(solar_df, formatter="{:.2f}")
    solar_df

    st.markdown(
        """<h2 style="text-align:center">Idea 4: Embracing a smart future</h2>""",
        unsafe_allow_html=True)
    st.markdown("""
    <p style="text-align:justify">We know cities are constantly on the lookout 
    for smart solutions to enhance city vibrancy and promote local businesses 
    by attracting local and overseas tourists. With this in mind, we propose 
    building on the sustainable solar poles and adding in street friendly 
    features such as a solar charging station for small devices.<br>
    We also believe we can harness the power of IoT by connecting each 
    solar pole to a cloud. Councils are able to utilise these wireless 
    connections by feeding in inputs such as weather forecasts, UV 
    index, cloud coverage. This allows the council to adjust the dimming 
    to accommodate for special public events such as New Years, 
    which may draw large crowds out into the city late at night. 
    This flexibility provides the citizens with safe lighting, as 
    well as meeting the council's energy and sustainability requirements.</p>
    """,
                unsafe_allow_html=True)
    smart_city = Image.open(os.path.join('asset', 'smart_city.png'))
    st.image(smart_city,
             caption='How poles can be intergrated into Smart City',
             use_column_width=True)

    st.header('About')
    st.markdown("""
    <p style="text-align:justify">
    This web app is part of a submission for GovHack 2020 Hackathon, made by 
    <a href="https://www.linkedin.com/in/arnab-mukherjee-data/">Arnab Mukherjee</a>, 
    <a href="https://www.linkedin.com/in/emily-shen/">Emily Shen</a>, 
    <a href="https://www.linkedin.com/in/hengwang322/">Heng Wang</a>, and 
    <a href="https://www.linkedin.com/in/alfred-zou/">Alfred Zou</a>.
    <br>
    Feel free to check out our <a href="https://hackerspace.govhack.org/projects/lights_out">project page</a> 
    and <a href="https://github.com/hengwang322/lights_out">the repository</a>! 
    
    </p>""",
                unsafe_allow_html=True)
示例#21
0
import streamlit as st
import random
import sys

titles = ["Hello", "Hi", "Howdy"]
icons = [":shark:", ":cat:", ":hamburger:", ":bomb:"]

st.beta_set_page_config(
    page_title=random.choice(titles),
    page_icon=random.choice(icons),
)


"""
# Hello world!
"""

x = st.slider("Foo", 0, 100)
st.write("Selected:", x)

print("Selected:", x)
sys.stdout.flush()
示例#22
0
import pandas as pd
import yfinance as yf
from datetime import datetime, date
import h2o
from h2o.automl import H2OAutoML
#import matplotlib.pyplot as plt
import streamlit as st
import plotly.express as px

#h2o.init()
st.beta_set_page_config(page_title="StockFit", page_icon="📈", layout='wide')

st.title("StockFit")
st.sidebar.subheader("Stock Settings:")
ticker = st.sidebar.text_input('Ticker', value="AAPL")
date_start = st.sidebar.date_input("Start", value=datetime(2016, 1, 1))
date_end = st.sidebar.date_input("End",
                                 value=datetime.today(),
                                 max_value=datetime.today())
st.sidebar.subheader("Model Settings:")
tick = yf.Ticker(ticker)
df = tick.history(start=date_start, end=date_end)
try:
    if df.shape[0] > 0:
        try:
            st.header(tick.info["shortName"])
            st.image(tick.info['logo_url'])
        except:
            st.header(ticker.upper())
        chart = px.line(df, y="Close")
        chart.update_layout(title=f"{ticker.upper()} Stock Close Price Chart",
示例#23
0
import os
import streamlit as st
import pandas as pd
from pathlib import Path

st.beta_set_page_config(page_title='MBOT',
                        page_icon="🚀",
                        layout='centered',
                        initial_sidebar_state='collapsed')

st.title('MBot Setup')
'''
Michigan Bot *(MBOT)* is a small mobile robot used with the Graduate Robotics Systems Laboratory course at University of Michigan.
Below is my intitial work completed on the robot.\n
***Please forgive the cheesy music in my videos 😊***\n


## **Assembly**   
*Timelapse of robot assembly.*
'''

# assembly timelapse
st.video('https://www.youtube.com/watch?v=HLtRFjogLS4')
'''
## **Simple Driving**   
*MBOT driving around using the teleop_simple program.*
'''

# teleop video
st.video('https://www.youtube.com/watch?v=lfkwy5WPypM')
'''
示例#24
0
import streamlit as st
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np
import time

st.beta_set_page_config(
    page_title="Auto Vaidya",
    layout="centered",
    initial_sidebar_state="collapsed",
)

# Just making sure we are not bothered by File Encoding warnings
st.set_option('deprecation.showfileUploaderEncoding', False)


def main():
    menu = ['Home', 'Contact']
    choice = st.sidebar.selectbox("Menu", menu)

    if choice == "Home":
        # Let's set the title of our awesome web app
        st.title('Auto Vaidya')
        # Now setting up a header text
        st.subheader("Automating Healthcare one problem at a time")

        def your_image_classifier(image):
            '''
            Function that takes the path of the image as input and returns the closest predicted label as output
            '''
            # Disable scientific notation for clarity
示例#25
0
from pytube import YouTube, Stream
import streamlit as st
import time
import streamlit.components.v1 as components
import webbrowser
import os
from pathlib import Path

###################################### Code ##########################################

st.beta_set_page_config(page_title='Youtube Video Downloader',
                        page_icon='▶',
                        layout='centered',
                        initial_sidebar_state='collapsed')


def local_css(filename):
    with open('style.css') as f:
        st.markdown('<style>{}</style>'.format(f.read()),
                    unsafe_allow_html=True)


local_css("style.css")

path_to_download_folder = str(os.path.join(Path.home(), "Downloads"))

st.markdown(
    "<h1 style='text-align: center;'><div><span class='highlight blue'><span style='cursor: default'>Youtube Video Downloader &nbsp;&nbsp; No ADS!!</h1>",
    unsafe_allow_html=True)

try:
示例#26
0
#panda is the datareader from web
import pandas as pd
import pandas_datareader.data as web
import requests

import plotly.figure_factory as ff
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px

import numpy as np

from PIL import Image

###From her set General Settings like App/Tab Icon and Name
st.beta_set_page_config(page_title='CLUE Stock Analyzing App',
                        page_icon='logo.jpg')


###From her import Stock List
@st.cache
def stock_list(stock_list):
    df = pd.read_excel('output_2.xlsx', index_col=0)
    #    df.drop(['Change in %', 'Last Price', 'Name.1', 'Letzter Preis', 'Änderung'], inplace=True, axis=1)
    df_li = df.dropna()
    return df_li


df_li = stock_list(stock_list)


### From her Stock List Overview and day price and change
示例#27
0
import joblib, os
import numpy as np
from PIL import Image
import requests
import urllib
import datetime, time

WIDTH = 300
HEIGHT = 300
IMG_PATH = "imgs"
URI = 'https://raw.githubusercontent.com/Chloejay/image_caption_app/master/app/'

st.set_option("deprecation.showfileUploaderEncoding", False)
st.beta_set_page_config(
    page_title="Image translation app",
    page_icon="",
    layout="wide",
    initial_sidebar_state="expanded",
)


@st.cache(show_spinner=False)
def get_file_content_as_string(app_file_path):
    url = URI + app_file_path
    response = urllib.request.urlopen(url)
    return response.read().decode("utf-8")


def run_the_app():
    st.markdown("## `#TODO`")

示例#28
0
           '(https://requests.readthedocs.io/en/master/)',
           '(https://pandas.pydata.org/)', '(https://pandas.pydata.org/docs/)',
           '(https://www.streamlit.io/)',
           '(https://docs.streamlit.io/en/stable/)', '(https://plotly.com/)',
           '(https://plotly.com/python/)')
import pandas as pd
import streamlit as st
import plotly.express as px
import requests
from io import BytesIO
from pyvalet import ValetInterpreter
from custom import download_link, load_time_series
# -------------------------------------------------------------------------------
st.beta_set_page_config(  # Configure page title, icon, layout, and sidebar state
    page_title='Bank of Canada Open Data Explorer',
    page_icon=':bank:',
    layout='wide',
    initial_sidebar_state='expanded')

# Retrieve and display the Bank of Canada's logo on the top of the sidebar
boc_logo = requests.get('https://logos-download.com/wp-content/uploads/'
                        '2016/03/Bank_of_Canada_logo.png')
boc_logo = BytesIO(boc_logo.content)
st.sidebar.image(boc_logo, use_column_width=True)

# Define the web application title
st.title(':bank: Bank of Canada :maple_leaf: [Open Data]'
         '(https://github.com/tylercroberts/pyvalet) Explorer :mag:')
# -------------------------------------------------------------------------------
# Introductory expander section covering overall application details
with st.beta_expander(label='Application details', expanded=True):
示例#29
0
import pandas as pd
import numpy as np
import io
from io import BytesIO, StringIO
import streamlit as st
from VizSerie import VizSerie
from Model import Model

st.beta_set_page_config(
    page_title="Magento 1 - Analise de relatório de vendas")


def viz(data):

    data_viz = VizSerie(data)
    """
    ## Como estão minhas vendas ao longo do tempo?
    
    *Você pode utilizar os filtros abaixo para vizualizar do tempo determinado até o atual*
    """
    data_viz.simplePlotSeries()
    """
    ## Vendas em diferentes series temporais 
    """
    data_viz.plotSubSales()
    """
    ## Qual a minha média de vendas nos dias da semana?    
    """
    data_viz.plotSalesByWeekDays()
    """
    ## Médias de vendas ao longo das semanas do mês?
示例#30
0
import streamlit as st
import os
import io
import json
import pandas as pd
import numpy as np
import folium
from folium import plugins
from streamlit_folium import folium_static


# SetUp for website
st.beta_set_page_config(
     page_title="El Rugido en MX"
)

def local_css(file_name):
    with io.open(file_name) as f:
        st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
    
local_css("style.css")

st.title("¿Dónde rugen los Tigres (6652)")

# Some basic description of the project
st.header("¿Cómo funciona?")
st.markdown("""
        Los miembros de **Tigres 6652** han llenado un [formulario](https://forms.gle/ozU7gcf7KhAXt8mA6),
        espero, con el que pudimos localizar sus puntos en el mapa y cuando tu cargas esta página, se
        revisa automáticamente que estén todos los puntos actualizados o si hay nuevas respuestas.