<jupyter_start><jupyter_text>Brainery Byte Building an Interactive User Interface in Jupyter Notebook     >> Building A Shopping List <<     R211014  <NAME>, 2021       <EMAIL> The objective of this workbook is to help you assemble the building blocks of an interactive user interface.            Widgets:    Widgets are what makes Jupyter Notebooks so awesome! Here is where I get my info on building  WIDGETS       Text Entry  Pull-Down Menus  Radio Buttons  Checkboxes  Action Buttons  Accordion boxes  Embedded Videos    Sliders            NOTES:             This is where you put notes.                      Here is a Hypterlink to my web site with additional text              Here is a hyperlink to a video                 Here is another line in the outline             When you are done, you can write simple textBecause we are working in Binder, and Binder sessions are meant to be ephemeral, it is not possible for you to save any changes you make to your Jupyter Notebook. If you do make changes or notes, you will need to download the notebook to your own computer by clicking File > Download as > Notebook (.ipynb). The only way you will be able to run these is if you have the appropriate software to run Jupyter Notebooks in Python and pip install OpenSeesPy and eSEESminiPy in your Python configuration. You may view my videos on how to install Anaconda, Jupyter Notebooks and OpenSeesPy (https://www.youtube.com/c/silviasbrainery).    This Code has been developed by <NAME>. Please acknowledge this in your scripts, when applicable<jupyter_code>#Here is an example of embedding a video into your Notebook
from IPython.lib.display import YouTubeVideo
YouTubeVideo('8AFhbeVl3qY')<jupyter_output><empty_output><jupyter_text>Initialize Python:<jupyter_code># pip install these packages if you are running this locally
from ipywidgets import widgets, Output
from ipywidgets import interact, interactive, fixed, interact_manual, Layout
from IPython.display import display
from IPython.display import clear_output
from IPython.display import HTML
from IPython.display import Image
from IPython.display import Javascript
%%javascript
IPython.OutputArea.auto_scroll_threshold = 100000;<jupyter_output><empty_output><jupyter_text>Initalize Widget Data<jupyter_code>AllWidgetData = {}
outBucketData = {}<jupyter_output><empty_output><jupyter_text>Create a header for your UI. put this into a widget so you can display it anywhere<jupyter_code>outBucketData['Header'] = Output()
def createHeader():
    label_TopHeader = widgets.HTML(value = """<font color="#D94496"><h1>My Interactive Shopping List</h1></font>
    <p>
    Developed by <NAME><br>
    Let's do some shopping. """)
    thisContainer = widgets.VBox(display='wrap',flex_wrap='wrap',children=[label_TopHeader],border='1px solid blue')
    return thisContainer
    
def displayHeader(thisOut):
    thisContainer = createHeader()
    thisOut.clear_output()
    with thisOut:
        display(thisContainer)
    display(thisOut)
    

displayHeader(outBucketData['Header'])<jupyter_output><empty_output><jupyter_text>Create nice formatted header, user-input<jupyter_code>def makeSectionHeaderWidget(text):
    thisWidget = widgets.HTML(value = """<font color="#D47088"><h3>""" + text + """</h3></font>""")
    return thisWidget<jupyter_output><empty_output><jupyter_text>Create Pull-Down Menu Widget<jupyter_code>def makeDropdownMenu(defValue,MenuArray,descrip):
    thisWidget = widgets.Dropdown(
        options=MenuArray,
        value=defValue,
        description=descrip,
        continuous_update=True,
        disabled=False,
    )
    return thisWidget<jupyter_output><empty_output><jupyter_text>Store Data<jupyter_code>StoreData = {}
StoreData['Costco'] = {'Address': 'here','Travel Time':10}
StoreData['TraderJoes'] = {'Address': 'there','Travel Time':22}
StoreData['Ralphs'] = {'Address': 'somewhere','Travel Time':5}<jupyter_output><empty_output><jupyter_text>Create Pull-Down Menu for Store<jupyter_code>SelectStore_Default = 'Costco'
outBucketData['StoreSelector'] = Output()

def updateStoreData(thisStore):
    AllWidgetData['MyStore'].value='My Store: ' + thisStore
    AllWidgetData['Address'].value='Address: ' + str(StoreData[thisStore]['Address'])
    AllWidgetData['MyStoreTravelTime'].value='Travel Time: ' + str(StoreData[thisStore]['Travel Time'])

    
def SelectStore_eventhandler(change):
    thisStore = change.new
    updateStoreData(thisStore)
    
    
def makeStoreSelector():
    thisSectionHeader = makeSectionHeaderWidget('Store')
    SelectStore_Options = StoreData.keys()
    SelectStore_Descript = 'Select Store'
    AllWidgetData['SelectStore'] = makeDropdownMenu(SelectStore_Default,SelectStore_Options,SelectStore_Descript)
    thisContainer = widgets.VBox(children=[thisSectionHeader,AllWidgetData['SelectStore']])
    AllWidgetData['SelectStore'].observe(SelectStore_eventhandler, names='value')
    
    return thisContainer
  
def displayStoreSelector(thisOut):
    thisContainer = makeStoreSelector()
    thisOut.clear_output()
    with thisOut:
        display(thisContainer)
    display(thisOut)
    
displayStoreSelector(outBucketData['StoreSelector'])<jupyter_output><empty_output><jupyter_text>Display Store Data<jupyter_code>outBucketData['StoreData'] = Output()

def makeStoreData(thisStore):
    thisSectionHeader = makeSectionHeaderWidget('Store Info')
    AllWidgetData['MyStore'] = widgets.Label(value='My Store: ' + thisStore)
    AllWidgetData['Address'] = widgets.Label(value='Address: ' + str(StoreData[thisStore]['Address']))
    AllWidgetData['MyStoreTravelTime'] = widgets.Label(value='Travel Time: ' + str(StoreData[thisStore]['Travel Time']))
    thisContainer = widgets.VBox(children=[thisSectionHeader,AllWidgetData['MyStore'],AllWidgetData['Address'],AllWidgetData['MyStoreTravelTime']])
    return thisContainer

def DisplayStoreData(thisStore,thisOut):
    thisContainer = makeStoreData(thisStore)
    thisOut.clear_output()
    with thisOut:
        display(thisContainer)
    display(thisOut)
    
DisplayStoreData(SelectStore_Default,outBucketData['StoreData'])<jupyter_output><empty_output><jupyter_text>Shopping Items<jupyter_code>ShoppingItems = {'FRUITS':{'Bananas':{'price':10,'default':0},
                           'Apples':{'price':25,'default':1},
                           'Oranges':{'price':33,'default':6}},
                 'CARBS':{'Rice':{'price':37,'default':3},
                          'Pasta':{'price':27,'default':2},
                          'Bread':{'price':15,'default':1}}}<jupyter_output><empty_output><jupyter_text>Create Checkbox<jupyter_code>def makeCheckbox(defValue,descrip):
    thisWidget = widgets.Checkbox(
        value=defValue,
        description=descrip,
        disabled=False,
        indent=False
    )
    return thisWidget<jupyter_output><empty_output><jupyter_text>Create Slider for quantity<jupyter_code>def makeFloatSlider(defValue,RangeArray,descrip):
    thisSlider = widgets.FloatSlider(
        value=defValue,
        min=RangeArray[0],
        max=RangeArray[2],
        step=RangeArray[1],
        description= descrip,
        disabled=False,
        continuous_update=True,
        orientation='horizontal',
        readout=True
    )
    return thisSlider<jupyter_output><empty_output><jupyter_text>Select Items and Amount:<jupyter_code>outBucketData['ShoppingItems'] = Output()
defValue = False

def makeShoppingItemsDisplay():
    thisSectionHeader = makeSectionHeaderWidget('Shopping Items')
    thisWidgetList_H = []
    for ItemType,ItemData in ShoppingItems.items():
        typeLabelWidget = widgets.Label(value=ItemType)
        thisWidgetList_here = []
        for thisItem,thisItemData in ItemData.items():
            thisPrice = ShoppingItems[ItemType][thisItem]['price']
            thisWidget=makeCheckbox(defValue,thisItem + ' (' + str(thisPrice) + '/unit)')
            thisDefaultAmt = ShoppingItems[ItemType][thisItem]['default']
            thisLabel = '(def=' + str(thisDefaultAmt)+')'
            AmountRange = [0,1,20]
            thisSliderWidget = makeFloatSlider(thisDefaultAmt,AmountRange,thisLabel)
            thisContainer = widgets.HBox(display='wrap',flex_wrap='wrap',children=[thisSliderWidget,thisWidget])
            thisWidgetList_here.append(thisContainer)
            AllWidgetData[thisItem+'CheckBox'] = thisWidget
            AllWidgetData[thisItem+'Amount'] = thisSliderWidget
        thisContainer = widgets.VBox(display='wrap',flex_wrap='wrap',children=[typeLabelWidget,*thisWidgetList_here])
        thisWidgetList_H.append(thisContainer)
    thisHBox = widgets.VBox(display='wrap',flex_wrap='wrap',children=thisWidgetList_H)
    thisContainer=widgets.VBox(display='wrap',flex_wrap='wrap',children=[thisSectionHeader,thisHBox])
    return thisContainer
  

def displayShoppingItemsDisplay(thisOut):
    thisContainer = makeShoppingItemsDisplay()
    thisOut.clear_output()
    with thisOut:
        display(thisContainer)
    display(thisOut)   
    
    
displayShoppingItemsDisplay(outBucketData['ShoppingItems'])<jupyter_output><empty_output><jupyter_text>Create Radio Buttons for Hot Items<jupyter_code>HotItems = {'Chicken':{'Whole':10,'Half':7,'None':0},'Ribs':{'FullRack':12,'HalfRack':8,'None':0}}
display(HotItems)

def makeRadioButtons(defValue,MenuArray,descrip):
    thisWidget = widgets.RadioButtons(
        options=MenuArray,
        value=defValue,
    #    layout={'width': 'max-content'}, # If the items' names are long
        description=descrip,
        disabled=False
    )
    return thisWidget

outBucketData['HotItems'] = Output()
PriceWidget = {}

def HotItems_eventhandler(change):
    updateHotItemsDisplay()
    
def updateHotItemsDisplay():
    TotalHotPrice = 0
    for ItemType,ItemData in HotItems.items():
        thisItemValue = AllWidgetData[ItemType].value
        thisItemPrice = HotItems[ItemType][thisItemValue]
        PriceWidget[ItemType].value = ItemType + ' Price: ' + str(thisItemPrice)
        TotalHotPrice = TotalHotPrice + float(thisItemPrice)
    PriceWidget['TotalHotPrice'].value = 'Total HotItems Price: ' + str(TotalHotPrice)
    
def makeHotItemsDisplay():
    thisSectionHeader = makeSectionHeaderWidget('Hot Items')
    thisWidgetList_V = []
    TotalHotPrice = 0
    for ItemType,ItemData in HotItems.items():
        theseOptions = ItemData.keys()
        thisDef = 'None'
        AllWidgetData[ItemType] =makeRadioButtons(thisDef,theseOptions,ItemType)
        PriceWidget[ItemType] = widgets.Label(value=ItemType + ' Price: ' + str(HotItems[ItemType][thisDef]) ,  fontsize=20, color = '#ff0000',border='3 px solid red')
        thisContainer=widgets.HBox(children=[AllWidgetData[ItemType],PriceWidget[ItemType]])
        thisWidgetList_V.append(thisContainer)
        TotalHotPrice = TotalHotPrice + HotItems[ItemType][thisDef]
        AllWidgetData[ItemType].observe(HotItems_eventhandler, names='value')
    PriceWidget['TotalHotPrice'] = widgets.Label(value='Total HotItems Price: ' + str(TotalHotPrice) ,  fontsize=20, color = '#ff0000',border='3 px solid red')
    thisContainer = widgets.VBox(children=[thisSectionHeader,*thisWidgetList_V,PriceWidget['TotalHotPrice']])
    return thisContainer
    
def displayHotItemsDisplay(thisOut):
    thisContainer = makeHotItemsDisplay()
    thisOut.clear_output()
    with thisOut:
        display(thisContainer)
    display(thisOut)
    
displayHotItemsDisplay(outBucketData['HotItems'])<jupyter_output><empty_output><jupyter_text>Entry Widget for Extras<jupyter_code>def makeTextEntryWidget(defValue,descrip,placeholder = ''):
    thisWidget = widgets.Text(
        value=defValue,
        placeholder=placeholder,
        description=descrip,
        #layout=widgets.Layout(width='75%', height='40px'),
        continuous_update=True,
        disabled=False
    )
    return thisWidget

def makeFloatEntryWidget(defValue,descrip,placeholder = ''):
    thisWidget = makeTextEntryWidget(str(defValue),descrip,placeholder)
    return thisWidget

outBucketData['Extras'] = Output()
ExtrasLabelWidget = {}
ExtrasPriceWidget = {}

def makeExtrasDisplay():
    thisSectionHeader = makeSectionHeaderWidget('Extras')
    thisExtraWidgetList = [thisSectionHeader]
    for i in range(5):
        ExtrasLabelWidget[str(i)] = makeTextEntryWidget('','','Enter Item Description')
        ExtrasPriceWidget[str(i)] = makeTextEntryWidget('','','Enter Item Price')
        thisContainer = widgets.HBox(children=[ExtrasLabelWidget[str(i)],ExtrasPriceWidget[str(i)]])
        thisExtraWidgetList.append(thisContainer)
    thisContainer = widgets.VBox(children=thisExtraWidgetList)
    return thisContainer

def dispalyExtrasDisplay(thisOut):
    thisContainer = makeExtrasDisplay()
    thisOut.clear_output()
    with thisOut:
        display(thisContainer)
    display(thisOut)

dispalyExtrasDisplay(outBucketData['Extras'])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1082758085782983, 'fraction_numerical': 0.007135655006592725, 'mean_word_length': 4.748551047703968, 'pattern_counts': {'":': 0, '<': 77, '<?xml version=': 0, '>': 79, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '38191', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3823, 'n_tokens_neox': 3736, 'n_words': 738, 'path': 'BraineryByte_Building_an_Interactive_UI_part2.ipynb', 'repo_name': 'silviamazzoni/BraineryBytes', 'size': '12933'}