r"""
EXAMPLE OF A MODULE "DOCSTRING"
   To run this app in a web browser undeployed on the development computer
   run the following command in the Anaconda console.
streamlit run "G:\My Drive\UConn\1-Subjects\Python\STAT476\CODE\StApp1Deploy\StreamlitApp1.py"

# This code is a template for creating a python app to run in a streamlit
# webpage.
# The webpage has a familiar "toolbar on left / plot and output on right"
# layout.

"""

import streamlit as st
from streamlit import session_state as S
   # Writing S.[VarName'] is easier than  st.session_state['VarName']
import matplotlib as mpl
import os
import pandas as pd
import numpy as np
import random

import urllib.request
import urllib

from PIL import Image # Image class from Python PIL package. for 'PIL'.

import openpyxl # Flagged as unused but required for excel behind the scenes.
from io import BytesIO
from pyxlsb import open_workbook as open_xlsb

# Plotly imports. Some may be flagged as unused, but import them anyway.
import scipy  # Used by plotly figure factory behind the scenes.
import plotly
import plotly.express as px
import plotly.figure_factory as ff
import plotly.graph_objects as go

class Global_Variables():  # A class for creating all python global variables.

    ##########################################################################
    # +++ RESOURCES AND OTHER LINKS OR VARIABLES THAT MIGHT CHANGE.
    #   - The values for these variables are all initialized here.

    Debug = False

    #  DETAILS ABOUT THIS MODULE
    # RESOURCE LINKS Etc  Pictures/Videos/Files etc stored online.
    #   Where possible we base our resources in this apps repostitory
    #   at github. If github basing is not possible or inadequate
    #   we have to use another cloud storage site, eg Google drive.Youtube etc.

    # +++ DETAILS ABOUT THIS MODULE
    ThisModule_Project = "Demonstrate and Explore Streamlit and Python."
    ThisModule_Version = "7_00     2022 March 3, 10.29 am EST."
    ThisModule_About = "This module has a done of demo code.. "
    ThisModule_Author = "TB, UConn Math Dept."
    ThisModule_Purpose = ("My first Streamlit app.")
    ThisModule_Contact = "Contacts not supplied."
    ThisModule_Docstring = (__doc__)
    ThisModule_FullPath  = os.path.abspath(__file__)
    ThisModule_FileName = os.path.basename(ThisModule_FullPath)
    ThisModule_ProjectPath = os.path.dirname(ThisModule_FullPath)
    ThisModule_Docstring = (__doc__)

        #https://github.com/ProfBrockway/StreamlitApp1Deploy/raw/main/Resource_ProgramDocumentation.pdf
    # Program Help/Documentation.
    # The raw version will download the pdf automatically.
    Link01 = r"https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_ProgramDocumentation.pdf?raw=true"
    # This will pop up the pdf if googles pdf reader page. But no index or working links.
    Link01 = r"https://docs.google.com/viewer?url=https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_ProgramDocumentation.pdf?raw=true"
    # This will pop up the pdf if googles pdf reader page. But no index or working links.
    Link01 = r"https://smallpdf.com/pdf-reader?url=https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_ProgramDocumentation.pdf?raw=true"
    # The non raw version will go to the file at github and show it in a simple pdf viewer without index.
    Link01 = r"https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_ProgramDocumentation.pdf"
    # Where to report a bug..
    Link04 = r"https://www.ibm.com/us-en?ar=1"
    # A picture stored at this projects repository at github.
    # NOTE: MUST HAVE THE '?raw=true' SUFFIX to extract the pic from github.
    Link06 = r"https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_TigerMoth.jpg?raw=true"
    # This apps code page at Github.
    Link08 = r"https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/0bc950a80603401a54dfb1c6ebe15bc83a362d6e/StreamlitApp1.py"
    # A test pdf online somewhere.
    Link10 = r"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
    # A RAW url to a demonstration CSV file stored at Github.
    Link11 = r"https://raw.githubusercontent.com/ProfBrockway/StreamlitApp1Deploy/main/Resource_TestCSVFile.csv"
    # A url of a video on Youtube.
    Link20 = r"https://youtu.be/nsHl48Wnudc"
    # A url of a video NOT on Youtube. Just a random website.
    Link24 = r"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4"
    # A url of a video on google drive.
    Link30 = r"https://drive.google.com/file/d/18xDRuX9lTpEuSsjtJjFHz4TNnxfKAWdI/view?usp=sharing"
	# Name of downloaded table
    Link40 = "ScreeningTestDataFrame.csv"
    # +++ END OF RESOURCES AND OTHER LINKS OR VARIABLES THAT MIGHT CHANGE.
    ###########################################################################

    # +++ USERS INPUTS (Copied from input widgets and internalized)
    RowsToGenerate = None
    AFloatNumber = None
    ShowLine3 = None
    ShowInput = None
    ShowData = None

    # +++ SUNDRY GLOBAL VARIABLES
    Fig1 = None
    Plot1 = None
    Title_1 = None
    Title_2 = None
    Msg01 = "Please fill out the input boxes and click the 'Plot Now' button."
    Msg_Current = None

    # +++ DATA TO BE PLOTTED
    x = []
    y1 = None
    y2 = None
    y3 = None

    # +++ A PANDAS DATAFRAME
    DataTable = pd.DataFrame(
    columns=["x",
             "y1",
             "y2",
             "y3",
             "random1",
             "sum with a long name",
             "sum with a longer name",
             "random2"]
                           )
# End of Global Variables
G = Global_Variables()    # Instantiate our global variables.

def MainLine():
    # Remember this app is rerun by streamlit every time the GUI is displayed.
    # So we have to keep track of the conversation state and preserve
    # or recreate variables appropriately.

    # Note: Console output from this program - like print("Whatever") - will
    # appear in the streamlit console NOT the usual python console.
    #    If this is too inconvenient, you can write debbuging information etc,
    #    to the streamlit webpage.
    ConsoleClear()  # Clear the internal IPyhon console.

    # If this the initial session create "Static/Persistent" variables
    # and do the "first load only" program initialization.
    if 'Dialog_State' not in S:
        if G.Debug: print("Debug: State=0 Initial load. Display count=1")
        Perform_First_Load_Only_Initialization()
        S.Dialog_State = 1  # Upgrade state so we don't come back here.

    else:  # We are responding to a session reply from the user.
        S.Display_Count += 1  # Count of sessions.
        if G.Debug:
           print("Debug: State=1. Display count=", S.Display_Count)

        # Initalize variables for every run.
        #   Remember nothing outside the Streamlit static/persistant dictionary
        #   is preserved across sessions. So we perform the one time
        #   program initialization once then perform the "every run"
        #   intialization.
        Perform_EveryRun_Initialization()

        # Validate and internalize users'input.
        InputOK = Validate_And_Internalize_User_Input()
        if InputOK == True:
            # Process the users input and generate the data for plotting.
            Process_Users_Data()
            # Plot the data
            Right_Panel_Build()

        else: # There is an error in the users input.
           st.error(G.Msg_Current) # Show the error in the right panel.

    # Having processed all input, we now insert the output into our GUI,
    # display the GUI and then wait for next user input.
    GUI_Build_And_Show()
    return()  # End of function: MainLine.

def Perform_First_Load_Only_Initialization():

    # Initalize variables etc.
    Perform_EveryRun_Initialization()

    # ++++ Set up a typical "About/Help" menu for the webpage.
    #  - The set_page_config command can only be used once per run.
    #  - The set_page_config command be the first Streamlit command used.
    #  - New line marker \n must be preceeded by at least two blanks to work.
    st.set_page_config  (
     page_title = "Webage Header. ",

     page_icon = ":confused:",

     layout="centered", # or "wide".
        # 'wide' gives a bigger display. 'centered' gives a smaller display
        #  Remember that plots and tables etc on the streamlit webpage
        #  can be "blownup" by the user clicking an "expand" icon.
        #  So don't worry if the normal view is too small.

     initial_sidebar_state="auto",

     # \r requires two preceeding spaces to work.
     menu_items={ # These appear as the webpage "about" menu items.
     'Get Help  ':  G.Link01,
     'Report a bug  ': G.Link04,
     'About': '  \rProgram: ' +  G.ThisModule_FileName
            + '  \rProject:  ' + G.ThisModule_Project
            + '  \rProgram Purpose:  ' + G.ThisModule_Purpose
            + '  \rAuthor:  ' +  G.ThisModule_Author
            + '  \rContacts:  ' +  G.ThisModule_Contact
            +  '  \rVersion:  ' + G.ThisModule_Version
               }
                      )

    # +++ CREATE PERSISTENT/STATIC VARIABLES.
    # https://docs.streamlit.io/library/api-reference/session-state
    # During the first load session, we create our "Persistent" variables.
    #  Persistent variables:
    #   - Are stored and created by streamlit in the streamlit
    #     'session state dictionary'
    #   - Are static (preserved) between sessions.
    #   - Are effectively global.
    #   - Have a python dictionary like syntax.
    #   - Are created using the streamlit "session_state" method.
    #      - Eg:  st.session_state['Display_Count'] = 0
    #      - In our case the st.session_State is abbreviated to Static.
    #          - from streamlit import session_state as Static
    #          - Eg: S.Input_SSN'] = 0
    #   - Can be "linked" to a streamlit widget via the widget key= parameter.
    #      - Using the key= parameter on any widget automatically
    #        creates a static variable in the 'session state dictionary'.
    #        But I prefer to declare them explicity as well.
    #      - Any change in the Static linked widget will automatically update
    #      - the linked persistant variable.
    #      - Any change in linked persistant variable will automatically
    #        update the linked widgets value in the Static dictionary.
    #      - The python type of linked variables are specifed by the
    #        linked widget's  "format=" parameter.
    #
    #      - Eg of a Linked persistent variable.
    #         In this initialization section:
    #              S.FirstName'] = "Fred"  # Create a persistant variable.
    #         In the Static creation code:
    #             st.number_input(label=:Enter first name", key="FirstName")
    #         Notice the key is the same as the persistent variable name.

    S.Dialog_State = 0    # Create session Dialog_State variable.
    S.Display_Count = 1   # A debugging Display_Count of sessions.

    # Persistant variables for the users input in the GUI
    S.MsgText = G.Msg01       # A text box for instructions & errors.
    S.RowsToGenerate = 100    # An integer variable.
    S.AFloatNumber = 123.678  # A float variable.

    # Persistant variables for checkboxes.
    S.ShowLine3 = False
    S.ShowInput = True
    S.ShowData = True

    S.UploadedFile = None

    return()  # End of function: Perform_First_Load_Only_Initialization

def Perform_EveryRun_Initialization():
    # Initalize variables for every run.
    #   Remember nothing is preserved across sessions, except variables in
    #   the Static streamlit "session_state" dictionary in its
    #   static/persistant variables.
    #
    #   On the first run we perform the one time program initialization.
    #   On subsequent runs we perform the "every run" intialization to
    #   initialize or reinitialize anything not preserved across
    #   the display/response dialog.
    #
    # Alternatives to repeating initialization here are:
    # (1) Save static/persistant variables in the streamlit "session_state".
    # (2) Make the initialization "static" using streamlit st.cache.
    #      - Use st.cache if the initialization is very time consuming.
    # (3) Initialize in our Global_Variables class (above)
    #     The Global_Variables class is run everytime the app is run.
    #     So it initializes every time streamlit reruns this app.
    #
    # However having an "Every Time" initialization function is good practice.
    # It may be neccessary to make the logic work.
    # Also its less vulnerable to the subtle misbehaviors of alternatives
    # (1) and (2).

    # No code needed here right now. All initialization done in
    # class Global_Variables.

    return()

