'''
Created on Aug 21, 2016
@author: Burkhard
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import Menu
from tkinter import ttk

#======================
# functions
#======================
# Exit GUI cleanly
def _quit():
    win.quit()
    win.destroy()
    exit()

#======================
# procedural code
#======================
# Create instance
win = tk.Tk()

# Add a title
win.title("Python Projects")
# ---------------------------------------------------------------
# Creating a Menu Bar
menuBar = Menu()
win.config(menu=menuBar)

# Add menu items
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label="New")
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=_quit)
menuBar.add_cascade(label="File", menu=fileMenu)

# Add another Menu to the Menu Bar and an item
helpMenu = Menu(menuBar, tearoff=0)
helpMenu.add_command(label="About")
menuBar.add_cascade(label="Help", menu=helpMenu)
# ---------------------------------------------------------------

# Tab Control / Notebook
tabControl = ttk.Notebook(win)          # Create Tab Control

tab1 = ttk.Frame(tabControl)            # Create a tab
tabControl.add(tab1, text='NOAA')       # Add the tab

tab2 = ttk.Frame(tabControl)                # Add a second tab
tabControl.add(tab2, text='Station IDs')    # Make second tab visible

tab3 = ttk.Frame(tabControl)            # Add a second tab
tabControl.add(tab3, text='Images')     # Make second tab visible

tab4 = ttk.Frame(tabControl)            # Add a second tab
tabControl.add(tab4, text='OpenWeatherMap')      # Make second tab visible

tabControl.pack(expand=1, fill="both")  # Pack to make visible
# ---------------------------------------------------------------

# We are creating a container frame to hold all other widgets
weather_conditions_frame = ttk.LabelFrame(tab1, text=' Current Weather Conditions ')
weather_conditions_frame.grid(column=0, row=1, padx=8, pady=4)

#================
ENTRY_WIDTH = 25
#================

# Adding Label & Textbox Entry widgets
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Last Updated:").grid(column=0, row=1, sticky='E')         # <== right-align
updated = tk.StringVar()
updatedEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=updated, state='readonly')
updatedEntry.grid(column=1, row=1, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Weather:").grid(column=0, row=2, sticky='E')               # <== increment row for each
weather = tk.StringVar()
weatherEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=weather, state='readonly')
weatherEntry.grid(column=1, row=2, sticky='W')                                  # <== increment row for each
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Temperature:").grid(column=0, row=3, sticky='E')
temp = tk.StringVar()
tempEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=temp, state='readonly')
tempEntry.grid(column=1, row=3, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Dewpoint:").grid(column=0, row=4, sticky='E')
dew = tk.StringVar()
dewEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=dew, state='readonly')
dewEntry.grid(column=1, row=4, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Relative Humidity:").grid(column=0, row=5, sticky='E')
rel_humi = tk.StringVar()
rel_humiEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=rel_humi, state='readonly')
rel_humiEntry.grid(column=1, row=5, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Wind:").grid(column=0, row=6, sticky='E')
wind = tk.StringVar()
windEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=wind, state='readonly')
windEntry.grid(column=1, row=6, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Visibility:").grid(column=0, row=7, sticky='E')
visi = tk.StringVar()
visiEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=visi, state='readonly')
visiEntry.grid(column=1, row=7, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="MSL Pressure:").grid(column=0, row=8, sticky='E')
msl = tk.StringVar()
mslEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=msl, state='readonly')
mslEntry.grid(column=1, row=8, sticky='W')
#---------------------------------------------
ttk.Label(weather_conditions_frame, text="Altimeter:").grid(column=0, row=9, sticky='E')
alti = tk.StringVar()
altiEntry = ttk.Entry(weather_conditions_frame, width=ENTRY_WIDTH, textvariable=alti, state='readonly')
altiEntry.grid(column=1, row=9, sticky='E')
#---------------------------------------------

# Add some space around each widget
for child in weather_conditions_frame.winfo_children():
        child.grid_configure(padx=4, pady=2)

#########################################################################################
# NOAA (National Oceanic and Atmospheric Administration) section starts here

# We are creating a container frame to hold other widgets
weather_cities_frame = ttk.LabelFrame(tab1, text=' Latest Observation for ')
weather_cities_frame.grid(column=0, row=0, padx=8, pady=4)

# ---------------------------------------------------------------
# Adding a Label
ttk.Label(weather_cities_frame, text="Weather Station ID: ").grid(column=0, row=0) # empty space for alignment

# ---------------------------------------------------------------
station_id = tk.StringVar()
station_id_combo = ttk.Combobox(weather_cities_frame, width=6, textvariable=station_id)
                        # Los Angeles, Denver, New York City
station_id_combo['values'] = ('KLAX', 'KDEN', 'KNYC')
station_id_combo.grid(column=1, row=0)
station_id_combo.current(0)                 # highlight first city station id

# ---------------------------------------------------------------
# callback function
def _get_station():
    station = station_id_combo.get()
    get_weather_data(station)
    populate_gui_from_dict()

get_weather_btn = ttk.Button(weather_cities_frame,text='Get Weather', command=_get_station).grid(column=2, row=0)

# Station City label
location = tk.StringVar()
ttk.Label(weather_cities_frame, textvariable=location).grid(column=0, row=1, columnspan=3)
# ---------------------------------------------------------------

for child in weather_cities_frame.winfo_children():
        child.grid_configure(padx=5, pady=4)

#########################################################################################
# NOAA DATA directly from live web search

#Retrieve the tags we are interested in
weather_data_tags_dict = {
    'observation_time': '',
    'weather': '',
    'temp_f':  '',
    'temp_c':  '',
    'dewpoint_f': '',
    'dewpoint_c': '',
    'relative_humidity': '',
    'wind_string':   '',
    'visibility_mi': '',
    'pressure_string': '',
    'pressure_in': '',
    'location': ''
    }

# ---------------------------------------------------------------
import urllib.request

def get_weather_data(station_id='KLAX'):
    url_general = 'http://www.weather.gov/xml/current_obs/{}.xml'
    url = url_general.format(station_id)
#     print(url)
    request = urllib.request.urlopen( url )
    content = request.read().decode()
#     print(content)

    # Using ElementTree to retrieve specific tags from the xml
    import xml.etree.ElementTree as ET
    xml_root = ET.fromstring(content)
#     print('xml_root: {}\n'.format(xml_root.tag))

    for data_point in weather_data_tags_dict.keys():
        weather_data_tags_dict[data_point] = xml_root.find(data_point).text

#     for key, value in weather_data_tags_dict.items():
#         print(key, value)

# ---------------------------------------------------------------
def populate_gui_from_dict():
    location.set(weather_data_tags_dict['location'])
    updated.set(weather_data_tags_dict['observation_time'].replace('Last Updated on ', ''))
    weather.set(weather_data_tags_dict['weather'])
    temp.set('{} \xb0F  ({} \xb0C)'.format(weather_data_tags_dict['temp_f'], weather_data_tags_dict['temp_c']))
    dew.set('{} \xb0F  ({} \xb0C)'.format(weather_data_tags_dict['dewpoint_f'], weather_data_tags_dict['dewpoint_c']))
    rel_humi.set(weather_data_tags_dict['relative_humidity'] + ' %')
    wind.set(weather_data_tags_dict['wind_string'])
    visi.set(weather_data_tags_dict['visibility_mi'] + ' miles')
    msl.set(weather_data_tags_dict['pressure_string'])
    alti.set(weather_data_tags_dict['pressure_in'] + ' in Hg')

#########################################################################################
# TAB 2
#######
# We are creating a container frame to hold all other widgets
weather_states_frame = ttk.LabelFrame(tab2, text=' Weather Station IDs ')
weather_states_frame.grid(column=0, row=0, padx=8, pady=4)

# ---------------------------------------------------------------
# Adding a Label
ttk.Label(weather_states_frame, text="Select a State: ").grid(column=0, row=0) # empty space for alignment

# ---------------------------------------------------------------
state = tk.StringVar()
state_combo = ttk.Combobox(weather_states_frame, width=5, textvariable=state)
state_combo['values'] = ('AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI',
                         'ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI',
                         'MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC',
                         'ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT',
                         'VT','VA','WA','WV','WI','WY'
                        )
state_combo.grid(column=1, row=0)
state_combo.current(0)                 # highlight first

# ---------------------------------------------------------------
# callback function
def _get_cities():
    state = state_combo.get()
    get_city_station_ids(state)

get_weather_btn = ttk.Button(weather_states_frame,text='Get Cities', command=_get_cities).grid(column=2, row=0)

from tkinter import scrolledtext
scr = scrolledtext.ScrolledText(weather_states_frame, width=30, height=17, wrap=tk.WORD)
scr.grid(column=0, row=1, columnspan=3)

# ---------------------------------------------------------------
for child in weather_states_frame.winfo_children():
        child.grid_configure(padx=6, pady=6)

# ---------------------------------------------------------------
def get_city_station_ids(state='ca'):
    url_general = 'http://w1.weather.gov/xml/current_obs/seek.php?state={}&Find=Find'
    state = state.lower()                       # has to be in lower case
    url = url_general.format(state)
    request = urllib.request.urlopen( url )
    content = request.read().decode()
#     print(content)

    parser = WeatherHTMLParser()
    parser.feed(content)

    # verify we have as many stations as cities
#     print(len(parser.stations) == len(parser.cities))

    scr.delete('1.0', tk.END)  # clear scrolledText widget for next btn click

    for idx in range(len(parser.stations)):
        city_station = parser.cities[idx] + ' (' + parser.stations[idx] + ')'
#         print(city_station)
        scr.insert(tk.INSERT, city_station + '\n')

#     print(parser.stations)
#     print(parser.cities)

from html.parser import HTMLParser

class WeatherHTMLParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.stations = []
        self.cities = []
        self.grab_data = False

    def handle_starttag(self, tag, attrs):
        for attr in attrs:
            if "display.php?stid=" in str(attr):
                cleaned_attr= str(attr).replace("('href', 'display.php?stid=", '').replace("')", '')
                self.stations.append(cleaned_attr)
                self.grab_data = True

    def handle_data(self, data):
        if self.grab_data:
            self.cities.append(data)
            self.grab_data = False

#########################################################################################
# TAB 3
#######
# We are creating a container frame to hold all other widgets
weather_images_frame = ttk.LabelFrame(tab3, text=' Weather Images ')
weather_images_frame.grid(column=0, row=0, padx=8, pady=4)

# ---------------------------------------------------------------
# requires Pillow (PIL in Python 2.x)
import PIL.Image
import PIL.ImageTk

im = PIL.Image.open("few_clouds.png")
photo = PIL.ImageTk.PhotoImage(im)
ttk.Label(weather_images_frame, image=photo).grid(column=0, row=0)

im = PIL.Image.open("night_few_clouds.png")
photo1 = PIL.ImageTk.PhotoImage(im)
ttk.Label(weather_images_frame, image=photo1).grid(column=1, row=0)

im = PIL.Image.open("night_fair.png")
photo2 = PIL.ImageTk.PhotoImage(im)
ttk.Label(weather_images_frame, image=photo2).grid(column=2, row=0)

#########################################################################################
# TAB 4 OpenWeatherMap
######################

# We are creating a container frame to hold other widgets
open_weather_cities_frame = ttk.LabelFrame(tab4, text=' Latest Observation for ')
open_weather_cities_frame.grid(column=0, row=0, padx=8, pady=4)

# Station City label
open_location = tk.StringVar()
ttk.Label(open_weather_cities_frame, textvariable=open_location).grid(column=0, row=1, columnspan=3)

# ---------------------------------------------------------------
# Adding a Label
ttk.Label(open_weather_cities_frame, text="City: ").grid(column=0, row=0)

# ---------------------------------------------------------------
open_city = tk.StringVar()
open_city_combo = ttk.Combobox(open_weather_cities_frame, width=16, textvariable=open_city)
open_city_combo['values'] = ('Los Angeles, US', 'London, UK', 'Paris, FR', 'Mumbai, IN', 'Beijing, CN')
open_city_combo.grid(column=1, row=0)
open_city_combo.current(0)                 # highlight first city station id

# ---------------------------------------------------------------
# callback function
def _get_station_open():
    city = open_city_combo.get()
    get_open_weather_data(city)

get_weather_btn = ttk.Button(open_weather_cities_frame,text='Get Weather', command=_get_station_open).grid(column=2, row=0)

# ---------------------------------------------------------------
for child in open_weather_cities_frame.winfo_children():
        child.grid_configure(padx=5, pady=2)

# ---------------------------------------------------------------
# We are creating a container frame to hold all other widgets
open_weather_conditions_frame = ttk.LabelFrame(tab4, text=' Current Weather Conditions ')
open_weather_conditions_frame.grid(column=0, row=1, padx=8, pady=4)

#================
ENTRY_WIDTH = 25
#================

# Adding Label & Textbox Entry widgets
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Last Updated:").grid(column=0, row=1, sticky='E')         # <== right-align
open_updated = tk.StringVar()
open_updatedEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_updated, state='readonly')
open_updatedEntry.grid(column=1, row=1, sticky='W')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Weather:").grid(column=0, row=2, sticky='E')               # <== increment row for each
open_weather = tk.StringVar()
open_weatherEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_weather, state='readonly')
open_weatherEntry.grid(column=1, row=2, sticky='W')                                  # <== increment row for each
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Temperature:").grid(column=0, row=3, sticky='E')
open_temp = tk.StringVar()
open_tempEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_temp, state='readonly')
open_tempEntry.grid(column=1, row=3, sticky='W')
#---------------------------------------------
# ttk.Label(open_weather_conditions_frame, text="Dewpoint:").grid(column=0, row=4, sticky='E')
# dew = tk.StringVar()
# dewEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=dew, state='readonly')
# dewEntry.grid(column=1, row=4, sticky='W')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Relative Humidity:").grid(column=0, row=5, sticky='E')
open_rel_humi = tk.StringVar()
open_rel_humiEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_rel_humi, state='readonly')
open_rel_humiEntry.grid(column=1, row=5, sticky='W')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Wind:").grid(column=0, row=6, sticky='E')
open_wind = tk.StringVar()
open_windEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_wind, state='readonly')
open_windEntry.grid(column=1, row=6, sticky='W')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Visibility:").grid(column=0, row=7, sticky='E')
open_visi = tk.StringVar()
open_visiEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_visi, state='readonly')
open_visiEntry.grid(column=1, row=7, sticky='W')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Pressure:").grid(column=0, row=8, sticky='E')
open_msl = tk.StringVar()
open_mslEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=open_msl, state='readonly')
open_mslEntry.grid(column=1, row=8, sticky='W')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Sunrise:").grid(column=0, row=9, sticky='E')
sunrise = tk.StringVar()
sunriseEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=sunrise, state='readonly')
sunriseEntry.grid(column=1, row=9, sticky='E')
#---------------------------------------------
ttk.Label(open_weather_conditions_frame, text="Sunset:").grid(column=0, row=10, sticky='E')
sunset = tk.StringVar()
sunsetEntry = ttk.Entry(open_weather_conditions_frame, width=ENTRY_WIDTH, textvariable=sunset, state='readonly')
sunsetEntry.grid(column=1, row=10, sticky='E')
#---------------------------------------------

# Add some space around each widget
for child in open_weather_conditions_frame.winfo_children():
        child.grid_configure(padx=4, pady=2)

#########################################################################################
# OpenWeatherMap Data collection

from Section1_Video4.API_key import OWM_API_KEY
from urllib.request import urlopen
import json

def get_open_weather_data(city='London,uk'):
    city = city.replace(' ', '%20')
    url = "http://api.openweathermap.org/data/2.5/weather?q={}&appid={}".format(city, OWM_API_KEY)
    response = urlopen(url)
    data = response.read().decode()
    json_data = json.loads(data)

    from pprint import pprint
    pprint(json_data)

    lat_long = json_data['coord']
    lastupdate_unix = json_data['dt']
    city_id = json_data['id']
    humidity = json_data['main']['humidity']
    pressure = json_data['main']['pressure']
    temp_kelvin = json_data['main']['temp']
    city_name = json_data['name']
    city_country = json_data['sys']['country']
    sunrise_unix = json_data['sys']['sunrise']
    sunset_unix = json_data['sys']['sunset']
    try: visibility_meter = json_data['visibility']
    except: visibility_meter = 'N/A'
    owm_weather = json_data['weather'][0]['description']
    weather_icon = json_data['weather'][0]['icon']
    wind_deg = json_data['wind']['deg']
    wind_speed_meter_sec = json_data['wind']['speed']

    def kelvin_to_celsius(temp_k):
        return "{:.1f}".format(temp_k - 273.15)

    def kelvin_to_fahrenheit(temp_k):
        return "{:.1f}".format((temp_k - 273.15)* 1.8000 + 32.00)

    from datetime import datetime
    def unix_to_datetime(unix_time):
        return datetime.fromtimestamp(int(unix_time)
        ).strftime('%Y-%m-%d %H:%M:%S')

    def meter_to_miles(meter):
        return "{:.2f}".format((meter * 0.00062137))

    if visibility_meter is 'N/A':
        visibility_miles = 'N/A'
    else:
        visibility_miles = meter_to_miles(visibility_meter)

    def mps_to_mph(meter_second):
        return "{:.1f}".format((meter_second * (2.23693629)))

    # -------------------------------------------------------
    # Update GUI entry widgets with live data
    open_location.set('{}, {}'.format(city_name, city_country))

    lastupdate = unix_to_datetime(lastupdate_unix)
    open_updated.set(lastupdate)
    open_weather.set(owm_weather)
    temp_fahr = kelvin_to_fahrenheit(temp_kelvin)
    temp_cels = kelvin_to_celsius(temp_kelvin)
    open_temp.set('{} \xb0F  ({} \xb0C)'.format(temp_fahr, temp_cels))
    open_rel_humi.set('{} %'.format(humidity))
    wind_speed_mph = mps_to_mph(wind_speed_meter_sec)
    open_wind.set('{} degrees at {} MPH'.format(wind_deg, wind_speed_mph))
    open_visi.set('{} miles'.format(visibility_miles))
    open_msl.set('{} hPa'.format(pressure))
    sunrise_dt = unix_to_datetime(sunrise_unix)
    sunrise.set(sunrise_dt)
    sunset_dt = unix_to_datetime(sunset_unix)
    sunset.set(sunset_dt)

    print(weather_icon)
    url_icon = "http://openweathermap.org/img/w/{}.png".format(weather_icon)
    ico = urlopen(url_icon)
    open_im = PIL.Image.open(ico)
    open_photo = PIL.ImageTk.PhotoImage(open_im)
    ttk.Label(open_weather_cities_frame, image=open_photo).grid(column=0, row=1)
    win.update()        # required or we won't see the icon

#======================
# Start GUI
#======================
# get_weather_data()
# populate_gui_from_dict()
win.mainloop()

_99_DesignWindowsApplication/Exercise Files/Section4 - Creating a GUI application with Tkinter/Section4_Video4/GUI_Weather_OpenWeatherMap.py


from selenium import webdriver
import pandas as pd
import random
import time

df = pd.read_csv('SalaryTravel.csv')

def get_professors():
    return df[df.Title.str.contains('PROFESSOR')]

df = get_professors()

browser = webdriver.Chrome()

class MultipleDirectoryMatchesException(Exception):
    pass

class NoDirectoryMatchesException(Exception):
    pass

def submit_form(first_name, last_name):
    first_name_textbox = browser.find_element_by_id('edit-firstname')
    first_name_textbox.send_keys(first_name)

    last_name_textbox = browser.find_element_by_id('edit-lastname')
    last_name_textbox.send_keys(last_name)

    captcha_answer = (browser.find_element_by_name('captcha-answer')
        .get_attribute('value'))
    captcha_textbox = browser.find_element_by_id('edit-captcha-test')
    captcha_textbox.send_keys(captcha_answer)

    captcha_textbox.submit()

def click_detail_link():
    a_tags = browser.find_elements_by_tag_name('a')
    a_tags = [a for a in a_tags if a.get_attribute('href')]
    detail_links = [a for a in a_tags if '/directory/detail' in a.get_attribute('href')]
    if len(detail_links) > 1:
        raise MultipleDirectoryMatchesException()
    elif not detail_links:
        raise NoDirectoryMatchesException()

    detail_link = detail_links[0]
    detail_link.click()

def get_details():
    details = browser.find_elements_by_css_selector('#block-system-main div p')
    detail_text = [d.text for d in details]
    department_raw = detail_text[1]
    title_raw = detail_text[2]

    department = department_raw.split(':')[1].strip()
    title = title_raw.split(':')[1].strip()

    return department, title

def get_first_last_name(name):

    def get_name_parts(name):
        return name.split(',') if ',' in name else (None, None)

    def get_first_name(name):
        last, first = get_name_parts(name)
        return first

    def get_last_name(name):
        last, first = get_name_parts(name)
        return last

    first_name = get_first_name(name)
    last_name = get_last_name(name)

    return first_name, last_name

def crawl():
    details = []

    browser.get('https://www.directory.gatech.edu/')

    for row in df.itertuples():
        first_name, last_name = get_first_last_name(row.Name)
        submit_form(first_name, last_name)

        multiple_matches = False
        try:
            click_detail_link()
            department, title = get_details()
        except MultipleDirectoryMatchesException:
            department, title = None, None
            multiple_matches = True
        except NoDirectoryMatchesException:
            department, title = None, None
        except:
            department, title = None, None
        details.append({
            'Name': row.Name,
            'Department': department,
            'Title': title,
            'MultipleMatches': multiple_matches
        })

        time.sleep(random.randrange(3, 10))

    browser.close()

    return details

if __name__ == '__main__':
    details = crawl()
    details = pd.DataFrame(details)
    details.to_csv('Details.csv', index=False)


from tkinter import *
from BetTypes import *
from functools import reduce

#Create a bet calculator class
class BetCalculator:

    def __init__(self, master):

        self.master = master
        master.title("Bet Calculator")

        #----------Top Frame
        self.topframe = Frame(master)

        Label(self.topframe,justify=LEFT, text = "Stake").grid(row=0, column = 0, sticky=W)

        self.stakeinput = StringVar()
        Entry(self.topframe, width=10, textvariable = self.stakeinput, justify=LEFT).grid(row=0, column=1)

        Label(self.topframe, text = "Each-Way").grid(row=0, column = 2)

        self.ewinput = IntVar()
        r1 = Radiobutton(self.topframe, text="Yes", variable=self.ewinput, value=True).grid(row=0,column=3)
        r2 = Radiobutton(self.topframe, text="No",variable=self.ewinput, value=False).grid(row=0,column=4)

        Label(self.topframe, text="Bet Type").grid(row=1,column=0)

        self.bettype = StringVar()
        choices = ["Single/Accum", "Lucky 15 Type", "Yankee Type"]
        self.bettype.set("Pick an option")

        OptionMenu(self.topframe, self.bettype, *choices).grid(row=1,column=1)

        Label(self.topframe, text="No. of Selections").grid(row=1, column=2)

        self.selections = StringVar()
        self.selections.set('4')
        selectchoices = [str(i) for i in range(1,9)]

        def ChangeMidFrames(event):
            for widget in self.midframe.winfo_children():
                widget.destroy()
            for i in range(1,int(event)+1):
                showMidframes(rows=i)

        OptionMenu(self.topframe,  self.selections, *selectchoices, command=ChangeMidFrames).grid(row=1, column=3)

        def storewin(event):
            wins = {"Win":True,"Place":False}
            self.listOfWins.append(wins[event])

        #----------Middle Frame
        self.midframe = Frame(master)

        def showMidframes(rows=1):

            Label(self.midframe, text="Odds").grid(row=rows, column = 0)

            self.odds = StringVar()
            Entry(self.midframe, width=5, textvariable = self.odds, justify = RIGHT).grid(row=rows, column=1)

            Label(self.midframe, text="E/W Terms").grid(row=rows, column = 2)

            self.ewterms = StringVar()
            Entry(self.midframe, width=5, textvariable = self.ewterms, justify=RIGHT).grid(row=rows, column=3)

            Label(self.midframe, text="Win?").grid(row=rows, column=4)

            self.win = StringVar()
            self.win.set("Win")
            winplace = ["Win", "Place"]
            OptionMenu(self.midframe, self.win, *winplace, command=storewin).grid(row=rows, column=5)

        for i in range(1,int(self.selections.get())+1):
            showMidframes(rows=i)

        #----------Bottom Frame
        self.bottomframe = Frame(master)

        Label(self.bottomframe, text = "Total Stake").grid(row=1, column=0)
        Label(self.bottomframe, text = "Payout").grid(row=1, column=2)

        self.totalstakes = StringVar()
        lblTotalStakes = Label(self.bottomframe, width=10, textvariable=self.totalstakes).grid(row=1, column=1)

        self.payout = StringVar()
        lblPayout = Label(self.bottomframe,width=10, textvariable=self.payout).grid(row=1, column=3)

        btComputeStakes = Button(self.bottomframe, text = "Compute Payout", command=self.computePayout).grid(row=0, column = 0,columnspan=2)

        self.topframe.pack(side=TOP)
        self.midframe.pack()
        self.bottomframe.pack(side=BOTTOM)

        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        self.listOfOdds = []
        self.listOfEWTerms = []
        self.listOfWins = [True]

    def computePayout(self):

        i=0
        for widget in self.midframe.winfo_children():
            if widget.winfo_class() == 'Entry' and i%2==0:
                self.listOfOdds.append(widget.get())
                i+=1
            elif widget.winfo_class() == 'Entry' and i%2==1:
                self.listOfEWTerms.append(widget.get())
                i+=1

        self.listOfOdds = [reduce(lambda x,y:x/y, list(map(float,item.split('/')))) for item in self.listOfOdds]
        self.listOfEWTerms = [reduce(lambda x,y:x/y, list(map(float,item.split('/')))) for item in self.listOfEWTerms]

        if self.bettype.get()=="Single/Accum":
            bet = Accum(stakes = float(self.stakeinput.get()), odds=self.listOfOdds, ew=self.ewinput.get(), ewterms=self.listOfEWTerms, winner=self.listOfWins)

        elif self.bettype.get()=="Lucky 15 Type":
            bet = LuckyFifteen(stakes = float(self.stakeinput.get()), odds=self.listOfOdds, ew=self.ewinput.get(), ewterms=self.listOfEWTerms ,winner=self.listOfWins)

        elif self.bettype.get()=="Yankee Type":
            bet = Yankee(stakes = float(self.stakeinput.get()), odds=self.listOfOdds, ew=self.ewinput.get(), ewterms=self.listOfEWTerms,winner=self.listOfWins)

        self.totalstakes.set(bet.totalstakes())
        self.payout.set(round(bet.payout(),2))

#Execution
if __name__=='__main__':

    #Step 6: Create the main window of an application
    root = Tk()

    #Step 6: Tell our calculator class to use this window
    my_gui = BetCalculator(root)

    #Step 6: Executable loop on the application, waits for user input
    root.mainloop()


from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import log_loss

import pandas as pd

import lightgbm as lgb
from datetime import datetime
import os

phase1 = '/home/malware/trace1_test/dex.txt'
phase2 = '/home/OpenCode/malware/phase2/trace1_test/dex.txt'
def line2data(line):
    return line.strip().split(';')

def readFile(filename):
    dataList = []
    shaList = []
    inf = open(filename)
    keys = line2data(inf.readline())
    for line in inf.readlines():
        vals = line2data(line)
        newData = {}
        for i in range(len(keys)):
            newData[keys[i]] = vals[i]
        dataList.append(newData)
        shaList.append(newData['sha1'])
    return dataList,shaList

def processDex(dataList):
    train = []
    for data in dataList:
        newData = {}
        permList = data['permission_list'].split(',')
        # newData['perms']  = len(permList)
        for key in data:
            if key not in ['sha1','permission_list','opcode_count']:
                newData[key] = int(data[key])
        train.append(newData)
    return train

def binLabel(typeList):
    result = []
    for data in typeList:
        result.append(int(data['safe_type']))
    return result

def multiLabel(typeList):
    result = []
    for data in typeList:
        result.append(int(data['family_id']))
    return result

def readDataFromDir(dirname,multi=False):
    dexFile = os.path.join(dirname,'dex.txt')
    typeFile = os.path.join(dirname,'safetype.txt')
    v = DictVectorizer()

    dataList,nameList = readFile(dexFile)
    trainList = processDex(dataList)
    x = v.fit_transform(trainList)

    typeList,_ = readFile(typeFile)
    if multi:
        y = multiLabel(typeList)
    else:
        y = binLabel(typeList)
    return x,y,nameList,trainList

def formatLabel(y_pred,multi=False):
    if multi:
        newLabel = []
        classLen = len(y_pred[0])
        for i in range(len(y_pred)):
            label = 0
            for j in range(classLen):
                if y_pred[i][j]>0.5:
                    label = j
            newLabel.append(label)
        y_pred = newLabel
    else:
        for i in range(len(y_pred)):
            if y_pred[i]>=.5:       # setting threshold to .5
                y_pred[i]=1
            else:
                y_pred[i]=0
    return y_pred

def checkModel(y_test,y_pred,multi=False):

    y_pred = formatLabel(y_pred)

    #calculating accuracy
    accuracy_lgbm = accuracy_score(y_pred,y_test)
    print(accuracy_lgbm)

    if not multi:
        auc_lgbm =  roc_auc_score(y_test,y_pred)
        print(auc_lgbm)

def checkMultiLabel():
    x,y,shaList,_ = readDataFromDir('/home/malware/trace1_train1',multi=True)

    x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.1)
    train_data=lgb.Dataset(x_train,label=y_train)

    param = {'num_leaves':150, 'objective':'multiclass','max_depth':7,'learning_rate':.05,'max_bin':200,'num_class':6}
    param['metric'] = ['auc']

    #Here we have set max_depth in xgb and LightGBM to 7 to have a fair comparison between the two.

    #training our model using light gbm
    num_round=50
    start=datetime.now()
    lgbm=lgb.train(param,train_data,num_round)
    stop=datetime.now()

    #Execution time of the model
    execution_time_lgbm = stop-start
    print('train time:',execution_time_lgbm)

    #predicting on test set
    y_pred=lgbm.predict(x_test)
    checkModel(y_test,y_pred,multi=True)
    x1,y1,_,_ = readDataFromDir('/home/malware/trace1_train2')
    checkModel(y1,lgbm.predict(x1))

def makeModel(x_train,y_train,multi=False):
    train_data=lgb.Dataset(x_train,label=y_train)

    if multi:
        param = {'num_leaves':50, 'objective':'multiclass','max_depth':7,'learning_rate':.05,'max_bin':200,'num_class':6}
        param['metric'] = ['auc']
    else:
        param = {'num_leaves':50, 'objective':'binary','max_depth':7,'learning_rate':.05,'max_bin':200}
        param['metric'] = ['auc']

    num_round=1000
    lgbm=lgb.train(param,train_data,num_round)
    lgbm.save_model('model.txt', num_iteration=lgbm.best_iteration)

    return lgbm

def predictData(filename,multi=False,append=False):
    v = DictVectorizer()
    x1,y1,_,trainX1 = readDataFromDir('/home/malware/trace1_train1',multi=multi)
    x2,y2,_,trainX2 = readDataFromDir('/home/malware/trace1_train2',multi=multi)
    x3,y3,_,trainX3 = readResultLabel(multi)
    trainX = trainX1+trainX2
    if append:
        trainX = trainX+trainX3
    x =  v.fit_transform(trainX)

    if append:
        y = y1+y2+y3
    else:
        y = y1 + y2
    print(len(trainX),len(y))
    model = makeModel(x,y,multi=multi)
    dataList, nameList = readFile(filename)
    trainList = processDex(dataList)
    x_test = v.fit_transform(trainList)
    y_pred = model.predict(x_test)
    if multi:
        outf = open('data/trace1_lgbm_output.txt', 'w+')
        outf.write('sha1,0,1,2,3,4,5\n')
        for i in range(len(nameList)):
            result = y_pred[i]
            outf.write(
                '%s,%f,%f,%f,%f,%f,%f\n' % (nameList[i], result[0], result[1], result[2], result[3], result[4], result[5]))
    return nameList,formatLabel(y_pred,multi=multi)

def solutionPhase1():
    nameList,y1 = predictData(phase2)
    _,y2 = predictData(phase2,multi=True)
    with open('/home/malware/phase1_trace1.csv','w+') as outf:
        for i in range(len(nameList)):
            outf.write(nameList[i]+','+str(int(y1[i]))+','+str(y2[i])+'\n')

def solutionPhase2():
    nameList,y1 = predictData(phase2,multi=False,append=False)
    _,y2 = predictData(phase2,multi=True,append=False)
    with open('/home/malware/trace1_test/trace1.csv','w+') as outf:
        for i in range(len(nameList)):
            outf.write(nameList[i]+','+str(int(y1[i]))+','+str(y2[i])+'\n')

def readResultLabel(multi):
    df2 = pd.read_csv('/home/malware/phase1_trace1.csv',header=None)
    df2.columns = ['sha1','safe_type','family_id']

    v = DictVectorizer()
    dataList, nameList = readFile(phase1)
    trainList = processDex(dataList)
    x = v.fit_transform(trainList)

    if multi:
        y = list(df2.family_id)
    else:
        y = list(df2.safe_type)
    return x, y, nameList, trainList

if __name__=='__main__':
    # solutionPhase1()
    solutionPhase2()


"""Module containing the rooms' descriptions and how they are displayed."""

from random import randint

import pygame

ENTRY_CAVE_TEXT = (
    "As you awaken in a dimly lit room, confusion sets in. Your surroundings are unfamiliar "
    "and disorienting, leaving you feeling lost and unsure of what to do next. You quickly "
    "realize that you need to find a way out of this place. A faint whisper echoes in your "
    "mind, urging you to 'look at' the walls. Perhaps they hold a clue to your escape. It's "
    "time to start searching and uncovering the secrets of this mysterious room."
)

VALLEY_TEXT = (
    "As you step out of the dark and confining room, you're greeted by "
    "the sight of an expansive green area. The soft blades of grass tickle "
    "your feet as you take in your surroundings. The area is dotted with tall "
    "trees, providing shade and a sense of tranquility. However, you quickly "
    "remember the task at hand - to find a way to survive. You'll need to explore "
    "the area and take advantage of the resources it has to offer. The fresh air "
    "and open space invigorate you, giving you the energy to tackle whatever "
    "challenges lay ahead."
)

class RoomText:
    """Room text object displaying the room's description."""

    def __init__(self, cmd_line):
        """Initialize object."""
        self.cmd_line = cmd_line

        self.room_text_dict = {
            "entry_cave": ENTRY_CAVE_TEXT,
            "valley": VALLEY_TEXT,
        }
        self.room_first_entry = dict.fromkeys(self.room_text_dict.keys(), True)
        self.update_text = True
        self.past_updated_text = 0
        self.update_text_speed = 20
        self.letter_counter = 0
        self.line_counter = 0
        self.prev_value = ""
        self.is_first = True

        self.keyboard_sound = pygame.mixer.Sound("src/audio/mech_keyboard.wav")
        self.enter_sound = pygame.mixer.Sound("src/audio/mech_keyboard_enter.wav")
        self.enter_sound.set_volume(0.1)

    def update_text_cooldowns(self):
        """Update cooldowns to type the next letter."""
        current_time = pygame.time.get_ticks()
        if not self.update_text:
            if current_time - self.past_updated_text >= (
                self.update_text_speed - randint(-20, 20)
            ):
                self.update_text = True

    def update_room_first_entry(self):
        """Check if current room has been already accessed in the past."""
        if self.room_first_entry[self.cmd_line.map_state]:
            self.cmd_line.active_player = False
            self.room_name = self.cmd_line.map_state.upper().replace("_", " ")
            self.room_text = self.room_text_dict[self.cmd_line.map_state]
            self.room_text = self.cmd_line.split_long_user_input(self.room_text)
            self.update_text_cooldowns()
            self.display_animated_text()

    def display_animated_text(self):
        """Display text letter by letter directly into the CL history."""
        # Get the current length of the CL history as starting point
        if self.is_first:
            self.prev_line_counter = self.cmd_line.len_history
            self.is_first = False

        # Write room description as it was typed in a mechanical keyboard
        if self.update_text == True:
            self.play_keyboard_sound()
            self.letter_counter += 1
            text = self.room_text[self.line_counter][: self.letter_counter]
            try:
                self.cmd_line._history[
                    self.prev_line_counter + self.line_counter
                ] = text
            except IndexError:
                self.cmd_line._history.append(text)
            self.past_updated_text = pygame.time.get_ticks()
            if self.letter_counter == len(self.room_text[self.line_counter]) + 2:
                self.line_counter += 1
                self.letter_counter = 0
                if self.line_counter == len(self.room_text):
                    self.update_text = False
                    self.is_first = True
                    self.line_counter = 0
                    self.room_first_entry[self.cmd_line.map_state] = False
                    self.keyboard_sound.stop()
                    self.cmd_line.input.value = ""
                    self.cmd_line.active_player = True
                    self.enter_sound.play()

    def play_keyboard_sound(self):
        """Play the sound of a mechanical keyboard typing."""
        if self.letter_counter == 0:
            self.keyboard_sound.play(loops=-1)

    def display_letter_on_cl(self, prev_value, new_letter):
        """Display room's description."""
        self.cmd_line._input.draw_letter_after_value(
            self.cmd_line.surface, prev_value, new_letter
        )


from ctypes import c_uint32
from multiprocessing import Pipe, Value
from multiprocessing.connection import Connection as PipeConnection

from py_mpworker import MPWorker

TEST_INTERVAL = 1

def process_event(
    state: Value, desired_call_count: int, finished_signaler: PipeConnection,
):
    with state.get_lock():
        state.value += 1
        if state.value == desired_call_count:
            finished_signaler.send(None)

def test_mpworker_callback_should_be_called_multiple_times():
    desired_call_count = 5
    (signal_receiver, finished_signaler) = Pipe(duplex=False)
    shared_state = Value(c_uint32)
    shared_state.value = 0

    def callback(state: Value):
        process_event(state, desired_call_count, finished_signaler)

    worker = MPWorker("test_worker", TEST_INTERVAL, callback, shared_state)
    worker.start()
    signal_receiver.poll(3600)
    worker.stop()
    with shared_state.get_lock():
        assert shared_state.value == desired_call_count


import pytest
import System
import Student

# IMPORTANT - The code only uses assignments from 'comp_sci'
#                         but each course has only "assignment1" and "assignment2" by default
#                         so it will always pass pytest unless you add and check an alternate\
#                         will add a section to create the assignment here
def test_view_assignments(grading_system):

    #added to ensure there is the appropriate assignment tested for
    grading_system.login('goggins', 'augurrox')
    grading_system.usr.create_assignment('assignment5', '03/10/20', 'databases')

    # actual test
    grading_system.login('akend3', '123454321')
    grading_system.usr.view_assignments('databases')
    assert 'assignment5' in grading_system.usr.users['akend3']['courses']['databases']

@pytest.fixture
def grading_system():
    gradingSystem = System.System()
    gradingSystem.load_data()
    return gradingSystem

# fails pytest

CS_4320 Software Development 1/assignments/assignment-five/05-testing/test_view_assignments.py


from flask import Flask, request, render_template
import os
import pickle
import zipfile

with zipfile.ZipFile('svc_model.zip', 'r') as zip_ref:
    zip_ref.extractall('.')

loaded_model = pickle.load(open("svc_model.sav", "rb"))

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def home():
    message = "Welcome to my flask based web application ... !!!"
    return render_template("home.html", message=message)

@app.route('/getPrediction', methods=["GET", "POST"])
def getPrediction():
    incoming_text = request.form["review_text"]
    print(incoming_text)
    res = make_prediction_linReg(incoming_text)
    print(res)
    return res

def make_prediction_linReg(text):
    res = loaded_model.predict([text])
    result = ""
    if res == 0:
        result = "Negative Review"
    elif res == 1:
        result = "Neutral Review"
    elif res == 2:
        result = "Positive Review"
    else:
        result = "UNKNOWN"
    return result

if __name__ == '__main__':
    app.run(debug=True)


import json
import boto3
import numpy as np
import PIL.Image as Image
import tensorflow as tf

# Change references to bucket as appropriate
# 1. dsikar.models.bucket
# 2. tensorflow-images-predictions-dsikar

s3 = boto3.resource('s3')
client_s3 = boto3.client('s3')
result = client_s3.download_file("dsikar.models.bucket",'firemodel.h5', "/tmp/firemodel.h5")
model = tf.keras.models.load_model('/tmp/firemodel.h5')
plot_size = 64
IMAGE_SHAPE = (plot_size, plot_size)
CATEGORIES = ['nofire', 'fire']

def lambda_handler(event, context):
  bucket_name = event['Records'][0]['s3']['bucket']['name']
  key = event['Records'][0]['s3']['object']['key']
  img = readImageFromBucket(key, bucket_name).resize(IMAGE_SHAPE)
  img = np.array(img)/255.0
  prediction = model.predict(np.expand_dims(img, axis=0))[0]
  predicted_class = CATEGORIES[np.argmax(prediction)]
  print('ImageName: {0}, Prediction: {1}'.format(key, predicted_class))
  response_str = 'ImageName: {0}, Prediction: {1}'.format(key, predicted_class)
  filename = key + '.txt'
  client_s3.put_object(Body=response_str, Bucket='tensorflow-images-predictions-dsikar', Key=filename)

def readImageFromBucket(key, bucket_name):
  bucket = s3.Bucket(bucket_name)
  object = bucket.Object(key)
  response = object.get()
  return Image.open(response['Body'])


from flask import Flask, request, jsonify
from flask_mysqldb import MySQL
from os import urandom
from yaml import load, FullLoader
import json

app = Flask(__name__)
mysql = MySQL(app)

# MySQL Configuration
db_keeps = load(open('db.yaml'), Loader=FullLoader)
app.config['MYSQL_HOST'] = db_keeps['mysql_host']
app.config['MYSQL_USER'] = db_keeps['mysql_user']
app.config['MYSQL_PASSWORD'] = db_keeps['mysql_password']
app.config['MYSQL_DB'] = db_keeps['mysql_db']
app.config['SECRET_KEY'] = urandom(24)

@app.after_request
def add_headers(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization, data')
    return response

@app.route('/add-data/<provider>')
def index(provider):
    f = open(f'sites/{provider}.json')
    data = json.load(f)
    cur = mysql.connection.cursor()
    for listing in data:
        infochips = listing['infoChips'].split(',')
        title = listing['title']
        description = listing['description']
        rent = listing['rent']
        imgCount = listing['imgCount']
        imgs = listing['imgs']
        furnishing = listing['furnishing']
        postedBy = listing['postedBy']
        infoChips = ", ".join(infochips)
        date = listing['date']
        area = listing['area']
        updatedOn = listing['updatedOn']
        bhk = listing['bhk']
        source = listing['source']
        contactType = listing['contactType']
        contact = listing['contact']

        cur.execute("INSERT INTO listings (title, description, rent, contactType, contact, imgCount, urlList, furnishing, postedBy, infoChips, date, area, updatedOn, bhk, source) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (title, description, rent, contactType, contact, imgCount, imgs, furnishing, postedBy, infoChips, date, area, updatedOn, bhk, source))
        cur.connection.commit()
    cur.close()
    return "Added to database"

@app.route('/api/v1.7/available')
def db():
    cur = mysql.connection.cursor()
    q = cur.execute("SELECT * FROM listings;")
    if q > 0:
        allApartments = []
        listings = cur.fetchall()
        for _list in listings:
            infoChipsList = _list[14].split(', ')
            imgUrlsList = _list[2].split(',')
            allApartments.append({
                "id": _list[0],
                "title": _list[1],
                "description": _list[15],
                "imgUrl": imgUrlsList,
                "furnishing": _list[3],
                "area": _list[4],
                "bhk": _list[5],
                "imgCount": _list[6],
                "postedBy": _list[7],
                "rent": _list[8],
                "contactType": _list[9],
                "contact": _list[10],
                "source": _list[11],
                "date": _list[12],
                "updatedOn": _list[13],
                "infoChips": infoChipsList
            })
    return jsonify(allApartments)

@app.route('/api/filters')
def filters():
    if len(request.args) == 4:
        bhk = request.args.get('bhk')
        furnishings = request.args.get('furnishing').split(',')
        area = request.args.get('area')

        if furnishings[0] != '':
            furnishing = "'" + "', '".join(furnishings) + "'"
        else:
            furnishing = "'semifurnished','furnished','unfurnished'"

        priceQuery = request.args.get('price').split("to")
        if len(priceQuery) == 2:
            priceTo = priceQuery[1]
        else:
            priceTo = '100'

        if bhk != '':
            queryBhk = f"(bhk IN ({bhk}))"
        else:
            queryBhk = f"(bhk IN (1, 2, 3))"
        queryFurnishing = f"(furnishing IN ({furnishing}))"
        queryPrice = f"(rent <= {priceTo}000)"
        finalQuery = f"SELECT * FROM listings WHERE {queryBhk} AND {queryFurnishing} AND {queryPrice} AND area='{area}';"
        print('\n' + finalQuery + '\n')
        flats = []
        cur = mysql.connection.cursor()
        q = cur.execute(finalQuery)
        if q > 0:
            listings = cur.fetchall()
            for _list in listings:
                infoChipsList = _list[14].split(',')
                imgUrlsList = _list[2].split(',')
                flats.append({
                    "id": _list[0],
                    "title": _list[1],
                    "description": _list[15],
                    "imgUrl": imgUrlsList,
                    "furnishing": _list[3],
                    "area": _list[4],
                    "bhk": _list[5],
                    "imgCount": _list[6],
                    "postedBy": _list[7],
                    "rent": _list[8],
                    "contactType": _list[9],
                    "contact": _list[10],
                    "source": _list[11],
                    "date": _list[12],
                    "updatedOn": _list[13],
                    "infoChips": infoChipsList
                })
        return jsonify(flats)
    else:
        return "Invalid request"

if __name__ == '__main__':
    app.run(debug=True)


"""
The class contains a neural net for predicting 13824 led
brightness values from an 30 bin fft vector input.
"""
import os
import keras
from keras.models import Sequential
from keras.utils import plot_model
from keras.utils.vis_utils import model_to_dot
from keras.layers import Dense, LSTM, Dropout, Activation
from keras.optimizers import SGD
from keras.models import model_from_json
from keras.models import load_model
from keras import backend as kerasBackend
import numpy as np

# os.environ['CUDA_VISIBLE_DEVICES'] = '-1' #force Tensorflow to use the
# computed
LOAD_MODEL = True
SAVE_MODEL = False

MODEL_FILE_PATH = './data/dictionary_model.h5'
MODEL_TRAININGS_DATA_FILE_PATH = './data/trainingsset_dodeca.csv'
MODEL_SAVE_FILE_PATH = './data/dictionary_model.h5'

INPUT_DIM = 512
BATCH_SIZE = 32
EPOCHS = 30
INITIAL_EPOCHS = 100

HIDDEN1_DIM = 512
HIDDEN2_DIM = 64
OUTPUT_DIM = 8

model = Sequential()

def load_model_from_file():
    """
    Load model from file
    """
    global model
    model = load_model(MODEL_FILE_PATH)
    model._make_predict_function()
    print('Loaded saved model from file')

def train_model():
    """
    loading the trainingsdata from a textfile. Convert the
    trainingpoints in the right dimension: One line in the text file is
    one trainingpoint with 30 FFT values and 13824 LED values, separated by tabulators
    """
    global model
    # import fft and led input data
    file_name = MODEL_TRAININGS_DATA_FILE_PATH
    file = open(file_name)
    print('Loading Trainingsdata from File:', file_name, '  ...')
    values = np.loadtxt(file_name, dtype='float32')
    print('Trainingsdata points: ', values.shape[0], "\n")
    print('Trainingsdata shape: ', values.shape, "\n")

    # split into input and outputs
    training_input, training_output = values[:,
                                             :-OUTPUT_DIM], values[:, INPUT_DIM:]
    print(
        'training_input shape: ',
        training_input.shape,
        'training_output shape: ',
        training_output.shape)
    my_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)
    model.add(
        Dense(
            HIDDEN1_DIM,
            activation='sigmoid',
            input_dim=INPUT_DIM,
            kernel_initializer=my_init,
            bias_initializer=my_init))
    model.add(
        Dense(
            HIDDEN2_DIM,
            activation='sigmoid',
            input_dim=HIDDEN1_DIM,
            kernel_initializer=my_init,
            bias_initializer=my_init))
    model.add(
        Dense(
            OUTPUT_DIM,
            activation='sigmoid',
            kernel_initializer=my_init,
            bias_initializer=my_init))
    sgd = SGD(lr=0.2, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(
        loss='binary_crossentropy',
        optimizer=sgd,
        metrics=['accuracy'])
    model.fit(
        training_input,
        training_output,
        epochs=INITIAL_EPOCHS,
        batch_size=32,
        shuffle=True)
    model._make_predict_function()
    model.summary()
    print('Loaded new model')

def new_model_handler(unused_addr, args):
    """
    this function should reinitialize the model, to start the training from scratch again.
    ToDo: make it work. Probably the crash is caused because of the multi-threading?
    """
    global model
    kerasBackend.clear_session()
    my_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)

    model.add(
        Dense(
            6144,
            activation='sigmoid',
            input_dim=30,
            kernel_initializer=my_init,
            bias_initializer=my_init))
    model.add(
        Dense(
            OUTPUT_DIM,
            activation='sigmoid',
            kernel_initializer=my_init,
            bias_initializer=my_init))
    sgd = SGD(lr=0.5, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(
        loss='binary_crossentropy',
        optimizer=sgd,
        metrics=['accuracy'])
    model.fit(
        training_input,
        training_output,
        epochs=1,
        batch_size=32,
        shuffle=True)
    model._make_predict_function()
    print('Loaded new model')

def train_handler(unused_addr, args):
    """
    neural network trainer
    """
    global model
    model.fit(
        training_input,
        training_output,
        epochs=EPOCHS,
        batch_size=BATCH_SIZE,
        shuffle=True)
    model._make_predict_function()
    print('training finished...')
    print('')

def frame_count_handler(unused_addr, args):
    """
    a function to synchronize for recording the output of the neural network
    """
    #print('received frameCoount: ', args)
    global frame_count
    frame_count = args

def run():
    """
    Executes model loading/training/saving
    """
    global model
    if LOAD_MODEL:
        load_model_from_file()
    else:
        train_model()
    if SAVE_MODEL:
        model.save(MODEL_SAVE_FILE_PATH)
        print('Saved new model to path: ', MODEL_SAVE_FILE_PATH)
        model.summary()

if __name__ == "__main__":
    run()


import xml.etree.ElementTree as ET
import json
import os
import sys
import cv2
import matplotlib.pyplot as plt

class JaguarAnnotationParser:
    def __init__(self, filename):
        self.filename = filename

    def parse(self):
        self.root = ET.parse(self.filename).getroot()

    def getBoundingBoxes(self):
        bboxes = []
        for bbox in self.root.iter('bndbox'):
            box = []
            for point in bbox:
                box.append(int(point.text))
            bboxes.append(box)
        return bboxes

    def getImageFileName(self):
        return os.path.dirname(self.filename) \
                + '/../' \
                + os.path.basename(self.filename).split('.')[0] \
                + '.jpg'

    def getWidth(self):
        return int(self.root.find('size')[0].text)

    def getHeight(self):
        return int(self.root.find('size')[1].text)

    def getClassName(self):
        return 'jaguar'

if __name__ == '__main__':
    args = sys.argv
    if not len(args) == 2:
        print('Usage: {} <Folder name of annotations>'.format(args[0]))
        exit(1)

    folder = args[1]
    files = ['{}/{}'.format(folder, x.strip()) for x in os.listdir(folder) if x.endswith('.xml')]

    # n = min(10, len(files))
    # files = files[:n]
    n = len(files)

    result = {}
    reid_folder = '{}/../reid'.format(folder)
    for file in files:
        obj = JaguarAnnotationParser(file)
        obj.parse()
        image = cv2.imread(obj.getImageFileName())
        if image is None:
            print('Failed to read image {}: {}'.format(file, obj.getImageFileName()))
            exit(1)
        bboxes = obj.getBoundingBoxes()

        for i in range(len(bboxes)):
            box = bboxes[i]
            subimg = image[box[1]:box[3], box[0]:box[2],] # Index as y,x
            imname = '{}/{}_{}.jpg'.format(reid_folder, os.path.basename(file).split('.')[0], i)
            print(imname)
            cv2.imwrite(imname, subimg)


import sys
from collections import deque
input = sys.stdin.readline

n = int(input())

lst=[]
for i in range(n):
    lst.append(list(map(int, input().rstrip())))

dx=[0,0,1,-1]
dy=[1,-1,0,0]

def bfs(lst,a,b):
    q = deque()
    q.append([a,b])
    lst[a][b] == 0
    cnt =1

    while q:
        x,y = q.popleft()
        lst[x][y] = 0

        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]

            if nx<0 or nx>= len(lst) or ny<0 or ny>=len(lst):
                continue

            if lst[nx][ny] == 1:
                lst[nx][ny] = 0
                q.append([nx,ny])
                cnt +=1
    return cnt

rst = []
for i in range(n):
    for j in range(n):
        if lst[i][j] ==1:
            cnt = bfs(lst, i, j)
            rst.append(cnt)
rst.sort()
print(len(rst))
for i in rst:
    print(i)


from sklearn import svm
import numpy as np
import os
import copy
import utils

class svm_model():
    def __init__(self, train_data, train_label, test_data, test_label):
        self.train_data = train_data
        self.train_label = train_label
        self.test_data = test_data
        self.test_label = test_label
        self.clf_list = []

    def generate_clf(self):
        train_data = self.train_data
        test_data = self.test_data

        train_data = train_data.reshape(train_data.shape[0], -1)
        test_data = test_data.reshape(test_data.shape[0], -1)

        for k in range(4):
            print("Training %d clf" %(k))
            label_k = np.where(train_label==k, 1, 0)
            clf = svm.SVC(C=10, probability=True, random_state=0)
            print(train_data.shape, label_k.shape)
            clf.fit(train_data, label_k)
            self.clf_list.append(clf)

    def test_clfs(self, test_data, test_label):
        test_data = test_data.reshape(test_data.shape[0], -1)
        acc = 0
        correct = 0
        preds = []
        for k in range(len(test_data)):
            proba_list = []
            for clf in self.clf_list:
                proba = clf.predict_proba(test_data[k].reshape(1,-1))
                proba_list.append(proba[0][1])
            pred = np.argmax(proba_list)
            preds.append(pred)
        for k in range(len(test_label)):
            if test_label[k] == preds[k]:
                correct += 1
        acc = correct / float(len(test_label))
        return acc, correct

if __name__=="__main__":
    data_path = "./SEED-IV"

    model_list = []
    acc_list = []

    for experiment in os.listdir(data_path):
        experiment_path = data_path+"/"+experiment
        print("Experiment ID: ", experiment)

        train_data_list = []
        train_label_list = []
        test_data_list = []
        test_label_list = []

        for session in os.listdir(experiment_path):
            session_path = experiment_path+"/"+session
            print("Session ID: ", session)
            train_data = np.load(session_path+"/train_data.npy")
            train_label = np.load(session_path+"/train_label.npy")
            test_data = np.load(session_path+"/test_data.npy")
            test_label = np.load(session_path+"/test_label.npy")

            train_data_list.append(train_data)
            train_label_list.append(train_label)
            test_data_list.append(test_data)
            test_label_list.append(test_label)

        for k in range(len(train_data_list)):
            print("Take %d as test" %(k))
            train_input = copy.deepcopy(train_data_list)
            train_label = copy.deepcopy(train_label_list)
            test_input = copy.deepcopy(test_data_list)
            test_label = copy.deepcopy(test_label_list)

            #print(len(train_label))
            model_test_data = test_input[k]
            model_test_label = test_label[k]
            del train_input[k]
            del train_label[k]
            del test_input[k]
            del test_label[k]

            train_input = np.concatenate(train_input)
            train_label = np.concatenate(train_label)
            test_input = np.concatenate(test_input)
            test_label = np.concatenate(test_label)

            model = svm_model(train_input, train_label, test_input, test_label)
            model.generate_clf()

            acc, correct = model.test_clfs(test_data=model_test_data, test_label=model_test_label)
            print("acc: %f, correct: %d" %(acc, correct))

            acc_list.append(acc)

        acc_sum = sum(acc_list)
        print(acc_sum / float(len(acc_list)))


import os
import re
import json
from enum import Enum
from io import StringIO, TextIOWrapper
from typing import List, Optional, Tuple

from .step import StepException, ViewsUpdate, MetricsUpdate, Step
from ..common import Path
from ..logging import warn
from ..config import Variable, Config
from ..state import DesignFormat, State

class CVCNoSupport(Exception):
    pass

def power_file_for(config: Config, json_header_str: str) -> str:
    try:
        json_header = json.loads(json_header_str)
    except json.JSONDecodeError as e:
        raise StepException(f"Invalid JSON file passed to step: {e}")

    vdd_nets = config["VDD_NETS"] or [config["VDD_PIN"]]
    gnd_nets = config["GND_NETS"] or [config["GND_PIN"]]
    if len(vdd_nets) != 1 or len(gnd_nets) != 1:
        raise CVCNoSupport("more than one power or ground net")

    vdd = vdd_nets[0]
    gnd = gnd_nets[0]

    if vdd != config["VDD_PIN"] or gnd != config["GND_PIN"]:
        raise CVCNoSupport("mismatched power/gnd nets")

    sio = StringIO()
    print(f"{vdd} power {config['VDD_PIN_VOLTAGE']}", file=sio)
    print(f"{gnd} power 0.0", file=sio)
    print(f"#define std_input min@{gnd} max@{vdd}", file=sio)

    module = json_header["modules"][config["DESIGN_NAME"]]
    for port, info in module["ports"].items():
        if info["direction"] != "input":
            continue
        if port in [vdd, gnd]:
            continue

        port_string = port
        bits = len(info["bits"])
        if len(info["bits"]) != 1:
            offset = info.get("offset", 0)
            upto = info.get("upto", 0)

            msb = bits - offset - 1
            lsb = offset

            if upto == 1:
                msb, lsb = lsb, msb

            port_string = f"{port}[{msb}:{lsb}]"

        print(f"{port_string} input std_input", file=sio)

    return sio.getvalue()

def cdl_clean(istream: TextIOWrapper, ostream: TextIOWrapper):
    class State(Enum):
        printing = 0
        in_bb = 0

    state = State.printing

    bb_rx = re.compile("Black-box entry subcircuit")

    for line in istream:
        line = line.strip()
        elements = line.split()
        if state == State.printing:
            if bb_rx.search(line):
                state = State.in_bb
            elif line.startswith("*"):
                pass
            elif line.startswith(".ENDS"):
                print(".ENDS", file=ostream)
            else:
                print(line, file=ostream)
        elif state == State.in_bb:
            if elements[1] == ".ends":
                state = State.printing

class ERC(Step):
    id = "CVCRV.ERC"
    long_name = "Electrical Rule Checking (CVC-RV)"
    inputs = [
        DesignFormat.JSON_HEADER,
        DesignFormat.SPICE,
    ]
    outputs = []

    config_vars = [
        Variable(
            "CVCRC",
            Optional[Path],  # Only optional for backwards-compat
            description="The CVC RC file for this PDK. If it doesn't exist, this step will do nothing.",
            pdk=True,
        ),
        Variable(
            "CVC_MODELS",
            Optional[Path],  # Only optional for backwards-compat
            description="",
            pdk=True,
        ),
        Variable(
            "CELL_CDLS",
            List[Path],
            description="A circuit-design language view of the standard cell library.",
            pdk=True,
            deprecated_names=["STD_CELL_LIBRARY_CDL"],
        ),
    ]

    def run(self, state_in: State, **kwargs) -> Tuple[ViewsUpdate, MetricsUpdate]:
        try:
            json_header = state_in[DesignFormat.JSON_HEADER]
            assert isinstance(json_header, Path), "Invalid input state"
            json_header_str = open(str(json_header), encoding="utf8").read()

            power_file = os.path.join(
                self.step_dir, f"{self.config['DESIGN_NAME']}.power"
            )
            with open(power_file, "w", encoding="utf8") as f:
                f.write(power_file_for(self.config, json_header_str))

            cdl_file = os.path.join(self.step_dir, f"{self.config['DESIGN_NAME']}.cdl")
            with open(cdl_file, "w", encoding="utf8") as f:
                for file in self.config["CELL_CDLS"] + [state_in[DesignFormat.SPICE]]:
                    cdl_clean(open(file, encoding="utf8"), f)
            kwargs, env = self.extract_env(kwargs)

            env["DESIGN_NAME"] = self.config["DESIGN_NAME"]

            # OL1 Nonsense
            env["signoff_tmpfiles"] = self.step_dir
            env["signoff_reports"] = self.step_dir
            env["CVC_SCRIPTS_DIR"] = os.path.dirname(self.config["CVC_MODELS"])

            log_file = os.path.join(self.step_dir, "cvc.log")

            self.run_subprocess(
                ["cvc_rv", self.config["CVCRC"]], env=env, log_to=log_file, **kwargs
            )
            return {}, {}
        except CVCNoSupport as e:
            warn(f"Could not run CVC: {e}. Skipping…")
            return Step.run(self, state_in, **kwargs)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/24 16:56
# @Author : anning
# @File : demo.py
# @Software: PyCharm
from common.RequestAndAssertion import RequestAndAssertion
from common.base import base

class demo(base):

    def test_one(self):
        super().__init__()
        # 请求参数
        self.body={}
        # 请求头
        self.headers={}
        # 请求的域名或者ip
        self.host= ''
        # 请求具体地址(接口路径)
        self.resource=''
        # 需要验证长度的字段
        self.field_length={
            '''
            目前支持的字符类型：string、decimal、date。
            后续还需要支持，请到base中修改get_field_length方法。
            使用方法
                {
                "string_32":["字段a","字段b"],
                "decimal_18_2":["字段a","字段b"],
                "date_date":["字段a","字段b"],
            }

            解析：
                string_32，代表字段类型为string，长度限制为32，我们可以传string_33，验证超长后是否报错
                decimal_18_2，代码字段类型为decimal，字段长度为18，小数位占2位。测试：decimal_19_2、decimal_18_3，长度19两位小数和长度18三位小数
                date_date，代码字段类型为date，目前获取的是系统的当前日期
            '''
        }

if __name__ == '__main__':
    execute = demo()
    RequestAndAssertion().execute(execute)


#import modules
from tkinter import *
import sqlite3
import tkinter.messagebox

#connect to database
conn = sqlite3.connect('database.db')
print("Sucessfully connected ")

#cursor to move around database
c = conn.cursor()

#Empty list to later append
ids =[]

#tkinter window
class Application:
    def __init__(self, master):
        self.master = master

        #creating the frames in master
        self.left = Frame(master, width = 800, height = 720, bg = 'lightgreen')
        self.left.pack(side=LEFT)

        self.right = Frame(master, width = 400, height = 720, bg = 'darkblue')
        self.right.pack(side=RIGHT)

        #Label the window
        self.heading = Label(self.left, text="Saturn hospital Appointment's", font = ('TimesNewRoman 40 bold italic'), fg='black',bg='lightblue')
        self.heading.place(x=0, y=0)

        #Patient's details

        #Patient's Name

        self.name = Label(self.left, text="Patient's Name",  font = ('TimesNewRoman 18 bold'), fg='black',bg='lightgreen')
        self.name.place(x=0, y=100)

        #Patient's Age
        self.age = Label(self.left, text="Age",  font = ('TimesNewRoman 18 bold'), fg='black',bg='lightgreen')
        self.age.place(x=0, y=140)

        #Gender
        self.gender = Label(self.left, text="Gender",  font = ('TimesNewRoman 18 bold'), fg='black',bg='lightgreen')
        self.gender.place(x=0, y=180)

        #Address
        self.location = Label(self.left, text="Address",  font = ('TimesNewRoman 18 bold'), fg='black',bg='lightgreen')
        self.location.place(x=0, y=220)

        #appointment time
        self.time = Label(self.left, text="Apppointment time",  font = ('TimesNewRoman 18 bold'), fg='black',bg='lightgreen')
        self.time.place(x=0, y=260)

        #Creating Entries for labels

        self.name_ent = Entry(self.left, width=30)
        self.name_ent.place(x=250, y=100)

        self.age_ent = Entry(self.left, width=30)
        self.age_ent.place(x=250, y=140)

        self.gender_ent = Entry(self.left, width=30)
        self.gender_ent.place(x=250, y=180)

        self.location_ent = Entry(self.left, width=30)
        self.location_ent.place(x=250, y=220)

        self.time_ent = Entry(self.left, width=30)
        self.time_ent.place(x=250, y=260)

        #To see the number of appointment fixed in a log
        sql2 = "SELECT ID FROM appointment"
        self.result = c.execute(sql2)
        for self.row in self.result:
            self.id = self.row[0]
            ids.append(self.id)

        #ordering
        self.new = sorted(ids)
        self.final_id = self.new[len(ids)-1]

        #FOR displaying log in right frame

        self.box = Text(self.right, width=40, height=40)
        self.box.place(x=30,y=30)
        self.box.insert(END, "Total appointment till now: " + str(self.final_id) )

        #function to call when add appointment button is clicked

        def add_appointment():
            #getting the user input
            self.val1 = self.name_ent.get()
            self.val2 = self.age_ent.get()
            self.val3 = self.gender_ent.get()
            self.val4 = self.location_ent.get()
            self.val5 = self.time_ent.get()

            #To alert user to fill all the details
            if self.val1 == "" or  self.val2 == "" or self.val3 == "" or self.val4 == "" or self.val5 == "" :
                tkinter.messagebox.showinfo("Warning","Please Fill all the details")
            else:
                #Now we add into database
                sql = "INSERT INTO 'appointment' (name, age, gender, location, Schedule_time) VALUES(?,?,?,?,?)"
                c.execute(sql,(self.val1,self.val2,self.val3,self.val4,self.val5))
                conn.commit()
                tkinter.messagebox.showinfo("Success","Appointment for " +str(self.val1) + " has been created")

                self.box.insert(END, ' Appointment Fixed for ' + str(self.val1) + ' at ' + str(self.val5))

        #Creating submit button
        self.submit = Button(self.left, text= 'Add appointment', width=20, height=2, bg='steelblue', command= add_appointment)
        self.submit.place(x=300, y=300)

#creating object
root =Tk()
b = Application(root)

#resolution of the window
root.geometry("1200x700+0+0")


from django import forms
from django.forms.widgets import NumberInput

class CartAddProductForm(forms.Form):
    quantity = forms.IntegerField(min_value=1, initial=1, widget=NumberInput(
        attrs={
            "style": "width:43px; text-align:center; margin-top:15px; border: 1px solid; margin-bottom: 25px;"
            # "class": "form-control"

        }
    ))
    update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)


from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from ConnPSI import *
import matplotlib.pyplot as plt

class Grafica(Frame):
    def __init__(self, master,*args):
        super().__init__(master,*args)
        self.dbpsi = BasePsico()
        self.create_widgets()

    def create_widgets(self):
        self.fig, self.ax = plt.subplots(dpi=80,figsize=(7,5),facecolor='black')
        plt.title("Grafica",color='#00ff00',size=16, family="Arial")
        self.ax.axhline(linewidth=2,color='r')
        self.ax.axvline(linewidth=2,color='r')
        self.ax.set_xlabel("DECATIPOS", color='#00ff00')
        self.ax.set_ylabel("ESCALAS", color='#00ff00')
        self.ax.tick_params(direction='out',length=6, width=2,colors='#00ff00',grid_color='black',grid_alpha=1)

        self.frame1 = Frame(self.master,bg='red')
        self.frame1.grid(column=0,row=0,sticky='nsew')

        self.frame2 = Frame(self.master,bg='black')
        self.frame2.grid(column=1,row=0,sticky='nsew')

        self.frame3= Frame(self.master,bg='black')
        self.frame2.grid(column=2,row=0,sticky='nsew')

        self.canvas=FigureCanvasTkAgg(self.fig, master=self.frame3)
        self.canvas.get_tk_widget().pack(expand=True)

        self.canvas=FigureCanvasTkAgg(self.fig, master=self.frame1)
        self.canvas.get_tk_widget().pack(expand=True)
        Label(self.frame2, text='lectura',bg='green',fg='blue',font='verdana').pack(expand=True)
        Entry
        Button(self.frame2,text='obtenerdatos',bg='magenta',command=self.obtener_datos).pack(expand=True)
        Button(self.frame2,text='Graficar datos',bg='magenta',command=self.graficar_datos).pack(expand=True)

    def obtener_datos(self):

        self.sql=("SELECT escalas,dp FROM universitario_has_test INNER JOIN test on idtest=test_idtest where universitario_iduniversitario = 1")
        self.dbpsi.cursor.execute(self.sql)
        self.datos=self.dbpsi.cursor.fetchall()
    def graficar_datos(self):
        x=[]
        n=[]
        for i in self.datos:
            a= i[0]
            b= i[1]
            n.append(a)
            x.append(b)
            #print(a,b)
        self.ax.plot(n,x,color='b', linestyle='solid')
        self.canvas.draw()
        plt.grid(alpha=0.5)

if __name__ == "__main__":
    ventana=Tk()
    ventana.geometry('1000x600')
    ventana.resizable(0,0)
    ventana.config(bg='black')

    ventana.wm_title('Grafica')
    app = Grafica(ventana)
    app.mainloop()
print(__name__)

"""
def btn_clicked():
    print("Button Clicked")

window = Tk()

window.geometry("1000x700")
window.configure(bg="#ffffff")
canvas = Canvas(
    window,
    bg="#ffffff",
    height=700,
    width=1000,
    bd=0,
    highlightthickness=0,
    relief="ridge")
canvas.place(x=0, y=0)

entry0_img = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img_textBox0.png")
entry0_bg = canvas.create_image(
    325.5, 168.0,
    image=entry0_img)

entry0 = Entry(
    bd=0,
    bg="#d9d9d9",
    highlightthickness=0)

entry0.place(
    x=198, y=152,
    width=255,
    height=30)

entry1_img = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img_textBox1.png")
entry1_bg = canvas.create_image(
    325.5, 256.0,
    image=entry1_img)

entry1 = Entry(
    bd=0,
    bg="#d9d9d9",
    highlightthickness=0)

entry1.place(
    x=198, y=240,
    width=255,
    height=30)

entry2_img = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img_textBox2.png")
entry2_bg = canvas.create_image(
    325.5, 300.0,
    image=entry2_img)

entry2 = Entry(
    bd=0,
    bg="#d9d9d9",
    highlightthickness=0)

entry2.place(
    x=198, y=284,
    width=255,
    height=30)

entry3_img = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img_textBox3.png")
entry3_bg = canvas.create_image(
    325.5, 212.0,
    image=entry3_img)

entry3 = Entry(
    bd=0,
    bg="#d9d9d9",
    highlightthickness=0)

entry3.place(
    x=198, y=196,
    width=255,
    height=30)

img0 = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img0.png")
b0 = Button(
    image=img0,
    borderwidth=0,
    highlightthickness=0,
    command=btn_clicked,
    relief="flat")

b0.place(
    x=500, y=151,
    width=149,
    height=33)

entry4_img = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img_textBox4.png")
entry4_bg = canvas.create_image(
    496.0, 496.5,
    image=entry4_img)

entry4 = Entry(
    bd=0,
    bg="#d9d9d9",
    highlightthickness=0)

entry4.place(
    x=75, y=350,
    width=842,
    height=291)

img1 = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//img1.png")
b1 = Button(
    image=img1,
    borderwidth=0,
    highlightthickness=0,
    command=btn_clicked,
    relief="flat")

b1.place(
    x=500, y=198,
    width=149,
    height=34)

background_img = PhotoImage(
    file=f"C://Users//Rummy//Desktop//PRUEBA AGENTE//prueba_env//PANTALLA EVPSI//background.png")
background = canvas.create_image(
    605.5, 109.0,
    image=background_img)

marco = LabelFrame(window, text="agente evaluador psi")
marco.place(x=75, y=350,
            width=842,
            height=291)

Academicotv = ttk.Treeview(marco)
Academicotv.grid(column=0, row=2, columnspan=4)
Academicotv["columns"] = (
    "IDUNIVERSITARIO", "NOMBRE", "APELLIDO PATERNO", "APELLIDO MATERNO", "NOMCARRERA", "NUMPREGUNTA", "AUTOCALIFICACION")
Academicotv.column("#0", width=0, stretch=NO)
Academicotv.column("IDUNIVERSITARIO", width=50, anchor=CENTER)
Academicotv.column("NOMBRE", width=100, anchor=CENTER)
Academicotv.column("APELLIDO PATERNO", width=150, anchor=CENTER)
Academicotv.column("APELLIDO MATERNO", width=150, anchor=CENTER)
Academicotv.column("NOMCARRERA", width=150, anchor=CENTER)
Academicotv.column("NUMPREGUNTA", width=150, anchor=CENTER)
Academicotv.column("AUTOCALIFICACION", width=100, anchor=CENTER)

Academicotv.heading("#0", text="")
Academicotv.heading("IDUNIVERSITARIO", text="IDUNIVERSITARIO", anchor=CENTER)
Academicotv.heading("NOMBRE", text="NOMBRE", anchor=CENTER)
Academicotv.heading("APELLIDO PATERNO", text="APELLIDO PATERNO", anchor=CENTER)
Academicotv.heading("APELLIDO MATERNO", text="APELLIDO MATERNO", anchor=CENTER)
Academicotv.heading("NOMCARRERA", text="NOMCARRERA", anchor=CENTER)
Academicotv.heading("NUMPREGUNTA", text="NUMPREGUNTA", anchor=CENTER)
Academicotv.heading("AUTOCALIFICACION", text="AUTOCALIFICACION", anchor=CENTER)

def vaciar_tabla():
    filas = Academicotv.get_children()
    for fila in filas:
        Academicotv.delete(fila)

def llenar_tabla():
    vaciar_tabla()
    sql = "SELECT test_idtest,iduniversitario,nomuni,appatuni,apmatuni,nomcarrera,autocalificacion FROM universitario_has_test inner join universitario on idUniversitario = universitario_iduniversitario inner join carrera on carrera_idcarrera=idcarrera "
    #sql= "SELECT * FROM psicouni.universitario;"
    dbpsi.cursor.execute(sql)
    filas = dbpsi.cursor.fetchall()
    for fila in filas:
        id = fila[0]
        Academicotv.insert("",END,id, text=id,values=fila)

llenar_tabla()
window.resizable(False, False)
window.mainloop()

"""


import pygame

class Backgroundblock:
    """A class to represent a single block in the sky"""

    def __init__(self, ai_game):
        """Initialize the block and set its starting position"""
        super().__init__()
        self.screen = ai_game.screen
        self.settings = ai_game.settings

        # Load the block image and set its rect attribute.
        self.image = pygame.image.load('images/grayblock.png')
        self.rect = self.image.get_rect()

        # Start each new block near the top left corner of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        # Store the block's exact  horizontal position
        self.x = float(self.rect.x)

    def check_edges(self):
        """Return True if block is at edge of screen"""
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right or self.rect.left <= 0:
            return True


# - [ML_master.py](file:///C:/Local/Work/ML_Name/Code/Test/ML_master.py)

 # - [ML_Amazon_product_adviser_chat_bot.md](file:///C:/Local/Work/ML_Name/Note/ML_Amazon_product/ML_Amazon_product_adviser_chat_bot.md)

# https://github.com/Jcharis/Streamlit_DataScience_Apps/tree/master/NLP_App_with_Streamlit_Python

# !------------------------------------------------------------------------->
#  Synopsis :
#     Master doc to Running the streamlit based web UI
#  Documentation :
#     ML_Amazon_product_adviser_chat_bot.md
# !------------------------------------------------------------------------->

"""
# App: NLP App with Streamlit (NLPiffy)
Author: [Jesse E.Agbe(JCharis)](https://github.com/Jcharis))\n
Source: [Github](https://github.com/Jcharis/Streamlit_DataScience_Apps/)
Credits: Streamlit Team,Marc Skov Madsen(For Awesome-streamlit gallery)
Description
This is a Natural Language Processing(NLP) Based App useful for basic NLP concepts such as follows;
+ Tokenization & Lemmatization using Spacy
+ Named Entity Recognition(NER) using SpaCy
+ Sentiment Analysis using TextBlob
+ Document/Text Summarization using Gensim/Sumy
This is built with Streamlit Framework, an awesome framework for building ML and NLP tools.
Purpose
To perform basic and useful NLP task with Streamlit,Spacy,Textblob and Gensim/Sumy
"""
# Core Pkgs

from PIL import Image
import streamlit as st
import os

# NLP Pkgs
from textblob import TextBlob
import spacy
from gensim.summarization import summarize

# Sumy Summary Pkg
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer

import name_nationality as nn
import name_entity_reco as ner
import ML_amazon_best_seller as best_seller
from newspaper import Article
import urllib.request
import itertools as it
import sys
import collections
import numpy as np

from bs4 import BeautifulSoup
import requests
import re
import nltk
import spacy
import streamlit as st
# NLP Pkgs

# Sumy Summary Pkg

# Function for Sumy Summarization
def sumy_summarizer(docx):
    parser = PlaintextParser.from_string(docx, Tokenizer("english"))
    lex_summarizer = LexRankSummarizer()
    summary = lex_summarizer(parser.document, 3)
    summary_list = [str(sentence) for sentence in summary]
    result = ' '.join(summary_list)
    return result

# Function to Analyse Tokens and Lemma

@st.cache
def text_analyzer(my_text):
    nlp = spacy.load('en')
    docx = nlp(my_text)
    # tokens = [ token.text for token in docx]
    allData = [('"Token":{},\n"Lemma":{}'.format(
        token.text, token.lemma_))for token in docx]
    return allData

# Function For Extracting Entities

@st.cache
def entity_analyzer(my_text):
    nlp = spacy.load('en')
    docx = nlp(my_text)
    tokens = [token.text for token in docx]
    entities = [(entity.text, entity.label_)for entity in docx.ents]
    allData = ['"Token":{},\n"Entities":{}'.format(tokens, entities)]
    return allData

# C:\Local\Work\Web\Note\nlp-word-cloud.jpg

@st.cache
def name_nationality(my_text):
    return(0)

def main():
    """ NLP Based App with Streamlit """
    # see  ML_Master.md
    # Title
    st.title("Jian's work ")

    # sidbar title image
    image = Image.open('C:/Local/Work/ML_Name/Code/Lib/my_nlp-word-cloud.jpg')
    st.sidebar.image(image, caption='NLP Cloud',
                     use_column_width=True)
    st.sidebar.subheader("Natural Language Processing On the Go..")
    st.markdown("""
    	# Description
    	+ This is a Natural Language Processing(NLP) Based App useful for basic NLP task
    	Tokenization,NER,Sentiment,Summarization : See
    	""")

    # Name Nationality
    if st.sidebar.checkbox("Name Nationality Recongition"):
        st.subheader("Enter your names, seperated by , ")
        message = st.text_area("Enter Name", "Type Here ..")
        if st.button("Analyze"):
            nlp_name = nn.name_nationality(message)
            st.json(nlp_name)

    # Name entity recognition
    if st.sidebar.checkbox("Name Entity Recongition"):
        st.subheader("Enter your website ")
        message = st.text_area(
            "Input:  article web link;\n  Output : person's names in article\n Highlight the person's name in the article\n Example : https://finance.yahoo.com/news/why-us-china-relations-are-worsening-on-almost-every-front-213714768.html")
        if st.button("Analyze"):
            nlp_text = ner.Get_html_text(message)
            #nlp_text = nlp_text.replace("University ", "**University** ")
            (nlp_text, person_name_all) = ner.get_person_name(nlp_text)
            st.write(person_name_all)
            st.markdown(nlp_text)

    # Amazon Best seller
    # Give a search lis
    if st.sidebar.checkbox("Amazon best seller list "):
                st.subheader("Enter your product search item ")
                message = st.text_area("Enter Name", "Type Here ..")
                if st.button("Analyze"):
                    best_seller.ML_amazon_best_seller(message)
                    #st.json(nlp_name)

    # give a product ID : download Amazon Product Information
    # see  ML_Master.md
    import bs_lib
    if st.sidebar.checkbox("Amazon Product"):
        st.subheader("Enter your product ID ")
        message = st.text_area(
            "ID: eg. B079K4TVPG")
        if st.button("Analyze"):
            amazon_product_dict = bs_lib.get_amazon_product_info(message)
            st.write(amazon_product_dict)

    #
    st.sidebar.subheader("About App")
    st.sidebar.text("NLP with Streamlit")
    st.sidebar.info("Cudos to the Streamlit Team")

    st.sidebar.subheader("By")
    st.sidebar.text("Jian Tang")

if __name__ == '__main__':
    main()


import sys
from time import gmtime, strftime
import service
import unittest
import logging
import os
from datetime import datetime
from dateutil.relativedelta import relativedelta

UNITTEST_CALENDAR = 'unittest-calendar'
SERVER = 'http://localhost:5984'

class GCalendarTest(unittest.TestCase):
  def setUp(self):
    self.calendarListFd = service.GCalendarList()
    self.calendarFd = service.GCalendar(UNITTEST_CALENDAR)
    self.assertTrue(self.calendarListFd.exists(UNITTEST_CALENDAR))

  '''
  def tearDown(self):
    self.calendarListFd.delete(UNITTEST_CALENDAR)
    self.assertFalse(self.calendarListFd.exists(UNITTEST_CALENDAR))
    pass
  '''

  def test_existing_calendar(self):
    self.assertIsNotNone(service.GCalendarList().exists("Menu"))

  def test_create_event(self):
    all_day_event = {
      'summary': 'New Appointment',
      'location': 'Somewhere',
      'start': {
        'date': strftime("%Y-%m-%d", gmtime())
        #'dateTime': strftime("%Y-%m-%d %H:%M:%S", gmtime())
      },
      'end': {
        'date': strftime("%Y-%m-%d", gmtime())
        #'dateTime': strftime("%Y-%m-%d %H:%M:%S", gmtime())
      },
      'attendees': [
        {
          'email': 'raymund.rimando@gmail.com',
        }
      ]
    }
    event = {
      'summary': 'New Appointment',
      'location': 'Somewhere',
      'start': {
        'dateTime': strftime("%Y-%m-%d %H:%M:%S", gmtime())
      },
      'end': {
        'dateTime': strftime("%Y-%m-%d %H:%M:%S", gmtime())
      },
      'attendees': [
        {
          'email': 'raymund.rimando@gmail.com',
        }
      ]
    }

    self.calendarFd.insert_event(all_day_event)
    #eventFd = service.GEvents()
    self.assertTrue(True)

class ShoppingListCreator(unittest.TestCase):
  def test_create_shopping_list_from_calendar(self):
    self.assertIsNotNone({})

if __name__ == '__main__':
  logging.basicConfig(filename='%s/test.log' % os.environ['LOG_DIR'], level=logging.DEBUG)
  sys.exit(unittest.main())


# nb: discord has more than this, but I'm only filling out as much in these structs as i'm using.
from __future__ import annotations

from typing import Any, List, Literal, Never, Optional, Union
import msgspec

from enum import IntEnum

# Interactions.
class InteractionType(IntEnum):
    PING = 1
    APPLICATION_COMMAND = 2

class BaseInteraction(msgspec.Struct, kw_only=True, tag_field="type"):
    id: str

class PingInteraction(BaseInteraction, tag=InteractionType.PING.value):
    pass

class ApplicationCommandInteraction(BaseInteraction, tag=InteractionType.APPLICATION_COMMAND.value):
    guild_id: str  # we don't support DMs. So this will always be a value.
    data: Union[ChatInputApplicationCommandData, MessageApplicationCommandData]

AnyInteraction = Union[PingInteraction, ApplicationCommandInteraction]

class ApplicationCommandType(IntEnum):
    CHAT_INPUT = 1
    # USER = 2  (not used)
    MESSAGE = 3

class BaseApplicationCommandData(msgspec.Struct, kw_only=True, tag_field="type"):
    id: str
    name: str

class ChatInputApplicationCommandData(BaseApplicationCommandData, tag=ApplicationCommandType.CHAT_INPUT.value):
    pass

class MessageApplicationCommandData(BaseApplicationCommandData, tag=ApplicationCommandType.MESSAGE.value):
    target_id: str
    resolved: Optional[Resolved] = None

class DiscordMessage(msgspec.Struct):
    id: str
    channel_id: str
    attachments: List[DiscordAttachment]

class DiscordAttachment(msgspec.Struct, kw_only=True):
    id: str
    filename: str
    content_type: Optional[str] = None
    size: int
    url: str
    proxy_url: str

class Resolved(msgspec.Struct):
    messages: Optional[dict[str, DiscordMessage]] = None

class InteractionCallbackType(IntEnum):
    PONG = 1
    CHANNEL_MESSAGE_WITH_SOURCE = 4

class InteractionResponse(msgspec.Struct, kw_only=True, tag_field="type"):
    data: Optional[Any]

class PongInteractionResponse(InteractionResponse, tag=InteractionCallbackType.PONG.value):
    data: None = None

NOT_EPHEMERAL = 0
EPHEMERAL = 1 << 6

class InteractionMessage(msgspec.Struct):
    content: str
    flags: int

class MessageInteractionResponse(InteractionResponse, tag=InteractionCallbackType.CHANNEL_MESSAGE_WITH_SOURCE.value):
    data: InteractionMessage

class ApplicationCommandType(IntEnum):
    CHAT_INPUT = 1
    USER = 2
    MESSAGE = 3

class ApplicationCommand(msgspec.Struct):
    name: str
    description: Optional[str] = None
    type: ApplicationCommandType = ApplicationCommandType.CHAT_INPUT
    default_member_permissions: str = "0"
    dm_permission: bool = False


import numpy as np
from PIL import Image
from flask_mail import Message
from .main import mail

def preprocess_image(image_file):
    image = Image.open(image_file)
    image = image.resize((224, 224))  # Resize the image to 224x224
    image = image.convert('RGB')  # Convert the image to RGB format
    return np.array(image) / 255.0  # Normalize pixel values

def send_email(to, subject, template):
    msg = Message(
        subject,
        recipients=[to],
        html=template,
        sender=('Your Name', 'your@email.com')
    )
    mail.send(msg)


from django.urls import path

from shop.views import (ShopView,
                        ProductSingleView,
                        CartView,
                        CheckoutView,
                        PaymentView,
                        add_to_cart,
                        add_one_to_cart,
                        remove_one_from_cart,
                        remove_from_cart)
app_name = 'shop'

urlpatterns = [
    path('<category>/', ShopView.as_view(), name='shop'),
    path('product-single/<slug>/', ProductSingleView.as_view(), name='product_single'),
    path('cart', CartView.as_view(), name='cart'),
    path('add-to-cart/<slug>/', add_to_cart, name='add-to-cart'),
    path('remove-from-cart/<slug>/', remove_from_cart, name='remove-from-cart'),
    path('add-one-to-cart/<slug>/', add_one_to_cart, name='add-one-to-cart'),
    path('remove-one-from-cart/<slug>/', remove_one_from_cart, name='remove-one-from-cart'),
    path('checkout', CheckoutView.as_view(), name='checkout'),
    path('payment', PaymentView.as_view(), name='payment'),
]


import cv2
import os

def batch_extract_frames(input_directory, output_directory):
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    video_extensions = ['.mp4', '.avi', '.mov']

    for filename in os.listdir(input_directory):
        if any(filename.lower().endswith(ext) for ext in video_extensions):
            video_path = os.path.join(input_directory, filename)
            capture = cv2.VideoCapture(video_path)

            frame_count = 0
            while True:
                ret, frame = capture.read()
                if not ret:
                    break

                frame_filename = os.path.join(output_directory, f"{os.path.splitext(filename)[0]}_{frame_count:04d}.jpg")
                cv2.imwrite(frame_filename, frame)

                frame_count += 1

            capture.release()
            print(f"视频 {filename} 解帧完成，共保存 {frame_count} 帧图片。")

if __name__ == "__main__":
    input_dir = input("请输入包含视频文件的文件夹路径：")
    output_dir = input("请输入保存解帧图片的文件夹路径：")

    batch_extract_frames(input_dir, output_dir)