def Validate_And_Internalize_User_Input():
    # - This function validates the users input.
    # - This function also internalizes the users input.
    #     -Internalization isolates the data processing from the GUI.
    #     -Internalization is achieved by transfering the input values
    #      from the streamlit persistant session_state dictionary to
    #      regular python variables in our global variable class.
    #    - We are using streamlit for our GUI but that may be replaced.
    #      Also streamlit has some nasty bugs we don't want complicating
    #      the data processing code.
    #
    # - The Streamlit input widgets perform validation for data type
	#   and values ranges.
    #      - Eg: A widget can be set up to disallow a number input
	#        that is not numeric.
    #      - So most of the following validations are duplicative.
    #        But I have left them in as belt and suspenders.

    Msg_Set("")

    # Validate and internalize population.
    G.RowsToGenerate, InputOK = Validate_Integer(S.RowsToGenerate)
    if InputOK == False:
        Msg_Set("Error 1006:\n'Rows to Generate' must be an integer.")
        return(False)
    if (G.RowsToGenerate < 50):
        Msg_Set("Error 1008:\n'Rows To Generate' must be [50,150] but not 99.")
        return (False)
    if S.RowsToGenerate == 99:
       Msg_Set("Error 1010:\n'Rows to Generate' is 99 which is not ok.")
       return(False)
    G.AFloatNumber, InputOK= Validate_Float(S.AFloatNumber)
    if G.AFloatNumber == 9:
       Msg_Set("Error 1012:\n'A FloatNumber' is exactly 9 which is not ok.")
       return(False)

    # Internalize checkbox options.
    G.ShowLine3 = S.ShowLine3
    G.ShowInput = S.ShowInput
    G.ShowData = S.ShowData

    # If we fall through here the users input is all valid.
    Msg_Set(G.Msg01)    # The "Please enter test specs" message.
    return(True)  # End of function: Validate_And_Internalize_User_Input

def Process_Users_Data():
    # Process the users input and create the data to be plotted/output.
    G.x = list(range(0, G.RowsToGenerate))
    G.y1 = G.x
    G.y2 = [item ** 1.2 for item in G.x]
    G.y3 = [item * -1 for item in G.x]

    # Create an example Pandas dataframe for plotting etc
    # The values are meaningless.

    i = -1
    for  xvalue in (G.x):
       i = i + 1
       newrow = {'x' : xvalue,
                 'y1':   G.y1[i],
                 'y2':   G.y2[i],
                 'y3':   G.y3[i],
                 'random1': random.random(),
                 'sum with a long name': G.y1[i] + G.y2[i],
                 'sum with a longer name': G.y1[i] + G.y2[i] + + G.y3[i],
                 'random2': random.randint(1,100)
               }
       G.DataTable = G.DataTable.append(newrow, ignore_index=True)

    # Temporary code only.
    # csvfullpath = os.path.join(G.ThisModule_ProjectPath,"TestCSVFile.csv")
    # G.DataTable.to_csv(csvfullpath)

    # End for
    return()  # End of function: Generate_Data_To_Be_Plotted

def Right_Panel_Build():  # Build the main panel on the right. Plot, pics etc.

###############################################################################
    FullScreenIcon_Enlarge() # Make the streamlit full screen icon larger.

###############################################################################
    #  +++ SHOW A CLICKABLE WEBLINK ON OUR WEBPAGE Static.
    #   There are several ways to do this.
    st.markdown("### LINK TO THIS APPS CODE. (DOWNLOADABLE). ")
    st.markdown(f" [Link To Source Code]({G.Link08})"  )
    # Also works: st.write("[Link To The Source Code](%s)" % G.Link08)

###############################################################################
    # +++ CREATE A MATPLOTLIB FIGURE.
    G.Fig1 = mpl.figure.Figure()

    # Create a plot object within the main figure with multiple lines.
    G.Plot1 = G.Fig1.add_subplot(111)
    G.Plot1.clear()  # Clear any current plot in G.Plot1. Just to be sure.

    # Add two lines to the plot
    G.Plot1.plot(G.x, G.y1, label="Y = X", color="red")
    G.Plot1.plot(G.x, G.y2, label="Y = X**2", color="blue")

    # The following shows how the plot can be modified by users requests.
    if G.ShowLine3 == True:
        G.Plot1.plot(G.x, G.y3, label="Y = - X", color="green")

    # Prettyfy the plot.
    G.Plot1.minorticks_on()
    G.Plot1.legend(loc="best", fontsize=14, prop={"weight": "bold"})
    G.Plot1.set_title(Title_Build("long"),fontsize=10,fontweight="bold" )
    G.Plot1.grid(visible=True, which='major', axis="both")
    G.Plot1.set_xlabel("A sample x axis. x=[0,100]")
    G.Plot1.set_ylabel("Y Values Value")

    # Put header(s) before the plot.
    st.subheader(" This Is The Static 'Output Display Panel' On The Right")
    if G.ShowInput == True:
        temptext = f"""
             ### The Values You Entered Are Listed Below.  \r
            {Title_Build()}  \r
            \r
            More Stuff:
            1. Blah blah.
            1. More Blah Blah.
            1. HOW TO ENLARGE OR SAVE THE PLOT :
                1. You can enlarge the plot using the View fullscreen icon. The icon is above and to the right of the plot.
                2. You can save the plot to your computer. Right click on the plot, then use 'save image' or 'copy image'.
            1. Great stuff !
            """
        st.info(temptext )
    else:
        st.subheader("The Values You Entered Are Not Displayed.")

    # Show the plot on the streamlit webpage.
    st.pyplot(G.Fig1)  # st.write(G.Fig1) also Displays a Matplotlib figure.

###############################################################################
    # +++ PROVE EXTERIOR HELPER FUNCTIONS WORK IN STREAMLIT
    st.info("PROVE EXTERIOR HELPER FUNCTIONS WORK IN STREAMLIT")
    from HelperFunctions import Exterior_Helper_Function1
    from HelperFunctions import Exterior_Helper_Function2
    st.text(Exterior_Helper_Function1())
    st.text(Exterior_Helper_Function2())

###############################################################################
   # +++ SHOW A PANDAS DATAFRAME IF USER REQUESTED IT.
    if G.ShowData == True:
       st.markdown("#### The Pandas Data Table You Requested Follows:")
       st.dataframe(data=G.DataTable, width=None, height=None)
       st.write("The data shown is just filler to demonstrate a Pandas "
                      "dataframe.")
       st.write("The dataframe display will automatically offer vertical "
                    "and horizontal scroll bars if required.")
       st.write("You can expand the datatable using the 'View fullscreen' "
                    "icon. The icon is above and to the right of the table.")

###############################################################################
    #  +++ ADD A "DOWNLOAD TO CSV" DATAFRAME BUTTON.
       # - The dataframe is converted to a csv file.
       # - That file is downloaded to the browsers download location.
       #  - There is no "save as" menu. The file name is hard coded.
       DataFrame_CSV = G.DataTable.to_csv().encode('utf-8')
       st.markdown("#### Download The Pandas DataFrame As A CSV File.")
       helpstr = f"""You can save the data frame to your computer using this button.  \r
                    The file will be called {G.Link40}.   \r
                     The file will be saved in your browser's default 'download' location on your computer.
	             """
       st.download_button(label="⚙ Download The DataFrame",
            data=DataFrame_CSV,
            file_name=G.Link40,
            mime= "text/csv",
            key="DownloadCSV_Button",
            help=helpstr,
            on_click=None,
            args=None,
            kwargs=None,
            disabled=False)

###############################################################################
   # +++ SHOW A PRETTYFIED PANDAS DATAFRAME +++++++++++++++++++++++++++++++++++
    # https://towardsdatascience.com/style-pandas-dataframe-like-a-master-6b02bf6468b0
    st.markdown("#### Here is the same dataframe Sorted descending on 'x', with titles and interesting data cells highlighted:")

    # We do this by creating a pandas styling object.
    # Styling should be performed after the data in a DataFrame has been processed.
    # https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

    def PdFormat_Align(s, props="text_align: center;"):
        return props

    def PdFormat_Max(s):  # Highlight the maximum value in all cols
        is_max = s == s.max()  # Create list of joint max vals.
        return ['background-color: lightblue' if v else '' for v in is_max]

    def PdFormat_ByVal(v):
        if v < 0 :    color="red"
        if v == 0:    color="blue"
        if v > 0:     color="green"
        if v == 96:   color = "yellow"
        style = f"color: {color};"
        return (style)

    # Sort and apply color styles to particular col and values of that col.
    # Since this looks at each element in turn we use applymap
    Styler1 = G.DataTable.sort_values(["x"], ascending=False).reset_index(drop=True).style.applymap(PdFormat_ByVal, subset=["x"])

    # Apply color styles to particular col and values of that col.
    # Since this looks at each element in turn we use applymap
    Styler2 = G.DataTable.style.applymap(PdFormat_ByVal, subset=["x"])

    # Apply color styles to all values.
    # Since this looks at each element in turn we use applymap
    Styler3 = G.DataTable.style.applymap(PdFormat_ByVal)

    st.dataframe(Styler1, width=None, height=None)

###############################################################################
    #  +++ ADD A "DOWNLOAD TO EXCEL" DATAFRAME BUTTON. IT KEEPS FORMATING
    #      COLORS ETC.
    def DataFrame_To_Excel(df):
        output = BytesIO()
        writer = pd.ExcelWriter(output, engine="xlsxwriter")
        df.to_excel(writer, index=False, sheet_name="Sheet1")
        workbook = writer.book
        worksheet = writer.sheets["Sheet1"]
        format1 = workbook.add_format({"num_format": '0.00'})
        worksheet.set_column("A:A", None, format1)
        writer.save()
        processed_data = output.getvalue()
        return (processed_data)

    # NOTE !! If we use a styler on the grid we can pass that instead
    #         of the dataframe and preserve all stylings in the excel file.
    df_xlsx = DataFrame_To_Excel(Styler1)
    st.download_button(label="📥 Download DataFrame To An Excel File",
     data=df_xlsx ,
     help="In an Excel file any cell highlighting or other "
          "styling will be preserved.",
     file_name= "df_CSV_To_Excel.xlsx")

###############################################################################
    # Use a styler to format and alter value of columns.
    Styler4 = G.DataTable.style.format(
        na_rep='MISSING', thousands=",",
        formatter={
          ("y1", "random1")        : "{:.6f}",
          ("sum with a long name" ): "{:.2f}",
          ("y2")                   : lambda x: "$ {:,.1f}".format(x*1000),
          ("y3")                   : PdFormat_ByVal
                  })

    #Styler4.set_table_styles([cell_hover, index_names, headers])
    st.dataframe(Styler4)

###############################################################################
    #  +++ SHOW FONT CHANGES IN TEXT USING HTML.
    MDText = StMarkdown(
        "This Demonstrates That We Can Format Text Using HTML.",
         fontsize=22,bold=True,color="blue")
    st.markdown(MDText, unsafe_allow_html=True)

###############################################################################
    # +++ DEMONSTRATE SHOWING A PICTURE FROM THE APPS GITHUB REPOSITORY.
    #   We must get our picture (and other resources) from a web address
    #   because streamlit does NOT have a full backend on its server from
    #   which server disk we might otherwise get resources.
    #   The obvious online repository for resources like pictures is the
    #   github repository for the project. Streamlit drives itself from
    #   the github repository. However github cannot as yet support some
    #   resources. For example a pdf displayed at github does not support
    #   pdf features like indexing or links.
    # Also the video storage is very  limited at github. S
    # So we will be using other online sites to store web
    #   accessable resources. (Eg Youtube)
    # - How to user github to host media for display
    #     https://www.labnol.org/internet/free-file-hosting-github/29092/
    st.markdown("#### DEMONSTRATE SHOWING A PICTURE FROM THE APPS GITHUB REPOSITORY.")
    st.image(G.Link06,
        caption="We used a github url address to get this picture from "
       "  github.   \n"
        "  NOTE: THE URL MUST HAVE THE '?raw=true' SUFFIX to extract the pic"
        "from github.")
    st.write("You can enlarge the picture by clicking the pop up symbol "
             "that appears when you mouse near the top right of the image.")

###############################################################################
    st.markdown("#### DEMONSTRATE SHOWING A SIZED PICTURE .")
    urllib.request.urlretrieve(G.Link06,"img.jpg") # Get image from web.
    img = Image.open("img.jpg")
    img.thumbnail((500, 500)) # Set the desired size. Its one tuple parameter.
    st.image(img)  # Show the resized image.

###############################################################################
    # # +++ DEMONSTRATE DOWNLOADING A PICTURE USING A DOWNLOAD BUTTON.
    # with open(G.Link06, "rb") as file:
    #  btn = st.download_button(
    #          label="Download image",
    #          data=file,
    #          file_name="Resource_TigerMoth.jpg",
    #          mime="image/png"
    #        )

###############################################################################
    # +++ DEMONSTRATE SHOWING A VIDEO FROM YOUTUBE.
    #  Github basing of videos does not allow raw address of large files.
    #  Google basing of videos  does not work because it downloads too slowly.
    #  So until I can figure out how to base videos at github we use Youtube.
    st.markdown("#### DEMONSTRATE SHOWING A VIDEO FROM YOUTUBE.")
    FullURL = G.Link20
    st.video(FullURL)

###############################################################################
    # +++ DEMONSTRATE SHOWING A VIDEO FROM AN ONLINE SOURCE OTHER THAN YOUTUBE.
    #  Github basing of videos does not allow raw address of large files.
    #  Google basing of videos  does not work because it downloads too slowly.
    st.markdown("#### DEMONSTRATE SHOWING A VIDEO AN ONLINE SOURCE OTHER THAN YOUTUBE.")
    st.write("The following video is just on a website somewhere.")
    st.video(G.Link24)

###############################################################################
    # # +++ DEMONSTRATE SHOWING A VIDEO FROM GOOGLE DRIVE.
    # #  Github does not allow raw address of large files.
    # #  Google basing of videos  does not work because it downloads too slowly.
    # st.subheader("DEMONSTRATE SHOWING A VIDEO FROM GOOGLE DRIVE.")
    # st.write("")
    # st.video(G.Link30)

###############################################################################
    # +++ DEMONSTRATE EASY SHOWING A PYTHON DICTIONARY ON A STREAMLIT WEBPAGE.
    df4 ={1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
          4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}

    st.info("DEMONSTRATE SHOWING A PYTHON DICTIONARY ON A STREAMLIT WEBPAGE.")
    st.text("Pretty printing python dictionarys is easy using streamlit.  \n"
                 "We use the st.dataframe feature.")
    st.dataframe(df4)

###############################################################################
    #  +++ SHOW A PLOT USING PLOTLY WHICH HAS GREAT INTERACTIVE CONTROLS
    st.info("DEMONSTRATE A 'PLOTLY' PLOT WITH GREAT INTERACTIVE CONTROLS.")
    st.write("""See my program 'screening test' for a much better example
             of using plotly graphs which are MUCH better than
             matplotlib in screenlit because the plotly plots are
             interactive.              """)
    # Add histogram data
    x1 = np.random.randn(200) - 2
    x2 = np.random.randn(200)
    x3 = np.random.randn(200) + 2
    # Group data together
    hist_data = [x1, x2, x3]
    group_labels = ['Group 1', 'Group 2', 'Group 3']
    # Create distplot with custom bin_size
    fig = ff.create_distplot(
             hist_data, group_labels, bin_size=[.1, .25, .5])
    st.plotly_chart(fig, use_container_width=True)   # Plot!

    #  +++ SHOW A PDF AT GITHUB USING POP UP NEW WEB PAGE
    ###########################################################################
    # +++ MAKE THIS APPS DOCUMENTATION AVAILABLE.
    #   We  base the pdf file in the github repository for the project.
    #   The github using the github link to the address displays
    #   the pdf file in the primitive github pdf view which does not
    #   have basic features, especially the pdf document index.
    #   I have not been able to fix this problem so for now, the pdf
    #   is displayed and the user advised to download it a use a
    #   proper pdf viewer.
    st.info("🟢 THIS APP'S DOCUMENTATION.")

    col1, col2 = st.columns(2)
    with col1:
        st.write(" [ Link To This App's Documentation.]"  "(%s)" % G.Link01)

    with col2:
        # Here we use a trick to display a pop up help message.
        # We use an st.button and load its help parameter with our popup.
        # This works fine when the user hovers the mouse over the button.
        # But when the user clicks the button (as is reasonable) the
        # app is rerun. This doesn't produce any errors but is obviously
        # inefficient. We have to live with this until we find a better
        # method for pop up messages.
        tempstr = ("""You can read this app's documentation at the
        provided link using a primitive pdf reader.  \r
        But by downloading the documentation PDF and viewing it
        on your computer you will be able to navigate the document using
        an index, search, etc.  \r
        You can also see the program documentation by using
        the menu in the top right of this webpage '≡' (3 horizontal lines) then
        select 'GET HELP'. """)
        st.button(label="Help", key="ButtonH1", help=tempstr )

###############################################################################
    # DEMONSTRATE HOW TO USE AN ICON
    # https://share.streamlit.io/streamlit/emoji-shortcodes
    # Just copy and paste the icon from the list.
    # Not all of the :whatever: codes work so best avoid that method.
    st.write("✔  ❌  How to include icons in any text",help="help text here" )

###############################################################################
    # +++ SHOW DEBUGGING INFORMATION.
    if G.Debug:
      st.subheader("Debugging Information Follows.")
      st.write(" The streamlit st.session_state persistant/static "
                    "variables follow.")
      st.write(S)    #  Show all streamlit persistent variables.
                # st.write(G)  # ?v fix so this works For debugging. Show global variables.

###############################################################################
    # +++ DEMONSTRATE AN EXPANDER
    st.subheader("DEMONSTRATE AN EXPANDER.")
    with st.expander("An expanding section that shows debugging information"):
        st.write(""" Write or display anything here. """)
        st.write("You can call any Streamlit command.")
        st.subheader("Debugging Information Follows.")
        st.write(" The streamlit st.session_state persistant/static "
                      "variables follow.")
        st.write(S)    #  Show all streamlit persistent variables.
        # st.write(G)  # ?v fix so this works For  Show global variables.

###############################################################################
    # +++ DEMONSTRATE A CONTAINER, ALLOWS GROUPING OF ITEMS
    st.subheader("DEMONSTRATE A CONTAINER.")
    with st.container():
        st.write("This is inside the container")
        st.write(""" Inserts an invisible container into your app that
                 can be used to hold multiple elements. This allows you to,
                 for example, insert multiple elements into your
                 app out of order.""")
    st.write("This is outside the container")

###############################################################################
    # +++ DEMONSTRATE COLUMN LAYOUT.
    st.subheader("DEMONSTRATE COLUMN LAYOUT. ")
    col1, col2, col3 = st.columns(3)
    with col1:
        st.header("A cat")
        st.image("https://static.streamlit.io/examples/cat.jpg")
    with col2:
        st.header("A dog")
        st.image("https://static.streamlit.io/examples/dog.jpg")
    with col3:
        st.header("An owl")
        st.image("https://static.streamlit.io/examples/owl.jpg")

###############################################################################
    # +++ DEMONSTRATE HOW THE ST.TEXT FEATURE FORMATS TEXT..
    st.info("Demonstrate using st.text with end of line characters")
    Anumber = 678.4325
    helpstr = f"""
    This shows how st.text shows fixed width preformatted text.\r
      A number. {Anumber}    \r
      This will appear on a new line.   \r
      The will be on another line."""
    st.text(helpstr)

    # +++ DEMONSTRATE A STREAMLIT 'INFO' Box.
    st.info("ℹ  This is a Streamlit 'info' box.")

    # +++ DEMONSTRATE A STREAMLIT 'WARNING' Box.
    st.warning("⚠ This is a Streamlit 'warning' box.")

    # +++ DEMONSTRATE A STREAMLIT 'ERROR' Box.
    st.error("❌ This is a Streamlit 'error' box.")

    # +++ DEMONSTRATE A STREAMLIT 'SUCCESS' Box.
    st.success("✅	This is a Streamlit 'success' box.")

    # +++ DEMONSTRATE A STREAMLIT 'EXCEPTION' Box.
    st.exception("This is a Streamlit 'exception' box.")

    # +++ DEMONSTRATE EMOJIS
    # The emojis supported by streamlit
    #    https://share.streamlit.io/streamlit/emoji-shortcodes
    # Just include the emojis markdown code in any output.
    st.info("The demonstates how easy it is to include emojis in any text:  \n"
            "  \n'white_check_mark ' :white_check_mark: "
            "  \n'pushpin ' :pushpin: " )

###############################################################################
    # DEMONSTRATE READING A CSV FILE FROM THE PROJECT'S GITHUB REPOSITORY.
    temptext = """
    ### DEMONSTRATE READING A CSV FILE FROM THE PROJECT'S GITHUB REPOSITORY.  \n
          THIS ALLOWS YOU TO HAVE A DATABASE AVAILABLE TO THE DEPLOYED
          APP WITHOUT THE NEED OF A WEB HOSTING BACKEND.  \n
            """
    st.info(temptext)
    df2 = pd.read_csv(G.Link11)
    st.dataframe(data=df2, width=None, height=None)

###############################################################################
    # +++ DEMONSTRATE A STREAMLIT FILE UPLOAD BUTTON.
    # https://pythonwife.com/file-upload-download-with-streamlit/
    st.info("DEMONSTRATE A STREAMLIT FILE UPLOAD BUTTON")
    UploadedFiles = st.file_uploader("Upload a file why not",
                    key="UploadedFile",  #?V Add to static dictionary
                    type="", # Let the user upload any file type
                    help = "Help text appears here.",
                    accept_multiple_files=True,
                    on_change = None, # Callback event
                    args =(), # optional tuple of args to pass to the callback.
                    kwargs = (), # A doctionary of kwargs to pass to  callback.
                    )

    if st.button("Process The Files"):
        # List details of the files uploaded.
        if UploadedFiles is not None:
           # The UploadedFile class is a subclass of BytesIO, and therefore it is
           # "file-like". This means you can pass them anywhere where a file
           # is expected
           i = 0
           for Uploaded_File in UploadedFiles:
    		   # Create a dictionary of the file details, which prints pretty.
               file_details = {"File Index In List Of Files":i,
                               "Filename":Uploaded_File.name,
                               "FileType":Uploaded_File.type,
                               "FileSize":Uploaded_File.size,
                               "InteralID":Uploaded_File.id}
               st.write(file_details)
               i = i + 1

###############################################################################
    ###########################################################################
    # +++ SHOW THIS APPS DOCSTRING
    #  Github basing of videos does not allow raw address of large files.
    #  Google basing of videos  does not work because it downloads too slowly.
    #  So until I can figure out how to base videos at github we use Youtube.
    st.info("🟢  THIS APP's DOCUMENT STRING FOLLOWS.")
    st.text(G.ThisModule_Docstring)

###############################################################################
    # # +++ DEMONSTRATE AN EMPTY CONTAINER. ALLOWS REMOVAL OF ITEMS
    # import time
    # st.subheader("DEMONSTRATE AN EMPTY CONTAINER.ALLOWS REMOVAL OF ITEMS.")
    # with st.empty():
    #     for seconds in range(20):
    #         st.write(f"⏳ {seconds} seconds have passed")
    #         time.sleep(1)
    #     st.write("✔ 1 minute over!")

################################################################################
    # +++ SHOW A TEXT OR CODE FILE STORED ONLINE.

    st.info("🟢  DISPLAY A TEXT OR CODE FILE STORED ONLINE (Github).")
    # At github be sure to get the github 'raw' url for the target file note
    # the regular url. You'll see the 'raw' option when at github.
    CodeUrl ="https://raw.githubusercontent.com/ProfBrockway/StreamlitApp1Deploy/main/HelperFunctions.py"
    file = urllib.request.urlopen(CodeUrl)
    content =  file.read().decode(file.headers.get_content_charset())
    st.text(content)

###############################################################################
    # +++ DEMONSTRATE USING AN EXCEL FILE (Upload then make it a pandas dataframe.")
    # https://towardsdatascience.com/how-to-work-with-excel-files-in-pandas-c584abb67bfb
    st.info("DEMONSTRATE USING AN EXCEL FILE BASED ONLINE IN THE GITHUB REPOSTIORY")
    st.write("Be sure that that remote url of the excel file includes the 'raw' suffix ?raw=true")
    st.write("For pandas to input an excel file you must install a pandas slave program xlrd. pip install xlrd  ")
    xPath = r"https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_TestExcelFile.xlsx?raw=true"
    df_sheet = pd.read_excel(xPath, sheet_name=0)
    st.write("EXCEL FILE FOLLOWS:\n",df_sheet)

    st.info("""########################################################   \r
             STREAMLIT,  PANDAS DATAFRAMES AND EXCEL SECTION FOLLOWS. """)
    #  FOR INSTRUCTION READ THIS LINK:
        # https://coderzcolumn.com/tutorials/python/simple-guide-to-style-display-of-pandas-dataframes#3
    # - set_table_styles(table_styles,axis=0,overwrite=True)  Format whole table
    # - set_td_classes(classes_dataframe) Format individual cells
    #   - set_td_classes works in combination with set_table_styles()
    # - apply(func,axis=0,subset=None) - Well suited for row-wise or column-wise decoration.
    # - applymap(func,subset=None) - Well suited for the decoration of individual cells based on some conditions.
    #
    # https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
    #
    # - USING functions TO STYLE:  https://pandas.pydata.org/pandas-docs/version/0.25.1/user_guide/style.html
    #     Styler.applymap: elementwise
    #     Styler.apply: column-/row-/table-wise

    # - Using Styler to manipulate the display is a useful feature because
    #   maintaining the indexing and datavalues for other purposes gives
    #   greater control. You do NOT have to overwrite your DataFrame to
    #   display it how you like including sorting.

###############################################################################
    # Get a local csv file and read it into a pandas dataframe.
    fpath=r"G:\My Drive\UConn\1-Subjects\Python\STAT476\CODE\StApp1Deploy\TestData1.csv"
    DFS1 = pd.read_csv (fpath)
    # Show the freshly loaded dataframe.
    st.info("DFS1: As read in from 'TestData1.csv'.")
    st.dataframe(DFS1)

###############################################################################
    st.info("DFS1: Lots of DIFFERENT FORMATTING APPLIED ALL AT ONCE.  \r"
            "Highlight min/max/NaN. Also color by sign. Also color columns."
            "Also apply precision. Also alter output eg decimal percent to percent.")
    # Hide does not work.       .apply(PD_Col_Color)\ not working
    StylerA = DFS1.style\
      .hide_columns(["TP","TN"])\
      .format({  # Format cells in each column.
        "Country": "{:s}" ,
        "Prevalence": lambda x: "{:.3f}%".format(x*100), # Alter val to %.
        "ColA": lambda x: "{:.5f}".format(abs(x)),  # Remove sign.
        "ColC": "{:+.2f}",
        "Column DDD": "{:-.2f}",
        "TP": "{:.7f}",
        "TN": "{:+4.0f}",  # integer
            })\
      .set_properties(subset=["Country"],**{"background-color": "red", "color": "white"})\
      .set_properties(subset=["TN"],**{"background-color": "black", "color": "white"})\
      .applymap(PDFormat_Numeric_By_Sign)\
      .highlight_max(color = "lightgreen")\
      .highlight_min(color = "coral")\
      .highlight_null(null_color="yellow")
    st.dataframe(StylerA)

###############################################################################
    st.info("DFS1: DOWNLOAD CSV DATAFRAME TO EXCEL FILE  \r"
            "This download will preserve the colors and stylings of the "
            "displayed dataframe. Usefull if we have highlighted (say) "
            "cells with errors.")
    def to_excel(df):
        output = BytesIO()
        writer = pd.ExcelWriter(output, engine="xlsxwriter")
        df.to_excel(writer, index=False, sheet_name="Sheet1")
        workbook = writer.book
        worksheet = writer.sheets["Sheet1"]
        format1 = workbook.add_format({"num_format": '0.00'})
        worksheet.set_column("A:A", None, format1)
        writer.save()
        processed_data = output.getvalue()
        return (processed_data)

    df_xlsx = to_excel(StylerA)
    st.download_button(label="📥 Download DataFrame To An Excel File",
                       data=df_xlsx ,
                       file_name= "df_CSV_To_Excel.xlsx")

###############################################################################
    st.info("DFS1: HIGHLIGHT ROW(S) ")
    def highlight_rows(row):
        f1 = ""
        value = row.loc["Country"]
        if value == "Canada":
            backcolor = "blue"
            color = "white"
        elif value == "Mexico":
            backcolor = "green"
            color = "white"
        else:
            backcolor = "white"
            color = "black"
        f1 =[f"background-color:{backcolor};color:{color}" for col in row]
        return (f1)

    StylerP = DFS1.style.apply(highlight_rows, axis=1)
    st.dataframe(StylerP)

###############################################################################
    st.info("DFS1: HIGHLIGHT COLUMNS(S) ")
    def highlight_cols(currentcol):
        f1 = ""
        if currentcol.name == "Country":
            backcolor = "blue"
            color = "white"
        elif currentcol.name == "Prevalence":
            backcolor = "green"
            color = "white"
        else:
            backcolor = "white"
            color = "black"
        f1 =[f"background-color:{backcolor};color:{color}" for row in currentcol]
        return (f1)

    StylerQ = DFS1.style.apply(highlight_cols, axis=0)
    st.dataframe(StylerQ)

###############################################################################
    st.info("DFS1: Save the styled dataframe above to a similarly styled xcel file. See 'styled.xlsx' in this programs project folder.")
    StylerR = DFS1.style\
      .applymap(PDFormat_Numeric_By_Sign)\
      .highlight_max(color = "lightgreen")\
      .highlight_min(color = "coral")\
      .highlight_null(null_color="yellow")\
      .to_excel("styled.xlsx", engine="openpyxl")

###############################################################################
    st.info("DFS1: Highlight Pos/Neg/Zero. On JUST 'ColA' and 'ColC'.")
    StylerC = DFS1.style.applymap(PDFormat_Numeric_By_Sign, subset=["ColA","ColC"])
    st.dataframe(StylerC)

###############################################################################
    st.info("DFS1: Highlight Pos/Neg/Zero. On ALL CELLS")
    StylerD = DFS1.style.applymap(PDFormat_Numeric_By_Sign)
    st.dataframe(StylerD)

###############################################################################
    st.info("DFS1: Format cells by column membership.")
    # ‘d’ for integers
    # ‘f’ for floating-point numbers
    # ‘b’ for binary numbers
    # ‘o’ for octal numbers
    # ‘x’ for octal hexadecimal numbers
    # ‘s’ for string
    # ‘e’ for floating-point in an exponent format
    StylerF = DFS1.style.format(
        {
        "Country": "{:s} color:yellow",
        "Prevalence": "{:> 0.5f}",
        "ColA": lambda x: "{:.5f}".format(abs(x)), # Apply a function to alter value.
        "ColC": "{:+.2f}",
        "Column DDD": "{:-.2f}",
        "TP": "{:.7f}",
        "TN": "{:+4.0f}",  # integer
        })
    st.dataframe(StylerF)

###############################################################################
    st.info("DFS1: READ AN ONLNE EXCEL FILE INTO A PANDAS DATAFRAME. USING NATIVE PANDAS") #
    # The excel file is stored at github so we must use the github 'raw' url.
    # Github does not offer the 'raw' url for all files. In that case
    # use the files regular github page then add '?raw=true' to the end.
    urlexcel = "https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_TestExcelFile.xlsx?raw=true"
    df=pd.read_excel(urlexcel, sheet_name="Resource_TestExcelSheet")
    st.dataframe(df)

###############################################################################
    st.info("DFS1: READ A POORLY SUITED ONLINE EXCEL FILE INTO A PANDAS "
         "DATAFRAME. USING NATIVE PANDAS AND openpyxl. "
         "We can specify where the header row is, the cols we want etc, etc.")

    # Native pandas does a great job reading simple xcel files/worksheets.
    # But in cases where the data is not a continuous table starting at
    # cell A1, the results may not be good.
    # Details here:
        # https://pbpython.com/pandas-excel-range.html

    # The excel file is stored at github so we must use the github 'raw' url.
    # Github does not offer the 'raw' url for all files. In that case
    # use the files regular github page then add '?raw=true' to the end.
    urlexcel = "https://github.com/ProfBrockway/StreamlitApp1Deploy/blob/main/Resource_TestExcelFile.xlsx?raw=true"
    df=pd.read_excel(
        urlexcel,
        sheet_name="Resource_TestExcelSheet",
        header=0, # Specify row of the headers (Might not be the first row).
        usecols=["x","y1","y2","y3","random2",]) # Pick cols.
    st.dataframe(df)

def PD_Col_Color (cols):
    ForColor = "yellow"
    BgColor = "pink"
    formstring = ""
    # for col in cols: #.iteritems():
    #     columnSeriesObj = cols[col]
    #     if col.name=="Country":
    #         formstring = f"background-color:{BgColor};color:{ForColor}"
    return (formstring)

    # We do this by creating a pandas styling object.
    # Styling should be performed after the data in a DataFrame has been processed.
    # https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html

def PdFormat_Align(s, props="text_align: center;"):
    return props

def PdFormat_Max(s):  # Highlight the maximum value in all cols
    is_max = s == s.max()  # Create list of joint max vals.
    return ['background-color: lightblue' if v else '' for v in is_max]

def PDFormat_Numeric_By_Sign(v):
    # Style numeric cells depending on positive/negative/zero value.
    # Each cell in the dataframe is passed as v, one by one.
    style= "" # In case the item is not a number.
    color=""  # In case the item is not a number.
    if isinstance(v, (int, float)):
        if v < 0.0 :     color="red"
        if v == 0.0:     color="blue"
        if v > 0.0:      color="green"
        if v == -23.0:   color = "yellow"
        style = f"color: {color};"
    return (style)

    return  # End of function: Right_Panel_Build

def GUI_Build_And_Show():        # Build the GUI.
    # - Our GUI is a streamlit web page with widgets in a vertical toolbar
    #   on the left and a plot and display area on the right.
    #
    # - !!!!! DON'T ADD A "value=" parameter to any input widget. !!!!!!
    #     The "val=" causes error messages about duplicate initialization.
    #
    #  - Widget values are stored in "linked" streamlit persistent variables.
    #     The value input/output to/from each widget is stored in/retrieved
    #     from a streamlit "linked" persistant variable linked to the
    #     widget's by the widgets "key=" parameter. See elsewhere in this
    #     program for an explanation of "linked" static variables.

    # - We now make the sidebar a single form with a single submit button.
    #    With st.form and its form_submit_button, this app only reruns
    #    when you hit the form submit button, NOT at each widget interaction.
    #    https://blog.streamlit.io/introducing-submit-button-and-forms/
    Form1 = st.sidebar.form(key="Form1", clear_on_submit=False)

    with Form1:
        # Add a title to the toolbar on the left.
        MDText = StMarkdown("THIS IS THE TOOLBAR",
           color="green",bold=True,italic=True,fontsize=16,align="center")
        st.write(MDText, unsafe_allow_html=True)

		# Add a form submit button.
        # Every "form" must have exactly one form_submit_button.
        st.form_submit_button(
                    label='Plot Now',
                    on_click=PlotNowButton_Click_Event,
                    help="When you have entered the parameters  \r"
                    "for the calculations click  \r"
                    "this button to draw your plot.",
                    args=(),
                    kwargs=())

        st.warning("The demonstates how easy it is to include emojis in "
                " any text:  \n"
                "  \n'white_check_mark ' :white_check_mark: "
                "  \n'pushpin ' :pushpin: " )

        # Create a textbox for displaying instructions and error messages.
        st.text_area(
            key="MsgText",   # Value will be placed in S.MsgText'].
            label="INSTRUCTIONS",
            height=150,
            max_chars=None,
            help="Watch here for instructions and error messages",
            on_change=None)

        # Create input boxes in the toolbar for our user specifed variables.

        #  Have the user input an integer from a widget.
        st.number_input(
            key="RowsToGenerate", # Value  linked to S.RowsToGenerate'].
            label="Table Rows To Generate",
            min_value=1,       # Be sure all values for this variable are
            max_value=1000,    # specified as integers.
            step=None,         # else streamlit throws an error.
            format="%i",       # Make this variable an integer.
            help="Enter the RowsToGenerate.\nValue [50,150] but not 99",
            on_change=None,
            args=None,
            kwargs=None,
            disabled=False)

        #  Have the user input a float number from a widget.
        st.number_input(
            key="AFloatNumber",  # Linked to placed in S.AFloatNumber'].
            label="A float number",
            min_value=0.00,         # Always add a number after the point
            max_value=80000000.0,   # since the variable is a float.
            step=100.0,            # else streamlit throws an error.
            format="%f",            # Make this variable a float.
            help="Enter any number.\nValue 99 NOT permitted.",
            on_change=None)

        # Add checkboxes for selecting the lines to be shown on plot.
        st.checkbox(key="ShowLine3", label="Show the Line_3 in plot.")
        st.checkbox(key="ShowInput", label="Show The Variables I Input.")
        st.checkbox(key="ShowData", label="Show The Pandas Data Frame.")

    # End of 'with form'.

    return()  # End of function: GUI_Build_And_Show

def PlotNowButton_Click_Event():
    # Not used.
    # This function is Included to demonstrate that streamlit widgets have a
    # typical "callback" event option.
    return()  # End of function: PlotNowButton_Click_Event

def ConsoleClear():  # Clear all output in console.
    try:     # This works regardless of Operating System prevailing.
        from IPython import get_ipython
        get_ipython().magic("clear")
        get_ipython().magic("reset -f")
    except:
        pass
    return()  # End of function: Console_Clear

def Validate_Float(TextString):
    try:
        tempvar = float(TextString)
    except:
        return (0,False)
    else:
        return(tempvar,True)

def Validate_Integer(TextString):
    try:
        tempvar = int(TextString)
    except:
        return (0,False)
    else:
        return(tempvar,True)

def Msg_Set(TextString):
    FormattedText = TextString
    ErrStr = TextString[0:5].upper()
    if ErrStr == "ERROR":
        FormattedText = f"❌ There is an error in your input.    \n{FormattedText}   \nPlease correct and try again."
    S.MsgText = FormattedText
    G.Msg_Current = FormattedText
    return()

def Title_Build(TitleLength = "short"):
    G.Title_1 = str(
                   "Rows To Generate = {:d}   \r".format(G.RowsToGenerate)  +
                   "AFloatNumber = {:.5f}".format(G.AFloatNumber) + "."
                   )
    return(G.Title_1)   #  End of function: Title_Build

def StMarkdown(TextToBeFormated="", color="black",
    fontsize=14,bold=False,italic=False,fontname="Courier",align="left" ):
    # Set a particular font for display as html markdown text.
    weight = ""
    weightend = ""
    if bold:
        weight = "<strong>"
        weightend = "</strong>"
    if italic:
        weight = "<em>"
        weightend = "</em>"
    if bold and italic:
        weight = "<em><strong>"
        weightend = "</em></strong>"

    fs = str(fontsize).strip() + "px"
    md = " ".join(
                  ["<p",
                      "style='",
                              "font-family:", fontname, ";",
                              "color:", color, ";",
                              "font-size: ",  fs, ";",
                              "text-align: ",  align, ";",
                           "'"
                  ">",
                        weight + TextToBeFormated + weightend ,
                  "</p>"]
               )
    return(md)  # End of function: StMarkdown

def FullScreenIcon_Enlarge():
    # This function increases the visibility of the Streamlit
    # full page icon. It injects css code using markdown.
    css = """
         button[title="View fullscreen"]
         {background-color: #004170cc; left: 2; color: white; }

         button[title="View fullscreen"]:hover
         {background-color: #004170; color: white; } """

    st.markdown( "<style>" + css + "</styles>", unsafe_allow_html=True)
    return() # End of function: FullScreenIcon_Enlarge

MainLine()   # Start this program.


class BucketConst:
    create = 'create_bucket'
    create_by_region = 'create_bucket_by_region'
    exception_status = 417
    exception_message = 'Occurred some error'
    status_code = {'invalid_bucket_name': 101, 'success': 200}
    status_message = {
        'invalid_bucket_name': 'The name of bucket is invalid.',
        'success': 'The operation was success'
    }


import os

x_list=[]
#add values to the list by looping
for i in range(30):
    x_list.append("Day {}".format(i+1))

print(x_list)

for items in x_list:
    os.mkdir(items)


import asyncio
from asyncio.proactor_events import _ProactorBasePipeTransport
import pprint
import os
from dotenv import load_dotenv
import logging

import scripts.Blockchains as Blc
import scripts.Controller as Ctr
from scripts.Models import Route
from scripts.Utills import silence_event_loop_closed, readJson, profiler

_ProactorBasePipeTransport.__del__ = silence_event_loop_closed(  # type: ignore
        _ProactorBasePipeTransport.__del__)

load_dotenv()

def formCache():
    cache = readJson('data\\SampleCache.json')
    result = {}
    for k, v in cache.items():
        temp = {}
        for i, j in v.items():
            name = i.split('_')
            temp[Blc.Token(name[0], name[1])] = j
        result[k] = temp

    return result

def forge():
    url3 = f'https://solitary-few-flower.bsc.quiknode.pro/{os.environ.get("Quicknode")}'
    Chain = Blc.BSC(url3)
    Cont = Ctr.Controller(blockchain=Chain, testing=False)
    routes = Chain.getArbRoute(save=False)
    cache = asyncio.run(Chain.buildCache(routes=routes, save=True))
    arbs = Cont.findAll(cache=cache, routes=routes)
    print(arbs)

def findALlTest():
    route = {
        "swaps": [
            {
            "fro": {
                "name": "WBNB",
                "address": "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
            },
            "to": {
                "name": "BSC-USD",
                "address": "0x55d398326f99059fF775485246999027B3197955"
            },
            "via": {
                "name": "pancakeswap_v2",
                "pair": "0x16b9a82891338f9bA80E2D6970FddA79D1eb0daE",
                "fee": 99750,
                "router": "0x10ED43C718714eb63d5aA57B78B54704E256024E"
            }
            },
            {
            "fro": {
                "name": "BSC-USD",
                "address": "0x55d398326f99059fF775485246999027B3197955"
            },
            "to": {
                "name": "WBNB",
                "address": "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
            },
            "via": {
                "name": "pancakeswap_v2",
                "pair": "0x16b9a82891338f9bA80E2D6970FddA79D1ebbbbE",
                "fee": 99750,
                "router": "0x10ED43C718714eb63d5aA57B78B54704E256024E"
            }
            }
        ],
        "simplyfied_short": "WBNB_3bc095c BSC-USD_3197955 pancakeswap_v2 - BSC-USD_3197955 WBNB_3bc095c pancakeswap_v2",
        "UsdValue": 283.54,
        "EP": 0,
        "rates": [],
        "capital": 0
    }
    cache = {
        "0x16b9a82891338f9bA80E2D6970FddA79D1eb0daE":
        {
            Blc.Token(
                name="WBNB",
                address="0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
            ): 500,
            Blc.Token(
                name="BSC-USD",
                address="0x55d398326f99059fF775485246999027B3197955"
            ): 600
        },
        "0x16b9a82891338f9bA80E2D6970FddA79D1ebbbbE":
        {
            Blc.Token(
                name="WBNB",
                address="0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
            ): 700,
            Blc.Token(
                name="BSC-USD",
                address="0x55d398326f99059fF775485246999027B3197955"
            ): 400
        }
    }
    Chain = Blc.BSC()
    Cont = Ctr.Controller(blockchain=Chain, testing=True)
    arbs = Cont.findAll(cache=cache, routes=[Blc.Route.fromDict(route)])
    print(arbs)

async def main():
    # url = f'https://bsc.nownodes.io/{os.environ}'
    url3 = f'https://solitary-few-flower.bsc.quiknode.pro/{os.environ.get("Quicknode")}'
    Chain = Blc.BSC(url=url3)
    # Chain.buildGraph()
    routes = Chain.getArbRoute(save=False)
    await Chain.buildCache(routes=routes, save=True)
    # pprint.pprint(Chain.exchanges)

if __name__ == '__main__':
    # asyncio.run(main())
    # forge()
    # findALlTest()
    pass


# Advent of Code 2020, Day 10
# (c) blu3r4y

from itertools import groupby

import numpy as np

from aocd.models import Puzzle
from funcy import print_calls, lmap, ilen, collecting
from sympy import tribonacci

@print_calls
def part1(jolts):
    # number of 1-step and 3-step differences multiplied
    bins = np.bincount(np.diff(jolts))
    return bins[1] * bins[3]

@print_calls
def part2(jolts):
    # product of permutations that each run
    # of 1-step differences allows for
    lengths = consecutive_lengths(jolts)
    perms = permutations(lengths)
    return np.prod(perms)

@collecting
def consecutive_lengths(arr):
    diffs = np.diff(arr)
    for group, values in groupby(diffs):
        if group == 1:
            yield ilen(values)

@np.vectorize
def permutations(n):
    return 1 if n < 2 else tribonacci(n + 1)

def load(data):
    jolts = lmap(int, data.split("\n"))
    jolts = [0] + jolts + [max(jolts) + 3]
    return sorted(jolts)

if __name__ == "__main__":
    puzzle = Puzzle(year=2020, day=10)

    ans1 = part1(load(puzzle.input_data))
    # puzzle.answer_a = ans1
    ans2 = part2(load(puzzle.input_data))
    # puzzle.answer_b = ans2


import sys
sys.stdin = open('input.txt', 'r')
input = sys.stdin.readline

class Node():

    def __init__(self, item, left, right):
        # item은 본인 (root node가 됨), left, right는 각각 child node가 됨.
        self.item = item
        self.left = left
        self.right = right
# Node 생성 Node는 자기 자신의 값인 item과 child node의 위치인 left와 right를 가짐.

def preorder(node):
    print(node.item, end='')
    if node.left != '.':
        preorder(tree[node.left])
    if node.right != '.':
        preorder(tree[node.right])
    # 전위 순회 root > left child > right child 순으로 순회함.

def inorder(node):
    if node.left != '.':
        inorder(tree[node.left])
    print(node.item, end='')
    if node.right != '.':
        inorder(tree[node.right])
    # 중위 순회 left > root > right 순으로 순회함.

def postorder(node):
    if node.left != '.':
        postorder(tree[node.left])
    if node.right != '.':
        postorder(tree[node.right])
    print(node.item, end='')
    # 후위 순회는 left > right > root 순으로 순회함.

N = int(input())
tree = {}
# 노드를 엮어줄 트리 생성 딕셔너리로 받는 이유
# TypeError: list indices must be integers or slices, not str 때문.

for i in range(N):
    node, left, right = map(str, input().split())
    tree[node] = Node(node, left, right)
# 트리에 입력받은 노드 값 입력
# tree[A] = left, right, root node

preorder(tree['A'])
print()
inorder(tree['A'])
print()
postorder(tree['A'])


import numpy as np
import sklearn.datasets as ds
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

## Train an SVM ##

def my_SVM(X_train, Y_train, X_test, Y_test, kernel=None, lamb=0.01, num_iterations=200, learning_rate=0.1):
    ## X_train: Training set of features
    ## Y_train: Training set of labels corresponding to X_train, in 0/1 format
    ## X_test: Testing set of features
    ## Y_test: Testing set of labels correspdonding to X_test, in 0/1 format
    ## lamb: Regularization parameter
    ## num_iterations: Number of iterations.
    ## learning_rate: Learning rate.

    n,p = X_train.shape
    ntest = X_test.shape[0]
    beta = np.random.randn(p+1,1)

    X1 = np.c_[np.repeat(1,n).reshape(n,1),X_train] #shape:n*(p+1), including intercept
    X1test = np.c_[np.repeat(1,ntest).reshape(ntest,1),X_test]
    Ytrain = 2 * Y_train-1 #change to -1/1 format
    Ytest = 2 * Y_test-1

    acc_train = np.zeros((num_iterations,1))
    acc_test = np.zeros((num_iterations,1))

    if kernel == None:
        for it in range(num_iterations):
            score = np.dot(X1,beta)
            delta = score * Ytrain <1 # filter out misclassified instances

            # Primal gradient descent
            dbeta = np.sum(np.repeat(delta * Ytrain,p+1,axis=1)*X1,axis=0).reshape(p+1,1)/n
            beta = beta + learning_rate*dbeta
            beta[1:(p+1)] = beta[1:(p+1)] - lamb*beta[1:(p+1)]
            acc_train[it] = np.mean(np.sign(np.dot(X1, beta))==Ytrain)
            acc_test[it] = np.mean(np.sign(np.dot(X1test,beta))==Ytest)
        #             if it % 10 == 0:
        #                 print("Training Accuracy: ", acc_train[it])
        #                 print("Testing Accuracy: ", acc_test[it])
        Y_train_pre = (np.sign(np.dot(X1, beta))+1)/2 # convert to original scales
        Y_test_pre = (np.sign(np.dot(X1test, beta))+1)/2

    if kernel == 'Gaussian':
        alpha = np.zeros((n,1)).reshape(n,1)
        delta = np.zeros((n,1))
        C=1

        K = np.zeros((n,n))
        for i in range(n):
            for j in range(n):
                K[i,j] = np.exp(-10*np.sum((X1[i,]-X1[j,])**2))
        Ktest = np.zeros((n,ntest))
        for i in range(n):
            for j in range(ntest):
                Ktest[i,j] = np.exp(-10*np.sum((X1test[i,]-X1test[j,])**2))
        z = np.dot(K,alpha).reshape(n,1)
        Q = np.repeat(Ytrain, n, axis = 1)* K* np.repeat(Ytrain.T, n, axis = 0)

        # Dual greedy coordinate descent
        for it in range(num_iterations):
            for i in range(n):
                delta[i] = max(-alpha[i], min(C-alpha[i],(1-z[i])/Q[i,i]))
            index = np.argmax(delta)
            #             index = np.random.randint(n)
            alpha[index] = alpha[index] + delta[index] # update alpha
            z = z + (Q[:,index]*delta[index]).reshape(n,1)
            Y_train_pre = np.sign(np.sum(alpha * Ytrain * K, axis = 0)).reshape(n,1)
            Y_test_pre = np.sign(np.sum(alpha * Ytrain * Ktest, axis = 0)).reshape(ntest,1)
            acc_train[it] = np.mean(Y_train_pre == Ytrain)
            acc_test[it] = np.mean(Y_test_pre == Ytest)
        #             if it % 10 == 0:
        #                 print("Training Accuracy: ", acc_train[it])
        #                 print("Testing Accuracy: ", acc_test[it])

        Y_train_pre = (Y_train_pre +1)/2
        Y_test_pre = (Y_test_pre +1)/2

    ## Function outputs 4 things:
    ## 1. The accuracy over the training set, acc_train (a "num_iterations" dimensional vector).
    ## 2. The accuracy over the testing set, acc_test (a "num_iterations" dimensional vector).
    ## 3. The final predicted Y_train
    ## 4. The final predicted Y_test

    return acc_train, acc_test, Y_train_pre, Y_test_pre

def testing_example():
    acc_train, acc_test, Y_trainp, Y_testp = my_SVM(
        X_train, Y_train, X_test, Y_test, num_iterations=1000)

    ax = plt.plot(range(len(acc_test)), acc_train, range(len(acc_test)), acc_test)
    plt.title("Simple SVM")
    plt.xlabel('Number of iteration')
    plt.ylabel('Accuracy')
    plt.legend(('Training Accuracy', 'Testing Accuracy'))
    plt.show()

    acc_train, acc_test, Y_trainp, Y_testp = my_SVM(
        X_train, Y_train, X_test, Y_test, kernel='Gaussian', num_iterations=1000)

    ax = plt.plot(range(len(acc_test)), acc_train, range(len(acc_test)), acc_test)
    plt.title("SVM with Gaussian Kernal")
    plt.xlabel('Number of iteration')
    plt.ylabel('Accuracy')
    plt.legend(('Training Accuracy', 'Testing Accuracy'))
    plt.show()


from pyspark.sql import SparkSession
from com.rposam.spark.config.SparkConf import CreateSparkDriver
import sys
import logging
if __name__ == "__main__":

    logging.basicConfig(filename=r"C:\Users\91889\Desktop\WordCountProgram.log",level=logging.INFO)

    logging.info("Creating Spark Driver ...")
    sparkDriver = CreateSparkDriver()

    logging.info("Spark Driver created Successfully ...")
    sc = sparkDriver.sparkContext
    logging.info("Spark Driver Context initialized ...")

    logging.info("Reading inputs from user ...")
    inputDir = input("Please enter input directory \n")
    outputDir = input("Please enter output directory \n")
    logging.info("Entered input:{}".format(inputDir))
    logging.info("Entered output:{}".format(outputDir))

    wordsRDD = sc.textFile(inputDir)
    logging.info("RDD created after file read")
    words = wordsRDD.flatMap(lambda x: x.split(" ")).map(lambda x:(x,1)).reduceByKey(lambda x,y:x+y)
    print(type(words))
    words.saveAsTextFile(outputDir)

    logging.info("Output file generated successfully..")
    sparkDriver.stop()
    logging.info("Spark Driver program terminated successfully")


from mock import Mock

from malcolm.modules.ADOdin.blocks import odin_runnable_block
from malcolm.testutil import ChildTestCase

class TestADOdinBlocks(ChildTestCase):
    def test_odin_detector_runnable_block(self):
        c = self.create_child_block(
            odin_runnable_block,
            Mock(),
            mri_prefix="mri_prefix",
            pv_prefix="pv_prefix",
            config_dir="/tmp",
        )
        assert c.parts["label"].initial_value == "Odin"


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import inkscape.fields

class Migration(migrations.Migration):

    dependencies = [
        ('releases', '0003_auto_20160126_1557'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='platform',
            options={'ordering': ('codename',)},
        ),
        migrations.AddField(
            model_name='release',
            name='background',
            field=inkscape.fields.ResizedImageField(format='PNG', upload_to='release/background', max_width=960, min_height=0, max_height=300, blank=True, min_width=0, null=True),
            preserve_default=True,
        ),
    ]


# https://www.acmicpc.net/problem/2559
import sys

n, k = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
res = [sum(arr[:k])]

for i in range(n - k):
    res.append(res[i] - arr[i] + arr[k+i])

print(max(res))

# 방법은 똑같이 생각났는데 구현을 못함ㅎ list 쓰는 법 아는데... why...


import colorama
import struct
import sys
from socket import socket
import socket
from threading import Thread
from colorama import Fore,Back,Style
from select import select
import time
from termios import tcflush, TCIFLUSH

local_ip = '127.0.0.1'
getch = ""
bufferSize = 1024
TeamName = b'Danieliel'
client_start_listening = f'Client started, listening for offer requests...'
ClientReceivedMsg = f'Received offer from {local_ip},attempting to connect...'
server_disconnected_msg = f'Server disconnected, listening for offer requests...'
server_port = ""
events = []
data = ""

def main():
    global getch, server_port, local_ip, events, data
    events = []
    data = ""

    print(client_start_listening)
    while True:
        try:
            #START UDP CONNECTION AN WAITE FORE THE BRUDCUST MESSAGE FROM THE SERVER
            client_udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            client_udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            client_udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            client_udp_socket.bind(('', 13115))
            data, local_ip = client_udp_socket.recvfrom(bufferSize)
            server_port = struct.unpack('I b h', data)[2]
            local_ip=local_ip[0]

            if not (data[0:4] == bytes([0xba, 0xdc, 0xcd, 0xab])) or not data[4] == 0x02:
                print(Fore.GREEN+f'Incompatible magic cookie or msg type')
            else:
                print(Fore.RED+f'Received offer from {local_ip},attempting to connect...')
                try:
                    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_tcp_socket:
                        client_tcp_socket.connect((local_ip, server_port))
                        client_tcp_socket.sendall(TeamName)
                        data = client_tcp_socket.recv(bufferSize)
                        print(Fore.BLUE+data.decode())
                        events, _, _ = select([sys.stdin, client_tcp_socket], [], [], 10)
                        if not events:
                            pass
                        elif events[0] == sys.stdin:
                            getch = sys.stdin.readline()[0]
                            sys.stdin.flush()
                            tcflush(sys.stdin, TCIFLUSH)
                            print(Fore.BLUE+getch)
                            client_tcp_socket.sendall(getch.encode())

                        data = (client_tcp_socket.recv(bufferSize)).decode()
                        print(Fore.BLUE+data)
                        data = (client_tcp_socket.recv(bufferSize)).decode()
                        print(Fore.BLUE+data)

                finally:
                    client_tcp_socket.close()
                    time.sleep(5)

        except Exception as e:
            print (e)
        finally:
            client_udp_socket.close()

def get_ans_from_keybord():
    global getch
    getch = input()
    print("get: " + getch)

if __name__ == '__main__':
    main()


# 76 - 119
# -*- coding: utf-8 -*-
import scrapy
from tutorial.items import TutorialItem
from urllib import parse
from tutorial.requests import SeleniumRequest
from tutorial.Spider import SeleniumSpider
from tutorial.tools import waitForXpath
from bs4 import BeautifulSoup
import re

class InfoSpider(scrapy.Spider):
    name = 'info66'

    def start_requests(self):
        baseurl = 'http://www.81-china.com/collect/60/'
        start = 15
        end = 19
        for i in range(start, end):
            url = baseurl + str(i) + '.html'
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        if response.status == '404':
            return
        html = response.body.decode('utf-8')
        # print(html)
        soup = BeautifulSoup(html, 'html.parser')
        item = TutorialItem()
        item['midx'] = '66'
        baseurl = 'http://www.81-china.com'
        for i in response.xpath('/html/body/div/div[5]/div[3]/div[2]/ul/li'):
            item['name'] = i.xpath('div[2]/h3/a/text()').get()
            item['text'] = i.xpath('div[2]/p/text()').extract()[1].strip()
            s = str(soup.find_all('img')[0])
            item['pic'] = baseurl + i.xpath('div[1]/a/img/@src').get()
            print(item['name'])
            print(item['text'])
            print(item['pic'])
            yield item


import argparse
import numpy as np
import os
from pwtools.constants import fs, rcm_to_Hz
from pwtools.pydos import pdos
from ase.io.trajectory import Trajectory

from mlff.cAPI.process_argparse import StoreDictKeyPair

def analyse_md():
    # Create the parser
    parser = argparse.ArgumentParser(description='Run an MD with a NN.')

    parser.add_argument('--observable', type=str, required=True,
                        help='Observable to plot.')
    parser.add_argument("--kwargs", action=StoreDictKeyPair,
                        metavar="KEY1=VAL2,KEY2=VAL2,KEY3=VAL3,...",
                        default=None)

    args = parser.parse_args()
    # random seed
    obs = args.observable
    kwargs = args.kwargs

    if obs == "auto_correlation":
        calculate_auto_correlation(**kwargs)
    else:
        msg = f"Analyse function not implemented for {obs}."
        raise NotImplementedError(msg)

def calculate_auto_correlation(time_step):
    cwd = os.getcwd()
    tr = Trajectory(os.path.join(cwd, 'atom.traj'))

    # read velocities
    V = np.array([atoms.get_velocities() for atoms in tr])

    freq, dos = pdos(V, dt=time_step * fs, method='direct', npad=1)
    np.savez(os.path.join(cwd, 'auto_correlation.npz'), **{'freq': freq/rcm_to_Hz, 'dos': dos})

if __name__ == '__main__':
    analyse_md()


alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'l']

direction = input("type encode to encrypt, type decode to decrypt : ")

message = input("type your message : ").lower()

shift = int(input("type the sgift number : "))

def cipher(direct, text_amount, shift_number):

    cipher_code = ""
    if direct == "decode" :
            shift_number *= -1   #shift_number = shift_number *  2 x -1 = -2
    for letter in text_amount:
        postion = alphabets.index(letter) # h = 7 + -2
        new_position = postion + shift_number # -5
        cipher_code += alphabets[new_position] # 5
    print(f'the {direct}d is {cipher_code}')

cipher(direct=direction, text_amount=message ,shift_number=shift)


from django.conf import settings
from django.db import models
from django.template.loader import render_to_string
from datetime import datetime
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db.models import Sum
from config.models import Config
from mailer.tasks import send_mail
from utils.datetime import convert_to_local

class Transaction(models.Model):
    COIN_CHOICES = (
        (-1, "no_data"),
        (1, "CERO"),
        (2, "GREEN"),
        (3, "THB")
    )

    METHOD_CHOICES = (
        (-1, "waiting"),
        (1, "sent"),
        (2, "receive"),
        (3, "top_up"),
        (4, "activity"),
        (5, "withdraw"),
        (6, "swap")
    )

    STATUS_CHOICES = (
        (-5, "refund"),
        (-4, "waiting_for_refund"),
        (-3, "cancel"),
        (-2, "reject"),
        (-1, "pending"),
        (1, "waiting_for_payment"),
        (2, "success")
    )

    account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    desc = models.TextField(blank=True)
    transaction_hash = models.CharField(max_length=200, blank=True, null=True, default=None)
    source_key = models.CharField(max_length=200, blank=True, null=True, default=None)
    destination_key = models.CharField(max_length=200, blank=True, null=True, default=None)

    values = models.FloatField(default=0.0)
    thb_values = models.FloatField(default=0.0)
    paid_by = models.CharField(max_length=200, blank=True, null=True, default=None)

    coin = models.IntegerField(choices=COIN_CHOICES, db_index=True, default=-1)
    method = models.IntegerField(choices=METHOD_CHOICES, db_index=True, default=-1)
    status = models.IntegerField(choices=STATUS_CHOICES, db_index=True, default=-1)
    rate_per_usdt = models.FloatField(db_index=True, default=0.00)

    datetime_start = models.DateTimeField(null=True, blank=True)
    datetime_end = models.DateTimeField(null=True, blank=True)

    datetime_create = models.DateTimeField(auto_now_add=True, db_index=True)
    datetime_update = models.DateTimeField(auto_now=True)

    datetime_cancel = models.DateTimeField(null=True, blank=True)
    datetime_complete = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-datetime_create']

    def __str__(self):
        return str(self.id)

    @property
    def is_reject(self):
        from django.utils import timezone
        if self.status == -2:
            return True
        elif self.datetime_end is not None:
            return timezone.now() > self.datetime_end
        else:
            return False

    @property
    def datetime_create_str(self):
        datetime_create = convert_to_local(self.datetime_create)
        return datetime_create.strftime("%c") if datetime_create else '-'

    @property
    def day_left(self):
        from django.utils import timezone

        if self.datetime_start is None:
            return -1  # TODO : Limit system
        elif self.datetime_end is None:
            return -1
        else:
            return (self.datetime_end - timezone.now()).days + 1

    @property
    def is_active(self):
        return self.status == 0

    @property
    def status_label(self):
        return self.get_status_display().replace("_", " ").title()

    @staticmethod
    def pull(id):
        transaction = Transaction.objects.get(id=id)
        return transaction if transaction else None

    @staticmethod
    def send_topup_noti(transaction_id, topup_status):
        prefix = Config.pull_value('mailer-subject-prefix')
        header_image = Config.pull_value('mailer-header-image')
        icon_image = Config.pull_value('mailer-icon-image')

        transaction = Transaction.objects.filter(id=transaction_id).first()
        if not transaction:
            return None

        email = transaction.account.email

        if topup_status == -2: # Reject
            subject = '%s - Your top-up has rejected' % prefix
            body = render_to_string(
                'mailer/transaction/TopupReject.html',
                {
                    'header_image': settings.CO2_API_URL + header_image,
                    'mail_icon': settings.CO2_API_URL + icon_image,
                    'thb_amount': transaction.thb_values
                }
            )
            send_mail(email, subject, body, 1)

        elif topup_status == -1: # waiting for approve
            subject = '%s - Payment verification is in process' % prefix
            body = render_to_string(
                'mailer/transaction/PaymentInProcess.html',
                {
                    'header_image': settings.CO2_API_URL + header_image,
                    'mail_icon': settings.CO2_API_URL + icon_image,
                }
            )
            send_mail(email, subject, body, 1)
        elif topup_status == 2: # Approve
            subject = '%s - Your top-up has approved' % prefix
            coin_dict = dict(Transaction.COIN_CHOICES)
            body = render_to_string(
                'mailer/transaction/TopupSuccess.html',
                {
                    'header_image': settings.CO2_API_URL + header_image,
                    'mail_icon': settings.CO2_API_URL + icon_image,
                    'thb_amount': transaction.thb_values,
                    'coin_amount': transaction.values,
                    'coin_name': coin_dict[int(transaction.coin)] if transaction and transaction.coin else '-'
                }
            )
            send_mail(email, subject, body, 1)

    def set_cancel(self):
        self.datetime_end = datetime.now()
        self.datetime_cancel = datetime.now()
        self.status = -3
        self.save(update_fields=['datetime_end', 'status', 'datetime_cancel', 'datetime_update'])

@receiver(post_save, sender=Transaction)
def update_carbon_saving(sender, instance, created, **kwargs):
    from activity.models import CarbonActivity
    from account.models import Account
    if instance and instance.method == 4 and instance.status == 2:
        carbon = CarbonActivity.objects.filter(
            transaction__method=4,
            transaction__status=2,
            transaction__account_id=instance.account_id
        ).aggregate(
            total_carbon_saving=Sum('carbon_saving')
        )
        account = Account.objects.filter(id=instance.account_id).first()
        account.carbon_saving = carbon['total_carbon_saving']
        account.save()

class Payment(models.Model):
    transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
    code = models.CharField(max_length=200, blank=True, null=True, default=None)
    qrcode = models.ImageField(upload_to='transaction/qrcode/%Y/%m/', null=True, blank=True)
    payment_slip = models.ImageField(upload_to='account/payment_slip/%Y/%m/', null=True, blank=True)

    ref_code_1 = models.CharField(max_length=200, blank=True, null=True, default=None)
    ref_code_2 = models.CharField(max_length=200, blank=True, null=True, default=None)

    datetime_create = models.DateTimeField(auto_now_add=True, db_index=True)
    datetime_update = models.DateTimeField(auto_now=True)

    datetime_stamp = models.DateTimeField(auto_now_add=True, db_index=True, null=True, blank=True)

    class Meta:
        ordering = ['-datetime_create']

    def __str__(self):
        return str(self.id)

    @property
    def datetime_stamp_str(self):
        datetime_stamp = convert_to_local(self.datetime_stamp)
        return datetime_stamp.strftime("%c") if datetime_stamp else '-'


#Golden Ratio
import numpy as np
import matplotlib.pyplot as plt

#Import the function
import sys
sys.path.insert(0,'/home/aman/assignment1/question5')
import fibo as fb

#The ratio of two consecutive Fibonacci Numbers
n=int(input("Enter the Number:",))
def ratio(n):
    return(fb.fibo(n+1)/fb.fibo(n))
print("Ratio of",n+1,"th and",n,"th fibonacci number is:",ratio(n))

#Plot of Golden Ratio
L=[]
m=np.linspace(1,100,100)
for i in range(1,101):
    L.append(fb.fibo(i+1)/fb.fibo(i))
plt.plot(m,L,'-o')
plt.xlabel("Natural Numbers")
plt.ylabel("The Ratio of two consecutive fibonacci numbers")
plt.title("Golden Ratio")
plt.grid()
plt.show()


import datetime
from typing import List

from fastapi import Depends, APIRouter

from sqlalchemy.ext.asyncio import AsyncSession

from src.database import get_async_session

from src.auth.depends import get_current_user

from src.folder.depends import get_my_folder
from src.folder.models import Folder

from src.abstract.schemas import AbstractCreate, AbstractRead, AbstractUpdate

from src.abstract.services.db import abstract_database_manager

router = APIRouter(prefix='/folder/{folder_id}/abstract', tags=['Abstract'])

@router.post('/')
async def create_abstract(
        abstract: AbstractCreate,
        folder: Folder = Depends(get_my_folder),
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    data: dict = abstract.dict()
    data.update({'folder_id': folder.id})
    data.update({'user_id': user.id})
    return

    return await abstract_database_manager.add_entity(
        abstract, folder, datetime.datetime.now(), user=user, session=session
    )

@router.get('/', response_model=List[AbstractRead])
async def get_abstracts(
        folder: Folder = Depends(get_my_folder),
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    return await abstract_database_manager.get_entities(filter_value=folder.id, user=user, session=session)

router_without_folder_id = APIRouter(prefix='/folder/abstract', tags=['Abstract'])

@router_without_folder_id.get('/{abstract_id}', response_model=AbstractRead)
async def get_abstract(
        abstract_id: int,
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    return await abstract_database_manager.get_entity_by_id(abstract_id, user, session)

@router_without_folder_id.patch('/{abstract_id}')
async def update_abstract(
        abstract_id: int,
        abstract: AbstractUpdate,
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    return await abstract_database_manager.update_entity_by_id(
        abstract, entity_id=abstract_id, user=user, session=session
    )

@router_without_folder_id.delete('/{abstract_id}')
async def delete_abstract(
        abstract_id: int,
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    return await abstract_database_manager.delete_entity_by_id(abstract_id, user, session)

@router_without_folder_id.post('/opening/{abstract_id}')
async def open_or_close_public_abstract(
        abstract_id: int,
        is_open: bool,
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    return await abstract_database_manager.open_or_close_entity_by_id(abstract_id, user, session, is_open)

@router_without_folder_id.get('/opening/{abstract_url_open}')
async def get_public_abstract(
        abstract_url_open: str,
        user=Depends(get_current_user),
        session: AsyncSession = Depends(get_async_session)
):
    return await abstract_database_manager.get_public_entity_by_id(abstract_url_open, user, session)


import os
import re
import sys
from collections import defaultdict

data_path = os.path.join("data", os.path.splitext(os.path.basename(sys.argv[0]))[0])

tc_filename = "submitInput"
tc_path = os.path.join(data_path, tc_filename)
tc_out_path = os.path.join(data_path, os.path.splitext(tc_filename)[0] + "_out")

book_path = os.path.join(data_path, "book.txt")
words = defaultdict(int)
#valid_chars = "abcdefghijklmnñopqrstuvwxyzáéíóúü"
invalid_chars_rgx = "[^abcdefghijklmnñopqrstuvwxyzáéíóúü]"

def get_valid_words(line):
    words = []
    line_valid = re.sub(invalid_chars_rgx, " ", line.lower())
    for word in line_valid.split():
        if word != "" and len(word) >= 3:
            words.append(word)
    #print(line, words)
    return words

def sort_word_slice(word_list, start_idx, end_idx):
    words_slice = word_list[start_idx:end_idx]
    word_list[start_idx:end_idx] = sorted(words_slice)

with open(book_path, "r") as book_file:
    for line in book_file.readlines():
        if line == "":
            continue

        line_words = get_valid_words(line)
        for lw in line_words:
            words[lw] += 1

words_decreasing_order = sorted(words, key=words.get, reverse=True)
#print(words_decreasing_order)
start_idx = None
last_count = None

for idx, word in enumerate(words_decreasing_order):
    word_count = words[word]

    if word_count == last_count:
        if start_idx is None:
            start_idx = idx-1
    elif start_idx is not None:
        #print([(w, words[w]) for w in words_decreasing_order[start_idx-1:idx+1]])
        sort_word_slice(words_decreasing_order, start_idx, idx)
        #print([(w, words[w]) for w in words_decreasing_order[start_idx - 1:idx + 1]])
        start_idx = None

    last_count = word_count

if start_idx is not None:
    sort_word_slice(words_decreasing_order, start_idx, len(words_decreasing_order))

with open(tc_path, "r") as in_file:
    with open(tc_out_path, "w") as out_file:
        num_tc = int(in_file.readline().strip())

        for cidx in range(1, num_tc + 1):
            in_data = in_file.readline().strip()

            if in_data.isnumeric():
                ranked_word = words_decreasing_order[int(in_data) - 1]
                word_count = words[ranked_word]
                resp = "%s %d" % (ranked_word, word_count)
            else:
                idx = words_decreasing_order.index(in_data)
                word_count = words[in_data]
                resp = "%d #%d" % (word_count, idx + 1)

            out_file.write("Case #%d: %s\n" % (cidx, resp))


#!/usr/bin/python
# coding: utf-8 -*-

# (c) 2021, Sean Sullivan
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function

__metaclass__ = type

ANSIBLE_METADATA = {
    "metadata_version": "1.1",
    "status": ["preview"],
    "supported_by": "community",
}

DOCUMENTATION = """
---
module: workflow_node_wait
author: "Sean Sullivan (@sean-m-sullivan)"
short_description: Wait for a workflow node to finish.
description:
    - Approve an approval node in a workflow job. See
      U(https://www.ansible.com/tower) for an overview.
options:
    workflow_job_id:
      description:
        - ID of the workflow job to monitor for node.
      required: True
      type: int
    name:
      description:
        - Name of the workflow node to wait on.
      required: True
      type: str
    interval:
      description:
        - The interval in sections, to request an update from the controller.
      required: False
      default: 1
      type: float
    timeout:
      description:
        - Maximum time in seconds to wait for a workflow job to reach approval node.
      default: 10
      type: int
extends_documentation_fragment: awx.awx.auth
"""

EXAMPLES = """
- name: Launch a workflow with a timeout of 10 seconds
  workflow_launch:
    workflow_template: "Test Workflow"
    wait: False
  register: workflow

- name: Wait for a workflow node to finish
  workflow_node_wait:
    workflow_job_id: "{{ workflow.id }}"
    name: Approval Data Step
    timeout: 120
"""

RETURN = """

"""

from ..module_utils.controller_api import ControllerAPIModule

def main():
    # Any additional arguments that are not fields of the item can be added here
    argument_spec = dict(
        workflow_job_id=dict(type="int", required=True),
        name=dict(required=True),
        timeout=dict(type="int", default=10),
        interval=dict(type="float", default=1),
    )

    # Create a module for ourselves
    module = ControllerAPIModule(argument_spec=argument_spec)

    # Extract our parameters
    workflow_job_id = module.params.get("workflow_job_id")
    name = module.params.get("name")
    timeout = module.params.get("timeout")
    interval = module.params.get("interval")

    module.wait_on_workflow_node_url(
        url="workflow_jobs/{0}/workflow_nodes/".format(workflow_job_id),
        object_name=name,
        object_type="Workflow Node",
        timeout=timeout,
        interval=interval,
        **{
            "data": {
                "job__name": name,
            }
        }
    )

    # Attempt to look up jobs based on the status
    module.exit_json(**module.json_output)

if __name__ == "__main__":
    main()


__author__ = 'Akshat Raj Vansh'
__version__ = '0.1.0'
__license__ = 'MIT'

def writeToFile(filename, data):
    print('Writes the output to the file')
    file = open(filename, 'w+')
    for x in data:
        file.write(x)
        file.write('\n')
    print(data)
    file.close()

def main():
    L={"One","Two","Three","Four","Five"}
    writeToFile('question8.txt', [(', '.join([x, str(len(x))])) for x in L])

if __name__ == '__main__':
    main()


from scipy import stats
import pandas as pd
import os

def test_model(config, model, DataHandler, verbose=1):
    spearman_result = {}

    if verbose > 0:
        print('Testing model')

    test_input = [DataHandler['X_test'], DataHandler['dg_test']]

    test_true_label = DataHandler['y_test']
    test_prediction = model.predict(test_input)
    spearman = stats.spearmanr(test_true_label, test_prediction)
    spearman_result = spearman[0]
    if verbose > 0:
        print(f'Spearman: {spearman}')

    return spearman_result

def save_results(config, set, train_type, mean, spearmanr):
    results_path = f'results/transfer_learning/{config.tl_data}/results.csv'
    if os.path.exists(results_path):
        results_df = pd.read_csv(results_path, index_col=0)
    else:
        columns = ['full_tl', 'full_tl_ensemble', 'LL_tl', 'LL_tl_ensemble', 'gl_tl', 'gl_tl_ensemble', 'no_tl', 'no_tl_ensemble', 'no_pre_train', 'no_pre_train_ensemble']
        rows = []
        for i in range(5):
            rows.append(f'set{i}')
        results_df = pd.DataFrame(index=rows, columns=columns)

    results_df[train_type][f'set{set}'] = '%.4f' % mean
    p_val = "{:e}".format(spearmanr[1])
    p_val = p_val[:5] + p_val[p_val.find('e'):]
    results_df[train_type + '_ensemble'][f'set{set}'] = '%.4f ' % spearmanr[0] +  f' ({p_val})'

    results_df.to_csv(results_path, index=True)


#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
import sys

import numpy as np
import matplotlib as mpl
mpl.use('Agg') #silent mode
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker

if __name__ == '__main__':
    # read k-point labels
    group_labels, x = [], []

    with open("KLABELS", 'r') as reader:
        lines = reader.readlines()[1:]

    for i in lines:
        s = i.encode('utf-8')#.decode('latin-1')
        if len(s.split()) == 2 and not s.decode('utf-8','ignore').startswith("*"):
            group_labels.append(s.decode('utf-8','ignore').split()[0])
            x.append(float(s.split()[1]))

    # read band gap
    with open("BAND_GAP", 'r') as reader:
        lines = reader.readlines()
    lines = [line.strip('\n').split() for line in lines]
    band_gap = float(lines[2][-1])

    #hsp=np.loadtxt(open("KLABELS", encoding='utf8'), dtype=np.string_,skiprows=1,usecols = (0,1))
    for index in range(len(group_labels)):
        if group_labels[index] == "GAMMA":
            group_labels[index] = u"Γ"

    # read INCAR SYSTEM
    with open('INCAR', 'r') as reader:
        lines = reader.readlines()
    lines = [line.strip().split('=') for line in lines]
    system_name = [line[1].split('#')[0] for line in lines if line[0].strip(' ') == 'SYSTEM'][0]

    # plot bands
    fig, axe = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
    axe.set_title('Band Structure of %s \nBand Gap is %.3f eV' \
            %(system_name, band_gap), fontsize=20, fontweight='bold')

    '''
    df_up = np.loadtxt("REFORMATTED_BAND_UP.dat", dtype=np.float64)
    df_dw = np.loadtxt("REFORMATTED_BAND_DW.dat", dtype=np.float64)

    df = df_up
    axe.plot(df[:,0], df[:,1:], linewidth=1.0, color='red')

    df = df_dw
    axe.plot(df[:,0], df[:,1:], linewidth=1.0, color='blue')
    '''
    if os.path.exists('REFORMATTED_BAND_UP.dat') and \
            os.path.exists('REFORMATTED_BAND_DW.dat'):
        datfiles = ['REFORMATTED_BAND_UP.dat', 'REFORMATTED_BAND_DW.dat']
        colors = ['red', 'blue']
    elif os.path.exists('REFORMATTED_BAND.dat'):
        datfiles = ['REFORMATTED_BAND.dat']
        colors = ['blue']
    else:
        raise ValueError('No such data files.')

    for dat, color in zip(datfiles, colors):
        df = np.loadtxt(dat, dtype=np.float64)
        axe.plot(df[:,0], df[:,1:], linewidth=2.0, color=color)

    # plot labels and
    font = {'color'  : 'black',
            'weight' : 'bold',
            'size'   : 14,
            }

    axe.set_xlabel(r'$\it{\bf{\mathbf{k}-points}}$', fontdict=font)
    axe.set_ylabel(r'$\it{\bf{{E}-E_{f}\ (eV)}}$', fontdict=font)

    axe.set_xticks(x)

    axe.set_xticklabels(group_labels, rotation=0, fontdict=font)

    # plot high symmetry k-point
    axe.axhline(y=0, xmin=0, xmax=1,linestyle= '--',linewidth=1.5,color='0.5')
    for i in x[1:-1]:
    	axe.axvline(x=i, ymin=0, ymax=1,linestyle= '--',linewidth=1.5,color='0.5')
    axe.set_xlim((x[0], x[-1]))

    #plt.show()
    plt.savefig('band.png')