"""
Damit die Daten eingelesen werden kÃ¶nnen:
Bitte speichern Sie den Ordner "opti", welcher alle Daten inkludiert, am selben Ort, an dem die Pythondatei abgespeichert ist.
Der opti Ordner muss die Unterordner "Mo_Ferien", "Mo_Schule", "Samstag" und "Sonntag" besitzen.
In den jeweiligen Ordnern mÃ¼ssen eine timetable.txt, timetable-blocks.txt und eine timetable-duties.txt Datei hinterlegt sein.

"""

#Sprint5.1

# Ã¼berall kleine Fehler im Output (Daten Schuld? DatenqualitÃ¤t Ã¼berprÃ¼fen)

# Bei DurchfÃ¼hrung Error in den Daten ausgefallen:
#   Bei VehID 9, 77, 63 sind die TeilumlÃ¤ufe nicht in korrekter Reihenfolge
#   Idee: Zeiten aufsteigend sortieren bei Transformieren

#######To-Dos########
## Prio 2: Mehrere Tage simulieren
## Prio 2: GUI optisch und inhaltlich verbessern (mehrere Dateien als AuswahlmÃ¶glichkeit)
    ## Prio 1: Stau einfÃ¼gen --> Erster Aufschlag implementiert
## Prio 1: Mehr und validere VerspÃ¤tungsarten
## Prio 1: ModularitÃ¤t ausbauen
    ## Prio 1: Dem Output die VerspÃ¤tungsart hinzufÃ¼gen --> Erster Aufschlag implementiert
    ## Prio 2: Einleseroutine hinzufÃ¼gen --> Done
## Prio 3: Dateninkonsistenzen beseitigen
## Prio 2: KPIs
## Prio 1: VerspÃ¤tungen in relative Werte wandeln (und runden)
## Prio 1: Pausenzeiten nutzen oder nicht?

## Zu klÃ¤ren:
## Statt mit absoluten VerspÃ¤tungen lieber mit relativen VerspÃ¤tungen arbeiten?
## Warum gibt es eine Haltestelle 244?

####################### Import Packages ###################################
import simpy
import pandas as pd
import numpy
from random import randint
from tkinter import *
import sys, datetime as dt
from io import StringIO

### GUI ###
root = Tk()
root.geometry("400x500")
l1 = Label(root,text='Berufsverkehr',background='grey', font = "Times")
var1 = IntVar()
c1 = Checkbutton(root, text='An diesem Tag gibt es Berufsverkehr.', variable=var1)
l2 = Label(root,text='Wetter',background='grey', font = "Times")
var2 = IntVar()
c2 = Checkbutton(root, text='An diesem Tag gibt es Gewitter.', variable=var2)
var3 = IntVar()
c3 = Checkbutton(root, text='An diesem Tag regnet es.', variable=var3)
var4 = IntVar()
c4 = Checkbutton(root, text='An diesem Tag scheint die Sonne.', variable=var4)
l3 = Label(root,text='Tag, der simuliert wird',background='grey', font = "Times")
var5 = IntVar()
c5 = Checkbutton(root, text='Wochentag - Keine Ferien', variable=var5)
var6 = IntVar()
c6 = Checkbutton(root, text='Wochentag - Ferien', variable=var6)
var7 = IntVar()
c7 = Checkbutton(root, text='Samstag', variable=var7)
var8 = IntVar()
c8 = Checkbutton(root, text='Sonntag', variable=var8)
button = Button(text = "BestÃ¤tigen", bg = "green", font = "Times", command = root.destroy)

l3.pack(fill=X, padx='20', pady='5')
c6.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
c7.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
c8.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
c5.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
l1.pack(fill=X, padx='20', pady='5')
c1.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
l2.pack(fill=X, padx='20', pady='5')
c2.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
c3.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
c4.pack(side='top', fill='x', padx='5', pady='5', anchor = "w")
button.pack(side='bottom', fill='y', padx='5',pady='10')

mainloop()

###Routine zum Auslesen der Textdateien
def load_table_data(fullfilepath):

    ### Read file
    tab_dict = {}
    with open(fullfilepath) as in_file:

    	### Iterate over rows

        while True:
            try:
                curr_row = in_file.readline()
            except IOError as e:
                sys.exit(1)

            if curr_row == '':      break    ### Empty (last) row found
            if curr_row[0] == '*':  continue ### Comment found
            if curr_row[0] == '$':           ### New table found
                split_list = curr_row.split(':')
                curr_row = split_list[1]
                tab_dict[split_list[0]] = ''

            ### Append current row to table string
            tab_dict[split_list[0]] = tab_dict[split_list[0]] + curr_row
        in_file.close()

    ### Create dict of pd.DataFrames
    tab_df_dict = {}
    for name, t in tab_dict.items():
        tab_df_dict[name] = (pd.read_csv(StringIO(t), sep=';'))
    return tab_df_dict

Weekday_No_Vacation = var5.get()
Weekday_Vacation = var6.get()
Saturday = var7.get()
Sunday = var8.get()

def dayChoice(Weekday_No_Vacation, Weekday_Vacation, Saturday, Sunday):
    if Weekday_No_Vacation == 1:
        data = load_table_data('opti/Mo_Schule/timetable.txt')
        blockdata = load_table_data('opti/Mo_Schule/timetable-blocks.txt')
        dutydata = load_table_data('opti/Mo_Schule/timetable-duties.txt')
        return(data, dutydata, blockdata)
    elif Weekday_Vacation == 1:
        data = load_table_data('opti/Mo_Ferien/timetable.txt')
        blockdata = load_table_data('opti/Mo_Ferien/timetable-blocks.txt')
        dutydata = load_table_data('opti/Mo_Ferien/timetable-duties.txt')
        return(data, dutydata, blockdata)
    elif Saturday == 1:
        data = load_table_data('opti/Samstag/timetable.txt')
        blockdata = load_table_data('opti/Samstag/timetable-blocks.txt')
        dutydata = load_table_data('opti/Samstag/timetable-duties.txt')
        return(data, dutydata, blockdata)
    elif Sunday == 1:
        data = load_table_data('opti/Sonntag/timetable.txt')
        blockdata = load_table_data('opti/Sonntag/timetable-blocks.txt')
        dutydata = load_table_data('opti/Sonntag/timetable-duties.txt')
        return(data, dutydata, blockdata)

data, dutydata, blockdata = dayChoice(Weekday_No_Vacation, Weekday_Vacation, Saturday, Sunday)

#relevante Dataframes extrahieren
servicefahrten = data["$SERVICEJOURNEY"]
dutyelements = dutydata["$DUTYELEMENT"]
blocks = blockdata["$BLOCK"]
blockelements = blockdata["$BLOCKELEMENT"]
dutytype = dutydata["$DUTY"]

allBlocks = blockelements
tableFinal = dutyelements
allLines = servicefahrten

tableFinal = tableFinal.drop(['ServiceJourneyCode', 'TransferType', 'GroupTransferIndex', 'DeadRunTransferBlockID', 'DeadRunTransferDutyID'], axis=1)
LineID = []

count_rows_duty = dutyelements.shape[0]
count_rows_dutytype = dutytype.shape[0]
count_rows_service = servicefahrten.shape[0]
count_blocks = blocks.shape[0]

for x in range(count_rows_duty):
    for y in range(count_rows_service):
        if tableFinal.iat[x,2] == allLines.iat[y,0]:
            LineID.append(allLines.iat[y,1])
    if tableFinal.iat[x,2] == -1:
            LineID.append(0)

VehTypeID = []
DepotID = []
for x in range(count_rows_duty):
    if tableFinal.iat[x,1] == -1:
        VehTypeID.append(tableFinal.iat[(x+1),1])
        DepotID.append(tableFinal.iat[x,4])
    else:
        for y in range(count_blocks):
            if tableFinal.iat[x,1] == blocks.iat[y,0]:
                VehTypeID.append(blocks.iat[y,1])
                DepotID.append(blocks.iat[y,2])

###Routine zum HinzufÃ¼gen des Duty Typs
df_dutytype = []
for x in range(count_rows_duty):
    for y in range(count_rows_dutytype):
        if tableFinal.iat[x,0] == dutytype.iat[y,0]:
            df_dutytype.append(dutytype.iat[y,1])

tableFinal["DutyType"] = df_dutytype
tableFinal["DepotID"] = DepotID
tableFinal["VehTypeID"] = VehTypeID
tableFinal["LineID"] = LineID

df = tableFinal
###export_csv = tableFinal.to_csv(r'TESTtableFinal.csv', index=None, header=True)

####################### Daten einlesen ####################################

#df = pd.read_csv("tableFinal.csv", sep=";")
####################### Daten transformieren und neue Zeitspalten in Dataframe einfÃ¼gen (Zeit) ########################
# Umrechnung der Start- & Endzeit in Minuten (fÃ¼r Simulationsuhr)
StartTime = []
count_row = df.shape[0]
for x in range(0, count_row):
    min_time = df.iloc[x, 5].split(":")
    minutes = int(min_time[1]) * 60
    minutes = minutes + int(min_time[2])
    StartTime.append(minutes)
EndTime = []
count_row = df.shape[0]
for x in range(0, count_row):
    min_time = df.iloc[x, 6].split(":")
    minutes = int(min_time[1]) * 60
    minutes = minutes + int(min_time[2])
    EndTime.append(minutes)
df["EndTime"] = EndTime
df["StartTime"] = StartTime

################################ Daten fÃ¼r Simulation erzeugen ##################################
# Gesamtanzahl an Fahrzeugen ermitteln
numberVeh = df["BlockID"].unique()
numberVeh = numberVeh.tolist()  # von Array in Liste formatieren
numberVeh = [elem for elem in numberVeh if elem >= 0]  # -1 entfernen
print("Die Gesamtanzahl von Fahrzeugen betrÃ¤gt %d." % len(numberVeh))

# DepotID (jedem Fahrzeug die unique DepotID zuordnen)
DepotID = []
counter = 1
for i in range(1, len(numberVeh) + 1):
    for j in range(0, df.shape[0]):
        if df.BlockID[j] == i and counter == i:
            DepotID.append(df.DepotID[j])
            counter += 1
print("Es gibt %d verschiedene Depots." %(len(set(DepotID))))
print("Jedes Fahrzeug wurde einem Depot zugeordnet: %s." % (
        len(DepotID) == len(numberVeh)))

# StartTimes der einzelnen Fahrzeuge in jedem Teilumlauf (in Dictionary gespeichert)
DepotID_plusOne = [0] + DepotID  # DepotIDListe verlÃ¤ngern, damit Schleife mit i funktioniert
startTime_dic = {}
for i in range(1, len(numberVeh) + 1):
    startTimes_Block = []
    for j in range(len(df)):
        if df.BlockID[j] == i:
            if df.FromStopID[j] == DepotID_plusOne[i]:
                startTimes_Block.append(df.StartTime[j])
    startTimes_Block = startTimes_Block + [
        1440]  # Add to every list a 1440 as last element for simulation loop (timeout)
    startTime_dic.update(
        {(i - 1): startTimes_Block})  # i-1 damit Index bei 0 anfÃ¤ngt (wichtig fÃ¼r Schleife (nachtrÃ¤gliche Ãnderung!)

StartTime_dic = startTime_dic

numTU_proF = []
for i in range(0,len(numberVeh)):
    numTU_proF.append(len(StartTime_dic[i])-1)
print("Die Fahrzeuge fahren im Schnitt %d TeilumlÃ¤ufe am Tag."
      " Das Maximum ist %d und das Minimum %d." % (sum(numTU_proF)/len(numTU_proF), max(numTU_proF), min(numTU_proF)))

# Listen von Haltestellen (from/to) (Liste mit vielen Listen)
FromStopID = []
ToStopID = []
for i in range(1, len(numberVeh) + 1):
    fromStopID_cache = []
    toStopID_cache = []
    for j in range(0, df.shape[0]):
        if df.BlockID[j] == i:
            fromStopID_one = df.FromStopID
            fromStopID_cache.append(fromStopID_one)
            toStopID_one = df.ToStopID
            toStopID_cache.append(toStopID_one)
    FromStopID.append(fromStopID_cache)
    ToStopID.append(toStopID_cache)

############ab hier Dictionaries erstellen #####################

DriveDuration_dic = {}
FromHS_dic = {}
ToHS_dic = {}
PartStartTime_dic = {}
PartEndTime_dic = {}
ElementID_dic = {}

for i in range(1, len(numberVeh) + 1):
    DifTime = []
    PartDif = []

    FromHS = []
    PartFromHS = []

    ToHS = []
    PartToHS = []

    StartTime = []
    PartStartTime = []

    EndTime = []
    PartEndTime = []

    Umlauf = []
    Teilumlauf = []

    for j in range(0, count_row):
        if df.BlockID[j] == i:

            difTime = df.EndTime[j] - df.StartTime[j]
            fromhs = df.FromStopID[j]
            tohs = df.ToStopID[j]
            stTime = df.StartTime[j]
            eTime = df.EndTime[j]
            elementID = df.ElementType[j]

            if df.ToStopID[j] == DepotID[i - 1]:
                PartDif.append(difTime)
                DifTime.append(PartDif)
                PartDif = []

                PartFromHS.append(fromhs)
                FromHS.append(PartFromHS)
                PartFromHS = []

                PartToHS.append(tohs)
                ToHS.append(PartToHS)
                PartToHS = []

                PartStartTime.append(stTime)
                StartTime.append(PartStartTime)
                PartStartTime = []

                PartEndTime.append(eTime)
                EndTime.append(PartEndTime)
                PartEndTime = []

                Teilumlauf.append(elementID)
                Umlauf.append(Teilumlauf)
                Teilumlauf = []

            else:
                PartDif.append(difTime)
                PartFromHS.append(fromhs)
                PartToHS.append(tohs)
                PartStartTime.append(stTime)
                PartEndTime.append(eTime)
                Teilumlauf.append(elementID)

    DriveDuration_dic.update({i - 1: DifTime})
    FromHS_dic.update({i - 1: FromHS})
    ToHS_dic.update({i - 1: ToHS})
    PartStartTime_dic.update({i - 1: StartTime})
    PartEndTime_dic.update({i - 1: EndTime})
    ElementID_dic.update({i - 1: Umlauf})

    ###################Art des Journeys#############################
Journey_dic = {}

for i in range(1,len(numberVeh) + 1):
    Umlauf = []
    Teilumlauf = []

    for j in range(0, count_row):
        if df.BlockID[j] == i:
            journey = df.iloc[j, 7]

            if df.ToStopID[j] == DepotID[i-1]:
                Teilumlauf.append(journey)
                Umlauf.append(Teilumlauf)
                Teilumlauf = []

            else:
                Teilumlauf.append(journey)

    Journey_dic.update({i-1: Umlauf})

###########Funktion um random Haltestellen auszusuchen, an denen Stau entsteht############
##Berechnet Anzahl Haltestellen
numberHS = 0
for i in range(0, count_row):
    if df.FromStopID[i] > numberHS:
        numberHS = df.FromStopID[i]

##Berechnet, welche Haltestellen am meisten frequentiert sind
HScount = []
for j in range(0, numberHS):
    count = 0
    for i in range(0, count_row):
        if df.FromStopID[i] == j:
            count += 1
    HScount.append(count)

##fÃ¼r die Annahme, dass ein Stau eher im Zentrum ist (Annahme, dass Zentrum dort ist, wo eine Haltestelle stark befahren wird)
cumulativeHS = []
cumulative = 0
for j in range(0, len(HScount)):
    cumulative += HScount[j]
    cumulativeHS.append(cumulative)

##Random mit gewichteter Wahrscheinlichkeit 10 Haltestellen, an denen Stau entsteht
Jam = []
for i in range(0,10):   ##Anzahl an Haltestellen mit Stau
    x = (randint(0, count_row))
    for j in range(0, len(cumulativeHS)):
        if x <= cumulativeHS[j]:
            Jam.append(j)
            break

############################## Funktionen fÃ¼r Objekt Vehicle #############################

# Abfrage: Fahrtzeit Ã¼ber Simulationsdauer
def drive_outOfTime(time, clock):
    doOT = time + clock > 1440
    return doOT

############################ StÃ¶rgenerator##################################
S = 5 # Einstellen des StÃ¶rfaktors

def stoerfaktor(s):  # n = Eingabeparameter um StÃ¶rausmaÃ zu steuern
    if (s == 0):
        factorX = numpy.random.choice(numpy.arange(0, 11), p=[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                                                              0.0])  # Wahrscheinlichkeiten von StÃ¶rungen / fÃ¼r jeden
        # Teilfahrt neuen StÃ¶rfaktor
    elif (s == 1):
        factorX = numpy.random.choice(numpy.arange(0, 11), p=[0.6, 0.2, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                                                              0.0])  # Wahrscheinlichkeiten von StÃ¶rungen / fÃ¼r jeden
        # Teilfahrt neuen StÃ¶rfaktor
    elif (s == 2):
        factorX = numpy.random.choice(numpy.arange(0, 11), p=[0.6, 0.0, 0.0, 0.2, 0.0, 0.2, 0.0, 0.0, 0.0, 0.0,
                                                              0.0])  # Wahrscheinlichkeiten von StÃ¶rungen / fÃ¼r jeden
        # Teilfahrt neuen StÃ¶rfaktor
    elif (s == 3):
        factorX = numpy.random.choice(numpy.arange(0, 11), p=[0.33, 0.0, 0.0, 0.0, 0.0, 0.33, 0.0, 0.0, 0.0, 0.0,
                                                              0.34])  # Wahrscheinlichkeiten von StÃ¶rungen / fÃ¼r
        # jeden Teilfahrt neuen StÃ¶rfaktor
    elif (s == 4):
        factorX = numpy.random.choice(numpy.arange(0, 11), p=[0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
                                                              0.5])  # Wahrscheinlichkeiten von StÃ¶rungen / fÃ¼r
        # jeden Teilfahrt neuen StÃ¶rfaktor
    elif (s == 5):
        factorX = 20
    return factorX

##VerspÃ¤tungen auÃerhalb der Simulation bilden
"""
def verspÃ¤tung():

    for fzg in range(1,len(numberVeh) + 1):
        shift = 0
        for partNbr in range(0, len(StartTime_dic[fzg-1])-1):
            if partNbr > 0:                ##wenn es nicht der erste teilumlauf ist, kann es zu abhÃ¤ngigkeiten zw den umlÃ¤ufen kommen
                lastTime = len(PartEndTime_dic[fzg-1][partNbr-1])-1   ##Zeit des letzten Umlaufs
                ##Wenn Umlauf starten soll, obwohl letzter Umlauf noch nicht beendet:
                if PartStartTime_dic[fzg-1][partNbr][0] < PartEndTime_dic[fzg-1][partNbr-1][lastTime]:
                    shift += PartEndTime_dic[fzg-1][partNbr-1][lastTime] - PartStartTime_dic[fzg-1][partNbr][0]
                    PartStartTime_dic[fzg-1][partNbr][0] = PartEndTime_dic[fzg-1][partNbr-1][lastTime]
                ##wenn Umlauf starten soll und letzter Umlauf auch beendet ist: (Zeitverschiebung kann verringert werden)
                if PartStartTime_dic[fzg-1][partNbr][0] > PartEndTime_dic[fzg-1][partNbr-1][lastTime]:
                    shift -= PartStartTime_dic[fzg-1][partNbr][0] - PartEndTime_dic[fzg-1][partNbr-1][lastTime]
                if shift < 0:
                    shift = 0

                ##FÃ¼r jeden Teilumlauf die einzelnen Fahrten durchiterieren
            for journey in range(0, len(PartStartTime_dic[fzg-1][partNbr])):
                if journey > 0:
                    PartStartTime_dic[fzg-1][partNbr][journey] = PartEndTime_dic[fzg-1][partNbr][journey-1]
                ##Wenn es keine Standzeit ist:
                if Journey_dic[fzg-1][partNbr][journey] != 9:
                    delaytime = stoerfaktor(2) ##Hier werden die StÃ¶rfaktoren eingebaut
                    shift += delaytime
                    PartEndTime_dic[fzg-1][partNbr][journey] = PartStartTime_dic[fzg-1][partNbr][journey] + DriveDuration_dic[fzg-1][partNbr][journey] + delaytime
                ##Wenn es eine Standzeit ist:
                if Journey_dic[fzg-1][partNbr][journey] == 9:
                    ##Wenn Verschiebung grÃ¶Ãer/gleich der Pausenzeit
                    if DriveDuration_dic[fzg-1][partNbr][journey] < shift:
                        shift = shift - DriveDuration_dic[fzg-1][partNbr][journey]
                        PartEndTime_dic[fzg-1][partNbr][journey] = PartStartTime_dic[fzg-1][partNbr][journey]
                    ##Wenn Verschiebung kleiner Pausenzeit ist
                    elif DriveDuration_dic[fzg-1][partNbr][journey] >= shift:
                        if shift < 0:
                            shift = 0
                        PartEndTime_dic[fzg-1][partNbr][journey] = PartStartTime_dic[fzg-1][partNbr][journey] + DriveDuration_dic[fzg-1][partNbr][journey] - shift
                        shift = 0
                if shift < 0:
                    shift = 0

verspÃ¤tung()

"""

def carTraffic(time):
    if var1.get() == 1:
        if (time >= 390 and time <= 510) or (time >= 1110 and time <= 1200):
            return (stoerfaktor(4))
    ##oder ggf prozentual die duration erhÃ¶ren? (30% mehr zu den stoÃzeiten?)
        else:
            return (stoerfaktor(1))
    else:
        return(stoerfaktor(0))

def weather():
     if var2.get() == 1:
        return(stoerfaktor(4))
     elif var3.get() == 1:
        return(stoerfaktor(3))
     elif var4.get() == 1:
        return(stoerfaktor(1))
     else:
        return(stoerfaktor(0))

def trafficjam(FromHS, ToHS):
    if FromHS in Jam or ToHS in Jam:
        return(stoerfaktor(4))
    else:
        return(stoerfaktor(0))

def breaktime(vehID, teilumlaufnummer, fahrtnummer, delayTime):
    if ElementID_dic[vehID][teilumlaufnummer][fahrtnummer] == 9:
        DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer] = \
        DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer] - delayTime
        if DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer] < 0:
            delayTime = abs(DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer])
            DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer] = 0
        else:
            delayTime = 0
    return(delayTime)

def Type(weather, traffic, jam):
    delayType = ""
    if weather > 0:
        delayType += ("Wetter")
    if traffic > 0 and delayType == "":
        delayType += ("Verkehr")
    elif traffic > 0 and delayType != "":
        delayType += (",Verkehr")
    if jam > 0 and delayType == "":
        delayType += ("Stau")
    elif jam > 0 and delayType != "":
        delayType += (",Stau")
    else:
        delayType += ("-")
    return(delayType)

############################## Daten fÃ¼r CSV-Datei ###############################
# Header fÃ¼r CSV-Datei
print("vehID Teilumlaufnummer Standort Dep/Arr Uhrzeit(Soll) Uhrzeit(Ist) FahrtverspÃ¤tung GesamtverspÃ¤tung VerspÃ¤tungsursache",
      file=open("eventqueue5.2.csv", "a"))
########################## Objekt Vehicle #########################################
def vehicle(env, vehID):  # Eigenschaften von jedem Fahrzeug
    while True:
        delayTime = 0  # DelayTime initialisieren (gilt fÃ¼r den ganze Tag des Fahrzeugs)
        delayType = ""
        for teilumlaufnummer in range(0, len(StartTime_dic)-1):  #Loop der durch die einzelnen TeilumlÃ¤ufe fÃ¼hrt
            try:
                if StartTime_dic[vehID][teilumlaufnummer] - env.now >= 0:
                    delayTime = 0
                    delayType = ""
                    yield env.timeout(
                        StartTime_dic[vehID][teilumlaufnummer] - env.now)
                else:
                    yield env.timeout(0)
                    delayTime = env.now - StartTime_dic[vehID][teilumlaufnummer]
                    delayType = ""

                umlaufstatus = 1  # Wenn Startzeit erreicht, Fahrzeug im Umlauf (umlaufstatus = 1)

                while umlaufstatus == 1:  # while Fahrzeug im Umlauf
                    for fahrtnummer in range(0, len(FromHS_dic[vehID][teilumlaufnummer])):

                        if ElementID_dic[vehID][teilumlaufnummer][fahrtnummer] == 9:
                            fahrtstatus = 2
                        else:
                            fahrtstatus = 0 # 0 = Abfahrt / 1 = Ankunft / 2 = Pause

                        delayTime_perDrive = 0 #fÃ¼r PrintAusgabe hier definiert
                        print(vehID + 1, teilumlaufnummer + 1, FromHS_dic[vehID][teilumlaufnummer][fahrtnummer],
                              fahrtstatus, PartStartTime_dic[vehID][teilumlaufnummer][fahrtnummer], env.now,
                              "-", delayTime, "-",
                              file=open("eventqueue5.2.csv", "a"))

                        # VerspÃ¤tung auf Fahrt ermitteln
                        delayType = ""
                        if ElementID_dic[vehID][teilumlaufnummer][fahrtnummer] == 9:
                            delayTime_perDrive = 0
                            delayType = "-"
                        else:
                            delayWeather = weather()
                            delayCarTraffic = carTraffic(env.now)
                            delayTrafficJam = trafficjam(FromHS_dic[vehID][teilumlaufnummer][fahrtnummer], ToHS_dic[vehID][teilumlaufnummer][fahrtnummer])
                            delayTime_perDrive = delayWeather + delayCarTraffic + delayTrafficJam
                            # FÃ¼ge der Outputvariable "delayType" den Grund der VerspÃ¤tung hinzu
                            delayType = Type(delayWeather, delayCarTraffic, delayTrafficJam)

                        # Aufsummieren der VerspÃ¤tungen im Teilumlauf
                        delayTime += delayTime_perDrive

                        # Abfrage, ob Fahrt auÃerhalb der Simulationszeit liegen wÃ¼rde
                        if drive_outOfTime(
                                DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer], env.now):
                            yield env.timeout(1440)
                            break

                        # Abfrage, ob Pausenzeit & VerspÃ¤tungszeit anpassen
                        delayTime = breaktime(vehID, teilumlaufnummer, fahrtnummer, delayTime)

                        # Timeout fÃ¼r Fahrtdauer zur nÃ¤chsten Haltestelle
                        yield (env.timeout(DriveDuration_dic[vehID][teilumlaufnummer][fahrtnummer] + delayTime_perDrive))

                        if ElementID_dic[vehID][teilumlaufnummer][fahrtnummer] == 9:
                            fahrtstatus = 2
                        else:
                            fahrtstatus = 1

                        # Abfrage ob Bus im Depot angekommen
                        if ToHS_dic[vehID][teilumlaufnummer][fahrtnummer] == DepotID[vehID]:
                            print(vehID + 1, teilumlaufnummer + 1, ToHS_dic[vehID][teilumlaufnummer][fahrtnummer],
                                  fahrtstatus, PartEndTime_dic[vehID][teilumlaufnummer][fahrtnummer],
                                  env.now, delayTime_perDrive, delayTime, delayType,
                                  file=open("eventqueue5.2.csv", "a"))
                            umlaufstatus = 0
                        else:
                            print(vehID + 1, teilumlaufnummer + 1, ToHS_dic[vehID][teilumlaufnummer][fahrtnummer],
                                  fahrtstatus, PartEndTime_dic[vehID][teilumlaufnummer][fahrtnummer],
                                  env.now, delayTime_perDrive, delayTime, delayType,
                                  file=open("eventqueue5.2.csv", "a"))

            except:
                if env.now >= 1440: # to avoid RunTimeError: GeneratorExit
                    return False
                continue

            ########################## Simulationsumgebung ##############################

env = simpy.Environment()

# Initialisierung von Fahrzeugen
for i in range(0,len(numberVeh)):  # Anzahl von Fahrzeugen = len(numberVeh)
    env.process(vehicle(env, i))  # Inputdaten Eigenschaften Fahrzeugen
# Simulation starten und Laufzeit festlegen
env.run(until=1440)  # Ein Tag simulieren: in Minuten ausdrÃ¼cken. 24h = 1440min


import flask
import os
from flask import request, send_file, make_response, jsonify
from meshlab import Meshlab, delete_output_file, get_output_file_path, get_file_names

app = flask.Flask(__name__)
UPLOAD_FOLDER = 'tmp/uploads'
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

@app.route("/process",  methods=["POST"])
def process():
    mesh = None
    filter = None
    for key in request.files:
        file = request.files[key]
        print(file)
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        filename = file.filename
        path = os.path.join(app.config['UPLOAD_FOLDER'] + "/" + key + "/", filename)
        print(path)
        file.save(path)

        if key == "template":
            filter = path
        else:
            mesh = path

    ml = Meshlab(mesh, filter)
    output_file = ml.process()
    return (output_file, 200)

@app.route("/files/<file_id>", methods=['GET'])
def get_file(file_id):
    return (send_file(get_output_file_path(file_id)), 200)

@app.route("/files/", methods=['GET'])
def get_files():
    return (jsonify(get_file_names()), 200)

@app.route("/files/<file_id>", methods=['DELETE'])
def delete_file(file_id):
    delete_output_file(file_id)
    return ('', 200)

@app.route("/", methods=["GET"])
def home():
    return "
MeshLab Container
"

app.run(port=5000, host="0.0.0.0")


"""
ID: wrwwctb1
LANG: PYTHON3
TASK: contact
3.1.5

key idea
count the number of every bit pattern seen
use an array to keep the counts
the index is bit pattern with a leading 1 prepended, eg to separate 01 and 001
"""

import os, sys, re, time
from collections import Counter, deque, defaultdict
from queue import Queue
from copy import copy, deepcopy
from itertools import combinations, permutations, accumulate, \
                      combinations_with_replacement
from functools import lru_cache, cmp_to_key, partial as functools_partial
from heapq import heappush, heappop, nlargest, nsmallest
from bisect import bisect_left, bisect_right
from math import ceil, floor, factorial, gcd, modf, log, log2, log10, sqrt, \
         pi, sin, cos, tan, asin, acos, atan, atan2, hypot, erf, erfc, inf, nan
# sys.setrecursionlimit(5782)
# python -m cProfile -s time ha.py

print = functools_partial(print, flush=True)
input = lambda: fin.readline().strip('\n')

def printwrite(string):
    print(string)
    fout.write(str(string) + '\n')

filename = 'contact'
fin = open(filename + '.in', 'r')
fout = open(filename + '.out', 'w')
ttt = time.time()

A, B, N = map(int, input().split())

string = []
while True:
    line = input()
    if line == '':
        break
    string.append(line)
string = ''.join(string)

Ncounts = 10000
counts = [0] * Ncounts

Nstring = len(string)
for i in range(Nstring):
    for l in range(A, B + 1):
        if i + l > Nstring:
            break
        sub = string[i:i+l]
        idx = int(sub, 2)
        idx ^= 1 << l
        counts[idx] += 1

counts = list(zip(counts, range(Ncounts)))

counts.sort(key=lambda cnt_idx: (-cnt_idx[0], cnt_idx[1]))

# collect results
out = defaultdict(list)
countsIdx = 0
while True:
    currCnt, currBits = counts[countsIdx]
    if currCnt == 0:
        break
    if (len(out) > N or (len(out) == N and currCnt not in out)):
        break
    out[currCnt].append(currBits)
    countsIdx += 1

# output
for key in sorted(out.keys(), reverse=True):
    printwrite(key)
    vals = out[key]
    outVals = []
    for val in vals:
        outVals.append(bin(val)[3:])
    i = 0
    while i < len(outVals):
        if i + 6 < len(outVals):
            printwrite(' '.join(['%s'] * 6) % tuple(outVals[i:i+6]))
        else:
            r = len(outVals) - i
            printwrite(' '.join(['%s'] * r) % tuple(outVals[i:i+r]))
        i += 6

fin.close()
fout.close()
del print, input
print(time.time() - ttt)


#!usr/bin/env python3
"""
main file, training the model in this file.
"""

import tensorflow as tf
from dataset import get_imagepaths_and_labels, read_images
from dataset import get_test_imagepaths_labels, read_test_images
from models import conv_net

# paths setting
MODEL_PATH = './models/conv_net'
DATASET_PATH = ''

# training parameters
learning_rate = 0.001
num_steps = 500
batch_size = 128
display_step = 100

# network parameters
num_classes = 10
dropout = 0.75

# reading the dataset
imagepaths, labels = get_imagepaths_and_labels(DATASET_PATH)
imagepaths_test, labels_test = get_test_imagepaths_labels(DATASET_PATH)

# build data input
X, Y = read_images(imagepaths, labels, batch_size)
X_test, Y_test = read_test_images(imagepaths_test, labels_test)

# define training ops
logits_train = conv_net(X, num_classes, dropout, reuse=False, is_training=True)
loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits \
                                           (logits=logits_train, labels=Y))

optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)

# define testing ops
logits_test = conv_net(X_test, num_classes, dropout, reuse=True, is_training=False)
correct_pred = tf.equal(tf.argmax(logits_test, 1), Y_test)
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

init = tf.global_variables_initializer()
saver = tf.train.Saver()

# training
with tf.Session() as sess:

    sess.run(init)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    print("Start training")

    for step in range(1, num_steps+1):

        if step % display_step == 0:
            _, loss, acc = sess.run([train_op, loss_op, accuracy])
            print("Step: " + "%04d" %step + ", loss= " + "{:.9f}".format(loss)\
                   + ", accuracy:" + "{:.4f}".format(acc))
        else:
            sess.run(train_op)

    print("Optimization finished!")

    saver.save(sess, MODEL_PATH)

    coord.request_stop()
    coord.join(threads)


import click
import os
import sys

from tlt.utils.file_utils import get_model_name_from_path

@click.command()
@click.option("--model-name", "--model_name",
              required=False,
              type=str,
              help="Name of the model to use")
@click.option("--model-dir", "--model_dir",
              required=False,
              type=str,
              help="Model directory to reload a previously exported model.")
@click.option("--prompt",
              required=False,
              type=str,
              help="Prompt with added context used to build the prompt dictionary")
@click.option("--temperature",
              required=False,
              type=float,
              default=1.0,
              help="The value used to modulate the next token probabilities (default: 1.0)")
@click.option("--top-p", "--top_p",
              required=False,
              type=float,
              default=0.75,
              help="If set to float < 1, only the smallest set of most probable tokens with probabilities "
                   "that add up to top_p or higher are kept for generation (default: 0.75)")
@click.option("--top-k", "--top_k",
              required=False,
              type=int,
              default=40,
              help="The number of highest probability vocabulary tokens to keep for top-k-filtering (default: 40)")
@click.option("--repetition-penalty", "--repetition_penalty",
              required=False,
              type=float,
              default=1.0,
              help="The parameter for repetition penalty. 1.0 means no penalty. (default: 1.0)")
@click.option("--num-beams", "--num_beams",
              required=False,
              type=int,
              default=4,
              help="Number of beams for beam search. 1 means no beam search. (default: 4)")
@click.option("--max-new-tokens", "--max_new_tokens",
              required=False,
              type=int,
              default=128,
              help="The maximum number of new tokens generated (default: 128)")
def generate(model_dir, model_name, prompt, temperature, top_p, top_k, repetition_penalty,
             num_beams, max_new_tokens):
    """
    Generates text from the model
    """
    from tlt.models import model_factory
    if model_name is None and model_dir is None:
        sys.exit("ERROR: Please define a model_dir to load a saved model OR specify model_name to use a "
                 "model for text generation")
    if model_name is None:
        model_name = get_model_name_from_path(model_dir)

    if model_dir:
        if not os.path.exists(os.path.join(model_dir, 'adapter_model.bin')):
            sys.exit("The Generate command is only supported for Pytorch Text Generation models")

    # Get the model
    try:
        model = model_factory.get_model(model_name, framework="pytorch", use_case="text_generation")
    except Exception as e:
        sys.exit("Error while getting the model (model name: {}), The Generate command is only supported"
                 " for Pytorch Text Generation models:\n{}".format(model_name, str(e)))

    if model_dir:
        if os.path.exists(model_dir):
            model.load_from_directory(model_dir)

    prompt = prompt.replace("\\n", "\n")
    output = model.generate(prompt, temperature=temperature, repetition_penalty=repetition_penalty, top_p=top_p,
                            top_k=top_k, num_beams=num_beams, max_new_tokens=max_new_tokens)
    print(*output, sep='\n')


# -*- coding: utf-8 -*-
"""
lesson3_osm_data.py

Tama skripti sisaltaa luento3 harjoitukset:
- opsen street mapin kasittely

Created on Tue Nov 13 11:18:02 2018

@author: Suvi Hatunen
"""
import osmnx as ox
import matplotlib.pyplot as plt

# specify the name of the AOI
place_name = "Kamppi, Helsinki, Finland"

# fetch osm street network from Kamppi
graph = ox.graph_from_address(place_name)

# plot the streets
fig, ax = ox.plot_graph(graph)

# convert the graph to geodataframes
nodes, edges = ox.graph_to_gdfs(graph)

# retrieve buildings from Kamppi
buildings = ox.buildings_from_address(place_name, distance=1000)

# footprint of Kamppi
footprint = ox.gdf_from_place(place_name)

# retrieve POI from osm
restaurants = ox.pois_from_place(place_name, amenities=['restaurant', 'bar'])

# plot everything together
# at the bottom the footprint
ax = footprint.plot(facecolor='black')
# the next layer is street edges
ax = edges.plot(ax=ax, linewidth=1, edgecolor='#BC8F8F')
# the next one is buildings, alpa tarkoittaa transparenttiutta 0= transparent, 1=non-transparent
ax = buildings.plot(ax=ax, facecolor='khaki', alpha=0.7)
# on the top the restaurants
ax = restaurants.plot(ax=ax, color='green', alpha=0.7, markersize=10)


import sqlite3

databasePath = 'models/admins.db'

def insertAdmin(email):
    try:
        conn = sqlite3.connect(databasePath)
        c = conn.cursor()
        c.execute("INSERT INTO admins (email) VALUES (?)", [email])
        conn.commit()
    except sqlite3.Error as error:
        raise Exception("An error occurred while inserting an email", error)
    finally:
        conn.close()

def deleteAdmin(email):
    try:
        conn = sqlite3.connect(databasePath)
        c = conn.cursor()
        c.execute("DELETE FROM admins WHERE email=?", [email])
        conn.commit()
    except sqlite3.Error as error:
        raise Exception("An error occurred while deleting an email", error)
    finally:
        conn.close()

def getAllAdmins():
    try:
        conn = sqlite3.connect(databasePath)
        c = conn.cursor()
        c.execute("SELECT * FROM admins")
        users = c.fetchall()
        return users
    except sqlite3.Error as error:
        raise Exception("An error occurred while getting an email", error)
    finally:
        conn.close()

def assignRole(email):
    list = getAllAdmins()
    if list.count(email) > 0:
        return 1
    else:
        return 0

if __name__ == "__main__":
    insertAdmin("meesen@tsn.at")


import json
from HclObject import HclObject

with open('value_names.json') as json_file:
    value_names = json.load(json_file)

with open('dashboard.json') as json_file:
    dashboard_data = json.load(json_file)

with open('var.json') as json_file:
    var_json = json.load(json_file)

hcl_obj = HclObject(is_root=True)
data = []

for widget in dashboard_data['widgets']:
    for panel in widget['definition']['widgets']:
        if panel['definition']['type'] == 'timeseries':
            requests = []
            for q in panel["definition"]["requests"]:
                requests.append(HclObject(type='dict_raw', values=[
                    HclObject(attribute_name='q', type='str', values=f'"{q["q"]}"'),
                    HclObject(attribute_name='type', type='str',
                              values=f'"{q["display_type"]}"'),
                ]))

            data.append(HclObject(attribute_name=f'{value_names[len(data)]}', type='dict_equal', values=[
                HclObject(attribute_name='title', type='str', values=f'"{panel["definition"]["title"]}"'),
                HclObject(attribute_name='viz', type='str', values='"timeseries"'),
                HclObject(attribute_name='autoscale', type='boolean', values='true'),
                HclObject(attribute_name='request', type='list', values=
                    requests
                ),
            ]))
        else: #timeseries가 아닌 경우
            pass

hcl_obj.add_attribute(type='locals', values=data)
result = hcl_obj.generate_hcl()

for key, val in var_json.items():
    result = result.replace(val, f'${{var.{key}}}')

print(result)


import requests
import re
import sys

from bs4 import BeautifulSoup
webpage = sys.argv[1]
page = requests.get(webpage)
soup = BeautifulSoup(page.content, 'html.parser')
questions = soup.find_all('table',class_="menu-tbl")
answers={}
for que in questions:
    children  =list(que.children)
    qno = children[1].get_text()
    opt = children[8].get_text()
    if(opt.isdigit()):
        answers[qno[13:]] = children[int(opt)+1].get_text()[13:]
    else:
        answers[qno[13:]] = "0"

ans_page  = open('JEE(Main).htm',encoding="utf8")
soup = BeautifulSoup(ans_page, 'html.parser')
exp = re.compile("ctl00_ContentPlaceHolder1_grAnswerKey_ctl(0[2-9]|[1-8][0-9]|90|91)_lbl_QuestionNo")
result_que = soup.find_all(id=exp)
exp2 = re.compile("ctl00_ContentPlaceHolder1_grAnswerKey_ctl(0[2-9]|[1-8][0-9]|90|91)_lbl_RAnswer")
result_ans = soup.find_all(id=exp2)
result_ans_list = list(result_ans)
score = 0
no_of_answered = 0
no_of_unattempted = 0
no_of_correct = 0
no_of_incorrect = 0
ele = 0
for q in result_que:
    qid = q.get_text()
    correct_ans = result_ans_list[ele].get_text()
    marked_ans = answers[q.get_text()]
    # print(qid,correct_ans,marked_ans)
    if(marked_ans!="0"):
        #Answered
        if(marked_ans==correct_ans):
           #Correct
           no_of_correct += 1
           score += 4
        else:
            #Incorrect
            no_of_incorrect += 1
            score -= 1
        no_of_answered+=1
    else:
        no_of_unattempted += 1

    ele = ele+1
print("Answered",no_of_answered)
print("Unanswered",no_of_unattempted)
print("Correct Answers",no_of_correct)
print("Incorrect Answers",no_of_incorrect)
print("Score",score)


from xml.dom import minidom
import os

class xml_converter:

    def __init__(self):
        self.classes={}
        self.class_count = -1
        self.file_count = 0

        self.current_path = os.path.abspath(os.curdir)
        self.ORIGIN_FORMAT_PATH = self.current_path + '/images/org_image'
        self.XML_FORMAT_PATH = self.current_path + '/images/annotation'
        os.chdir(self.XML_FORMAT_PATH)

    def getYoloCordinates(self, size, box):
        width_ratio = 1.0/size[0]
        height_ratio = 1.0/size[1]
        x = (box[0]+box[1])/2.0
        y = (box[2]+box[3])/2.0
        w = box[1]-box[0]
        h = box[3]-box[2]
        x = x * width_ratio
        w = w * width_ratio
        y = y * height_ratio
        h = h * height_ratio
        return (x,y,w,h)

    def xml_to_yolo(self):
        for current_dir, dirs, files in os.walk('.'):
            for file in files:
                if file.endswith('.xml'):
                    xmldoc = minidom.parse(file)
                    yolo_format = (self.ORIGIN_FORMAT_PATH+'/'+file[:-4]+'.txt')

                    with open(yolo_format, "w") as f:

                        objects = xmldoc.getElementsByTagName('object')
                        size = xmldoc.getElementsByTagName('size')[0]
                        width = int((size.getElementsByTagName('width')[0]).firstChild.data)
                        height = int((size.getElementsByTagName('height')[0]).firstChild.data)

                        for item in objects:
                            name =  (item.getElementsByTagName('name')[0]).firstChild.data

                            if not name in self.classes:
                                self.class_count += 1

                            self.classes[name] = self.class_count

                            if name in self.classes:
                                class_name = str(self.classes[name])
                            else:
                                class_name = "-1"
                                print ("[Warning]Class name ['%s'] is not in classes" % name)

                            # get bbox coordinates
                            xmin = ((item.getElementsByTagName('bndbox')[0]).getElementsByTagName('xmin')[0]).firstChild.data
                            ymin = ((item.getElementsByTagName('bndbox')[0]).getElementsByTagName('ymin')[0]).firstChild.data
                            xmax = ((item.getElementsByTagName('bndbox')[0]).getElementsByTagName('xmax')[0]).firstChild.data
                            ymax = ((item.getElementsByTagName('bndbox')[0]).getElementsByTagName('ymax')[0]).firstChild.data
                            xml_cordinates = (float(xmin), float(xmax), float(ymin), float(ymax))
                            yolo_cordinates = self.getYoloCordinates((width,height), xml_cordinates)

                            f.write(class_name + " " + " ".join([("%.6f" % a) for a in yolo_cordinates]) + '\n')
                            self.file_count += 1

                    print ("{}. [{}] is created".format(self.file_count, yolo_format))

        with open(self.current_path + '/' + 'classes.txt', 'w') as txt:
            for item in self.classes:
                txt.write(item + '\n')
                print ("[%s] is added in classes.txt" % item)
        os.chdir(self.current_path)


class Game:
    def __init__(self, player1, player2):
        self.player1 = player1
        self.player2 = player2
        self.current_player = self.player1
        self.sticks = 0
        self.pick_sticks = 0

    def start(self):
        self.num_sticks()
        print(self.sticks)
        while self.sticks > 1:
            self.pick_num_sticks()
            self.decrement_sticks()
            self.loser()

    def num_sticks(self):
        print("Welcome to the Game of Sticks!")
        sticks = int(input("How many sticks are on the table initially (10 - 100)? "))
        while sticks < 10 or sticks > 100:
            print ("Please enter a number between 10 and 100.")
            sticks = int(input("How many sticks are on the table initially (10 - 100)? "))
        return sticks

    def pick_num_sticks(self):
        pick_sticks = int(input("How many sticks do you take (1-3)? "))
        while pick_sticks < 1 or pick_sticks > 3:
            print("Please enter a number between 1 and 3.")
            pick_sticks = int(input("How many sticks do you take (1-3)? "))
        return pick_sticks

    def decrement_sticks(self):
        self.sticks -= self.pick_sticks

    def switch_players(self):
        if self.current_player == self.player1:
            self.current_player = self.player2
        else:
            self.current_player = self.player1

    def loser(self):
         if self.total_sticks == 1:
             self.current_player = self.player1
         else:
             self.current_player = self.player2

class Player:
    def __init__(self, name):
        self.name = name

if __name__ == '__main__':
    p1 = Player("Player1")
    p2 = Player("Player2")
    game = Game(p1, p2)
    game.start()


#encoding:utf-8_*_
#author：@robin
#create time：2018/11/1 9:18
#file：lasso.py
#IDE:PyCharm
import numpy as np
import regression.starndLR as stand
from numpy import *
from matplotlib import pyplot as plt
#lasso的功能:解决最小当特征数大于样本数，特征存在冗余的时候
#标准化矩阵
def regular(xMat,yMat):
    yMean = np.mean(yMat,0)
    xMean = np.mean(xMat,0)
    xVar = np.var(xMat,0)
    yMat = yMat-yMean
    xMat = (xMat-xMean)/xVar
    return xMat,yMat
def rsserror(label,yhat):
    error = ((label-yhat)**2).sum()
    return error
#lasso算法中由于具有绝对值函数，因此求导的时候有必要进行处理，（1）贪心算法：先找到一个特征，固定其他系数，优化该特征（前向逐步回归）
#                                                            （2）逐一优化：固定某一维度，选择某一维度进行优化
def forword_step_res(xArr,yArr,eps=0.01,numIter=10):
    xMat = np.mat(xArr);yMat = np.mat(yArr).transpose()
    xMat,yMat = regular(xMat,yMat)
    m,n = np.shape(xMat)
    returnweight = np.zeros((numIter,n))
    weight = np.zeros((n,1))
    wTest = weight.copy();wMax = weight.copy()
    print('w original:', weight.T)
    for i in range(numIter):
        lower = np.inf
        for j in range(n):
            for chang in [-1,1]:
                wTest = weight.copy()
                wTest[j] += eps*chang
                yTest = xMat*wTest
                # print('yMat',yMat.A)
                # print('yTest',yTest.A)
                error = rsserror(yMat.A,yTest.A)
                if(error<lower):
                    lower = error
                    wMax = wTest
        weight = wMax.copy()
        returnweight[i,:] = weight.T
        # print('returnweight',returnweight);exit()
    return returnweight

if __name__=='__main__':
    xArr,yArr = stand.loadData('abalone.txt')
    iter_weight = forword_step_res(xArr,yArr,eps=0.005,numIter=1000)
    # iter_weight = forword_step_res(xArr,yArr)
    print('last weight:\n',iter_weight)
    fig = plt.figure(figsize=(8,5))
    ax1 = fig.add_subplot(111)
    ax1.plot(iter_weight)
    ax1.plot(iter_weight)
    plt.xlabel('iter num')
    plt.ylabel('every feature corfficient')
    plt.title('different iter weight')
    plt.show()
    ws = stand.standRegression(xArr,yArr)
    print('最小二乘法权重：',ws.T)


class Solution:
    def merge(self, intervals):
        ans = []
        intervals.sort(key=lambda x: x[0])
        for interval in intervals:
            if not ans:
                ans.append(interval)
            if ans[-1][1] < interval[0]:
                ans.append(interval)
            else:
                ans[-1][1] = max(ans[-1][1], interval[1])
        return ans


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 13:32:33 2018

@author: Oskari

This is a test program which is supposed to simulate a DAQ, fetch the simulated
data and plot it using the niscope module.
"""

import numpy as np
import niscope
import matplotlib.pyplot as plt

def simulate_DAQ(resource_name, options, n_samples, sample_rate, vertical_range,coupling):
    # 1. Initialize DAQ
    with niscope.Session(resource_name=resource_name,options=options) as session:

        # List channels to be used:
        channel_list = [0]

        # 2. Configure settings for data acquisition:
        #Configure timing settings
        session.configure_horizontal_timing(min_sample_rate=sample_rate,
                                            min_num_pts = n_samples,
                                            ref_position = 0.0,
                                            num_records = 1,
                                            enforce_realtime = True)

        # Configure vertical (data) settings:
        session.channels[channel_list].configure_vertical(vertical_range, coupling)

        # 3. Allocate numpy arrays for data
        waveforms = [np.ndarray(n_samples, dtype=np.float64) for c in channel_list]

        # 4. Configure trigger
        session.configure_trigger_immediate()

        # 5. Collect data using fetch_into()
        #Initiate data collection
        with session.initiate():
            for channel, waveform in zip(channel_list, waveforms):
                session.channels[channel].fetch_into(waveform)

    return waveforms

def plot(waveforms):
    for waveform in waveforms:
        x = np.arange(0,len(waveform),1)
        plt.plot(x,waveform)

def main():
    resource_name = 'PXI1Slot2'
    options = {'simulate': True, 'driver_setup': {'Model': '5164', 'BoardType': 'PXIe', }, }
    n_samples = 1000
    sample_rate = 10000.0
    vertical_range = 2.0
    coupling = niscope.VerticalCoupling.DC
    waveforms = simulate_DAQ(resource_name, options, n_samples, sample_rate, vertical_range,coupling)

    plot(waveforms)

Data acquisition software/Photodetector DAQ (Python)/simulate_DAQ.py


# Uang anak kos

# kamus
kos = 500000 # biaya kos
makan = 500000 # uang buat makan/jajan
buku = 200000 #uang buat beli buku

pengeluaran = kos + makan + buku
sangu = int(input('Uang bulanan yang diberikan ortu Soni: '))

tiket_biasa = 500000
tiket_vip = 1000000

#algoritma
if sangu >= pengeluaran:
    uang = sangu - pengeluaran
    if uang >= tiket_vip:
        print('Soni jadi menonton konser dengan tempat duduk VIP')
    elif tiket_biasa <= uang < tiket_vip:
        print('Soni jadi menonton konser dengan tempat duduk biasa')
    else:
        print('Soni tidak bisa menonton konser karena uang kurang')
else:
    print('Input tidak valid')


from fastapi import FastAPI, status

from src.api.question import create_question
from src.schema import QuestionSchema

def add_routes(app: FastAPI) -> None:
    app.add_api_route(
        path='/api/questions',
        endpoint=create_question,
        status_code=status.HTTP_201_CREATED,
        response_model=QuestionSchema,
        methods=['post'],
    )


import json
import requests
import sys
import argparse

def highestID():
	return requests.get("https://0ym0hvjsll.execute-api.us-east-2.amazonaws.com/default/chat/highestid").json()

def newMessage(msgID = None):

	i = highestID()
	if msgID == None:
		message_id = i
	else:
		message_id = str(msgID)

	r = requests.get("https://0ym0hvjsll.execute-api.us-east-2.amazonaws.com/default/chat?id="+message_id)

	messages = r.json()["Items"]
	if len(messages) > 0:
		with open("messages.txt", "w") as f:
			for item in messages:
				reponse = item['user']+ ": "+ item['message'] + "\n"
				f.write(reponse)
				#print(reponse)

	return len(messages) > 0

def getMessages():
	f = open("messages.txt","r")
	lines = f.readlines()
	for line in lines:
		print(line)

# print(highestID())
# print(newMessage(-1))


import requests;
import pandas as pd
def fetch_data_api(offset,ts,key,Hash,name_start_with) :

    payload= {  'ts':ts,
            'apikey': key,
            'hash' : Hash ,
          'limit':'100',
          'offset':offset,
        'nameStartsWith': name_start_with
         }
    r = requests.get("http://gateway.marvel.com/v1/public/characters" ,params = payload)
    print(r.status_code,r.reason)
    if(r.status_code != 200):
        raise Exception(r.reason,r.status_code)
    df = pd.read_json(r.url)
    data=df['data']['results']
    df1= pd.json_normalize(data)
    return df1[['id','name','comics.available','series.available','stories.available','events.available']]

def filter_char(df,column,cond,comp):
    if(cond==1):
        return df[df[column]==comp]
    if(cond==2):
        return df[df[column]!=comp]
    if(cond==3):
        return df[df[column]<=comp]
    if(cond==4):
        return df[df[column]<comp]
    if(cond==5):
        return df[df[column]>=comp]
    if(cond==6):
        return df[df[column]>comp]

# name = input('name')

# print(name *10)


import itertools
from collections import defaultdict
from heapq import heappush, heappop

inf = float("inf")

N, M, R = map(int, input().split())
towns = list(map(int, input().split()))

vertices = [i for i in range(1, N+1)]
edge_costs = {i: defaultdict(int) for i in range(N+1)}

for _ in range(M):
    a, b, c = map(int, input().split())
    edge_costs[a][b] = c
    edge_costs[b][a] = c

def dijkstra(s):
    dist = [inf for _ in range(N+1)]
    dist[s] = 0
    searched = [False for _ in range(N+1)]

    q = [] # heap
    heappush(q, (0, s))

    while len(q) != 0:
        d, v = heappop(q)
        # don't need to check when the stored vertex has been already searched,
        # or the stored value is greater than provisional distance
        if searched[v] or d > dist[v]:
            continue

        for u, c in edge_costs[v].items():
            temp = d + c
            if temp < dist[u]:
                dist[u] = temp
                heappush(q, (dist[u], u))

        searched[v] = True

        if sum(searched) == N: # finish when all vertices have been searched
            break

    return [dist[t] for t in towns]

D = [dijkstra(t) for t in towns]

ans = min([sum([D[perm[i]][perm[i+1]] for i in range(R-1)]) for perm in itertools.permutations(range(R))])
print(ans)


import numpy as np
from astropy.io import fits

import vstarstack.library.data

def readfits(filename: str):
    """Read fits image file"""

    images = fits.open(filename)

    for plane in images:
        tags = {}
        for key in plane.header:
            val = str(plane.header[key])
            tags[key] = val

        shape = plane.data.shape
        if len(shape) == 2:
            original = plane.data.reshape((1, shape[0], shape[1]))
        else:
            original = plane.data
        shape = original.shape

        params = {
            "w": shape[2],
            "h": shape[1],
        }

        dataframe = vstarstack.library.data.DataFrame(params, tags)

        exptime = plane.header["EXPTIME"]

        slice_names = []

        weight_channel_name = "weight"
        weight = np.ones((shape[1], shape[2]))*exptime
        dataframe.add_channel(weight, weight_channel_name, weight=True)

        if shape[0] == 1:
            if "FILTER" in plane.header:
                channel_name = plane.header["FILTER"].strip()
            else:
                channel_name = "Y"
            slice_names.append(channel_name)
        elif shape[0] == 3:
            slice_names.append('R')
            slice_names.append('G')
            slice_names.append('B')
        else:
            print("Unknown image format, skip")
            yield None

        for i, slice_name in enumerate(slice_names):
            dataframe.add_channel(
                original[i, :, :], slice_name, brightness=True)
            dataframe.add_channel_link(
                slice_name, weight_channel_name, "weight")

        yield dataframe


from django.utils import timezone
from django.db import models
import json

class Account(models.Model):
    name = models.CharField(max_length=255, null=True)
    startDate = models.DateTimeField(null=True)
    status = models.IntegerField(null=True)
    endDate = models.DateTimeField(null=True)
    owner = models.ForeignKey(
        'Person',
        null=True,
        on_delete=models.SET_NULL,
        related_name='account_owner_data'

    )
    account = models.ForeignKey(
        'Account',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='groups'
    )

    def to_json(self):
        return {
            'id': self.pk,

            'name': self.name,
            'startDate': self.startDate.isoformat() if self.startDate else None,
            'status': self.status,
            'endDate': self.endDate.isoformat() if self.endDate else None,
            'owner': self.owner.to_json() if self.owner else None,
            'account': self.account.to_json() if self.account else None,
        }

class Person(models.Model):
    lastName = models.CharField(max_length=255, null=True)
    firstName = models.CharField(max_length=255, null=True)
    startDate = models.DateTimeField(null=True)
    status = models.IntegerField(null=True)
    phone = models.CharField(max_length=255, null=True)
    email = models.CharField(max_length=255, null=True)
    parentPhone1 = models.CharField(max_length=255, null=True)
    parentPhone2 = models.CharField(max_length=255, null=True)
    dob = models.DateTimeField(null=True)
    userId = models.CharField(max_length=255, null=True)
    type = models.IntegerField(null=True, default=0)

    def to_json(self):
        return {
            'id': self.pk,

            'lastName': self.lastName,
            'firstName': self.firstName,
            'startDate': self.startDate.isoformat() if self.startDate else None,
            'status': self.status,
            'phone': self.phone,
            'email': self.email,
            'parentPhone1': self.parentPhone1,
            'parentPhone2': self.parentPhone2,
            'dob': self.dob.isoformat() if self.dob else None,
            'userId': self.userId,
            'type': self.type,
        }

    def __str__(self):
        return f"{self.pk}: {self.firstName}  {self.lastName} "

class Group(models.Model):
    name = models.CharField(max_length=255)
    startDate = models.DateTimeField()
    endDate = models.DateTimeField()
    weekDays = models.CharField(max_length=255)
    type = models.IntegerField(null=True)
    status = models.IntegerField(null=True)
    days_of_week = models.IntegerField(default=0)
    createdBy = models.OneToOneField(
        'Person',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='created_group'
    )
    created = models.DateTimeField(default=timezone.now)
    lastUpdated = models.DateTimeField(default=timezone.now)
    lastUpdatedBy = models.OneToOneField(
        'Person',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='updated_group'
    )
    teacher = models.ForeignKey(
        'Person',
        null=True,
        on_delete=models.SET_NULL,
        related_name='group_teacher'
    )

    def to_json(self):
        return {
            'id': self.pk,

            'name': self.name,
            'startDate': self.startDate.isoformat(),
            'endDate': self.endDate.isoformat(),
            'weekDays': self.weekDays,
            'type': self.type,
            'status': self.status,
            'createdBy': self.createdBy.to_json() if self.createdBy else None,
            'created': self.created.isoformat(),
            'lastUpdated': self.lastUpdated.isoformat(),
            'lastUpdatedBy': self.lastUpdatedBy.to_json() if self.lastUpdatedBy else None,
            'teacher': self.teacher.to_json() if self.teacher else None,
        }

    def __str__(self):
        return f"{self.pk}: {self.name}  "

class AppUser(models.Model):
    uid = models.CharField(max_length=255, null=True)
    token = models.CharField(max_length=255, null=True)
    active = models.BooleanField(null=True)
    contactId = models.IntegerField(null=True)
    createdBy = models.OneToOneField(
        'Person',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='created_appuser'
    )
    created = models.DateTimeField(default=timezone.now)
    lastUpdated = models.DateTimeField(default=timezone.now)
    lastUpdatedBy = models.OneToOneField(
        'Person',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='updated_appuser'
    )
    userType = models.CharField(max_length=255)
    language = models.CharField(max_length=255, null=True)
    admin = models.BooleanField(null=True)
    person = models.OneToOneField(
        'Person',
        null=True,
        on_delete=models.SET_NULL
    )

    def to_json(self):
        return {
            'uid': self.uid,
            'token': self.token,
            'active': self.active,
            'contactId': self.contactId,
            'createdBy': self.createdBy.to_json() if self.createdBy else None,
            'created': self.created.isoformat(),
            'lastUpdated': self.lastUpdated.isoformat(),
            'lastUpdatedBy': self.lastUpdatedBy.to_json() if self.lastUpdatedBy else None,
            'userType': self.userType,
            'language': self.language,
            'admin': self.admin,
            'person': self.person.to_json() if self.person else None,
        }

class GroupPerson(models.Model):
    studentId = models.IntegerField()
    groupId = models.IntegerField()
    createdBy = models.ForeignKey(
        'Person',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='created_groupperson'
    )
    created = models.DateTimeField(default=timezone.now)
    lastUpdated = models.DateTimeField(default=timezone.now)
    lastUpdatedBy = models.ForeignKey(
        'Person',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='updated_groupperson'
    )
    status = models.IntegerField(null=True)
    group = models.ForeignKey(
        'Group',
        null=True,
        on_delete=models.SET_NULL,
        related_name='group_people'
    )
    student = models.ForeignKey(
        'Person',
        null=True,
        on_delete=models.SET_NULL,
        related_name='group_participations'
    )

    class Meta:
        unique_together = [('studentId', 'groupId')]

    def to_json(self):
        return {
            'id': self.pk,

            'studentId': self.studentId,
            'groupId': self.groupId,
            'createdBy': self.createdBy.to_json() if self.createdBy else None,
            'created': self.created.isoformat(),
            'lastUpdated': self.lastUpdated.isoformat(),
            'lastUpdatedBy': self.lastUpdatedBy.to_json() if self.lastUpdatedBy else None,
            'status': self.status,
            'group': self.group.to_json() if self.group else None,
            'student': self.student.to_json() if self.student else None,
        }

class GroupEvent(models.Model):
    created = models.DateTimeField(null=True, default=timezone.now)
    lastUpdated = models.DateTimeField(null=True, default=timezone.now)
    status = models.IntegerField(null=True)

    createdBy = models.ForeignKey(
        'Person',
        on_delete=models.SET_NULL,
        null=True,
        related_name='created_events'
    )
    lastUpdatedBy = models.ForeignKey(
        'Person',
        on_delete=models.SET_NULL,
        null=True,
        related_name='updated_events'
    )

    group = models.ForeignKey('Group', on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return f"GroupEvent {self.pk}"

    def to_json(self):
        return {
            'id': self.pk,
            'created': self.created.isoformat() if self.created else None,
            'lastUpdated': self.lastUpdated.isoformat() if self.lastUpdated else None,
            'status': self.status,
            'createdBy': self.createdBy.to_json() if self.createdBy else None,
            'lastUpdatedBy': self.lastUpdatedBy.to_json() if self.lastUpdatedBy else None,
            'group': self.group.to_json() if self.group else None,
        }

class StudentAttendance(models.Model):
    createdBy = models.IntegerField()
    created = models.DateTimeField(default=timezone.now)
    lastUpdated = models.DateTimeField(default=timezone.now)
    lastUpdatedBy = models.IntegerField()
    status = models.IntegerField()
    groupEvent = models.ForeignKey('GroupEvent', on_delete=models.CASCADE)
    student = models.ForeignKey('Person', on_delete=models.CASCADE)

    def to_json(self):
        return {
            'id': self.pk,
            'createdBy': self.createdBy,
            'created': self.created.isoformat(),
            'lastUpdated': self.lastUpdated.isoformat(),
            'lastUpdatedBy': self.lastUpdatedBy,
            'status': self.status,
            'groupEvent': self.groupEvent.to_json() if self.groupEvent else None,
            'student': self.student.to_json() if self.student else None,
        }

class Purchase(models.Model):
    createdBy = models.ForeignKey(
        'Person', on_delete=models.CASCADE, related_name='purchases_created', null=True)
    created = models.DateTimeField(null=True, default=timezone.now)
    lastUpdated = models.DateTimeField(null=True, default=timezone.now)
    lastUpdatedBy = models.ForeignKey(
        'Person', on_delete=models.CASCADE, related_name='purchases_updated', null=True)
    status = models.IntegerField(null=True, default=0)
    student = models.ForeignKey(
        'Person', on_delete=models.CASCADE, related_name='purchases')
    amount = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    maxAttendances = models.IntegerField(null=True)
    account = models.ForeignKey('Account', on_delete=models.CASCADE, null=True)
    autoGenerate = models.BooleanField(default=False)

    @property
    def noMoreEventsAllowed(self):
        purchaseAttendances = PurchaseAttendance.objects.filter(purchase=self).filter(
            studentAttendance__status__in=[0, 1])
        return self.maxAttendances <= len(purchaseAttendances)

    @property
    def allPurchaseAttendancesB(self):
        purchaseAttendances = PurchaseAttendance.objects.filter(purchase=self)
        return len(purchaseAttendances)

    @property
    def purchaseAttendancesBillable(self):
        purchaseAttendances = PurchaseAttendance.objects.filter(purchase=self).filter(
            studentAttendance__status__in=[0, 1])
        return len(purchaseAttendances)

    def to_json(self):
        return {
            'id': self.pk,
            'createdBy': self.createdBy.to_json() if self.createdBy else None,
            'created': self.created.isoformat() if self.created else None,
            'lastUpdated': self.lastUpdated.isoformat() if self.lastUpdated else None,
            'lastUpdatedBy': self.lastUpdatedBy.to_json() if self.lastUpdatedBy else None,
            'status': self.status,
            'student': self.student.to_json() if self.student else None,
            'amount': str(self.amount),
            'maxAttendances': self.maxAttendances,
            'account': self.account.to_json() if self.account else None,
            'autoGenerate': self.autoGenerate,
        }

class Payment(models.Model):
    purchase = models.OneToOneField(
        Purchase, on_delete=models.CASCADE, primary_key=True, related_name='payment')
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    created = models.DateTimeField(auto_now_add=True)
    lastUpdated = models.DateTimeField(auto_now=True)
    createdBy = models.ForeignKey(
        'Person', on_delete=models.CASCADE, related_name='payments_created')
    lastUpdatedBy = models.ForeignKey(
        'Person', on_delete=models.CASCADE, related_name='payments_updated')
    account = models.ForeignKey('Account', on_delete=models.CASCADE)
    PAYMENT_TYPES = (
        ('cash', 'Cash'),
        ('credit_card', 'Credit Card'),
        ('cheque', 'Cheque'),
        ('bit', 'Bit'),
    )
    paymentType = models.IntegerField(null=True)
    chequeNumber = models.CharField(max_length=50, blank=True)
    chequeBank = models.CharField(max_length=100, blank=True)
    chequeDate = models.DateTimeField(null=True)
    notes = models.CharField(max_length=2000, blank=True, null=True)

    def to_json(self):
        return {
            'id': self.pk,
            'purchase': self.purchase.to_json(),
            'amount': str(self.amount),
            'created': self.created.isoformat(),
            'lastUpdated': self.lastUpdated.isoformat(),
            'createdBy': self.createdBy.to_json() if self.createdBy else None,
            'lastUpdatedBy': self.lastUpdatedBy.to_json() if self.lastUpdatedBy else None,
            'account': self.account.to_json() if self.account else None,
            'paymentType': self.paymentType,
            'chequeNumber': self.chequeNumber,
            'chequeBank': self.chequeBank,
            'chequeDate': self.chequeDate.isoformat() if self.chequeDate else None,
            'notes': self.notes,
        }

class LookupTable(models.Model):
    code = models.IntegerField(null=True)
    type = models.CharField(max_length=20, null=True)
    value = models.CharField(max_length=20, null=True)
    seq = models.IntegerField(null=True)
    active = models.BooleanField(default=True)
    desc = models.CharField(max_length=2000, null=True)
    lang = models.CharField(max_length=3, null=True)

    class Meta:
        unique_together = [('type', 'code', 'lang')]

    def to_json(self):
        data = {
            'code': self.code,
            'type': self.type,
            'value': self.value,
            'seq': self.seq,
            'active': self.active,
            'desc': self.desc,
            'lang': self.lang,
        }
        return data

    def __str__(self):
        return f"LOV {self.type} {self.value} {self.lang}"

class PurchaseAttendance(models.Model):
    purchase = models.ForeignKey('Purchase', on_delete=models.CASCADE)
    studentAttendance = models.ForeignKey(
        'StudentAttendance', on_delete=models.CASCADE)
    created = models.DateTimeField(default=timezone.now)

    def to_json(self):
        return {
            'id': self.pk,
            'purchase': self.purchase.to_json(),
            'studentAttendance': self.studentAttendance.to_json(),
            'created': self.created.isoformat()
        }


# CENG 487 Assignment3 by
# Mustafa Berkay Özkan
# StudentId: 230201005
# 11 2019

import random

from vec3d import Vec3d

class MeshDeprecated:
    def __init__(self, vertices, triangles):
        self.vertices = vertices
        self.triangles = triangles
        self.color = []
        self.create_colors()
        self.can_subdivide = False

    def create_colors(self):
        for i in range(len(self.triangles)):
            self.color.append(Vec3d(random.randint(0,255),random.randint(0,255),random.randint(0,255)) / 255)


import copy

import numpy as np
import pandas as pd

import optuna

from ..core import Pipeline
from ..validation import CrossValidator

class OptunaHPOptimizer:
    """
    Object for using optuna for optimizing parameters for a model.
    """
    def __init__(self, pipeline: Pipeline, cv: CrossValidator) -> None:
        """
        Initialize the optimizer.

        inputs:
        pipeline: A pipeline object that contains the model whose
                  hyperparameters are to be optimized. The model inside the
                  pipeline should contain the parameters to be optimized.
        """
        self.pipeline = pipeline
        self.cv = cv
        self.study = None
        self.objective = None

        self.create_study()
        self.create_objective()

    def create_study(self) -> None:
        """
        Creates an optuna study for the pipeline named after model.
        """
        study_name = self.pipeline.model.__class__.__name__
        storage_name = "sqlite:///tuning/{}.db".format(study_name)
        direction = self.pipeline.model.metric_direction
        self.study = optuna.create_study(study_name=study_name, storage=storage_name,
                                        load_if_exists=True, direction=direction)

    def create_objective(self)-> None:
        """
        Creates an objective function for the optimizer.
        """
        def objective(trial, X:pd.DataFrame)-> float:

            # Generate parameters for the model
            model_params = {}
            params = copy.deepcopy(self.pipeline.model.hyperparams)
            for param, values in params.items():
                suggestion_generator = getattr(trial, f'suggest_{values.pop("type")}')
                model_params[param] = suggestion_generator(name = param, **values)

            # Set model parameters
            self.pipeline.model.set_params(model_params)

            # Cross validate the model
            X = self.cv.generate_folds(X)
            cv_result = self.cv.cross_validate(self.pipeline, X)

            # Find the value of the relevant metric
            metric = self.pipeline.model.metric_name
            return np.mean(cv_result[metric])

        self.objective = objective

    def optimize(self, X:pd.DataFrame, n_trials: int = 100)->None:
        """
        Run the optimization study.
        """
        self.study.optimize(lambda trial:self.objective(trial, X), n_trials=n_trials)

    def get_best_params(self)-> dict:
        """
        Gets the parameters for the best trial.
        """
        return self.study.best_params


import numpy as np
import torch
from torch.utils.data import Dataset

from src.dataset import brats_labels
from src.dataset.utils import nifi_volume as nifi_utils

class BratsDataset(Dataset):

    def __init__(self, data: list, sampling_method, patch_size: tuple, compute_patch: bool=False, transform=None):
        """
        :param data:
        :param ground_truth:
        :param modalities_to_use:
        :param sampling_method: patching method
        :param patch_size:
        """
        self.data = data
        self.sampling_method = sampling_method
        self.patch_size = patch_size
        self.compute_patch = compute_patch
        self.transform = transform

    def __len__(self):
        return len(self.data)

    def __getitem__(self, idx):

        if torch.is_tensor(idx):
            idx = idx.tolist()

        modalities = self.data[idx].load_mri_volumes(normalize=True)
        brain_mask = self.data[idx].get_brain_mask()

        segmentation_mask = self.data[idx].load_gt_mask()

        segmentation_mask = brats_labels.convert_from_brats_labels(segmentation_mask)

        if self.transform:
            modalities, segmentation_mask, brain_mask = self.transform((modalities, segmentation_mask, brain_mask))

        if self.compute_patch:
            modalities, segmentation_mask = self.sampling_method.patching(modalities, segmentation_mask,
                                                                          self.patch_size, brain_mask)

        modalities = torch.from_numpy(modalities.astype(float))
        segmentation_mask = torch.from_numpy(segmentation_mask.astype(int))

        return modalities, segmentation_mask

    def get_patient_info(self, idx):
        return {attr[0]: attr[1] for attr in vars(self.data[idx]).items()}


from utils import *
import os
import json
import pickle
import joblib
import pandas as pd
from flask import Flask, jsonify, request
from peewee import (
    Model, IntegerField, FloatField,
    TextField, IntegrityError
)
from playhouse.shortcuts import model_to_dict
from playhouse.db_url import connect
from uuid import uuid4

baseline_columns = [
"race",
"gender",
"age",
"weight",
"time_in_hospital",
"medical_specialty",
"has_prosthesis",
"num_procedures",
"number_outpatient",
"number_emergency",
"number_inpatient",
"number_diagnoses",
"blood_type",
"hemoglobin_level",
"blood_transfusion",
"diuretics", "insulin", "change", "diabetesMed", "readmitted"]

from sklearn.base import BaseEstimator, TransformerMixin
class CustomTransformer(BaseEstimator, TransformerMixin):
    def fit(self, X, y=None):
        return self
    def transform(self, X, y=None):
        Xdata = X.copy()
        cols = baseline_columns.copy()
        cols.remove("readmitted")
        return Xdata[cols]

########################################
# Begin database stuff

# The connect function checks if there is a DATABASE_URL env var.
# If it exists, it uses it to connect to a remote postgres db.
# Otherwise, it connects to a local sqlite db stored in predictions.db.
DB = connect(os.environ.get('DATABASE_URL') or 'sqlite:///predictions.db')
#DB = connect('sqlite:///predictions.db')

class Prediction(Model):
    #observation_id = IntegerField(unique=True)
    admission_id = IntegerField(unique=True)
    observation_data = TextField()
    #proba = FloatField()
    predicted_readmitted = TextField()
    actual_readmitted = TextField(null=True)

    class Meta:
        database = DB

DB.create_tables([Prediction], safe=True)

# End database stuff
########################################

########################################
# Unpickle the previously-trained model

with open('columns.json') as fh:
    columns = json.load(fh)

pipeline = joblib.load('pipeline.pickle')

with open('dtypes.pickle', 'rb') as fh:
    dtypes = pickle.load(fh)

# End model un-pickling
########################################

########################################
# Begin webserver stuff

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():

    obs_dict = request.get_json()

    try:
        _id = obs_dict['admission_id']
    except:
        _id = None
        error = 'Missing admission_id.'
        return jsonify({"admission_id":_id,"error":error})

    try:
        #observation = obs_dict['data']
        observation = obs_dict
        #del observation['admission_id']
        #test = list(observation.keys())[0]
    except:
        #changed
        error = 'No observation data.'
        return jsonify({"admission_id":_id, "error": error})

    #implement the mapping for the valid values

    valid_category_map = {
                "admission_id":int() ,
                "patient_id":int(),
                "race": ['White','Caucasian','European','AfricanAmerican','EURO','Afro American','?','African American','WHITE','Asian','Black','Hispanic','Other','Latino','AFRICANAMERICAN'],
                "gender":['Male','Female','Unknown/Invalid'],
                "age": ['[0-10)','[10-20)','[20-30)','[30-40)','[40-50)','[50-60)','[60-70)','[70-80)','[80-90)','[90-100)', None],
                "weight": ['?', None,'[50-75)','[25-50)','[75-100)','[125-150)','[100-125)','[0-25)','[150-175)','[175-200)'],
                "admission_type_code": [ 3. , 6. , 2. , 1. , 5. , 8. ,None, 4. , 7.],
                "discharge_disposition_code": [ 1. ,25. ,6. ,11. ,2. ,14. ,3. ,5. ,None, 18. ,4. ,13. ,22. ,24. ,8. ,23. ,7. ,28. ,15. ,16. ,9.],
                "admission_source_code": [ 1 ,17 ,7 ,5 ,6 ,4 ,2 ,20 ,8 ,9 ,3 ,22],
                "time_in_hospital": [2 ,4 ,3 ,6 ,1 ,10 ,9 ,11 ,7 ,8 ,5 ,13 ,14 ,12],
                "payer_code":['?','UN','MC','SP','DM','HM','MD','BC','CM','CP','WC','OG','PO','MP','OT','CH','SI'],
                "medical_specialty":['?','Family/GeneralPractice','InternalMedicine','Surgery-Neuro','Orthopedics-Reconstructive','Pulmonology','Surgery-General','Hematology/Oncology','Gastroenterology','Oncology','Emergency/Trauma','Cardiology','Neurology','Orthopedics','Nephrology','Surgery-Cardiovascular/Thoracic','Urology','Surgery-Vascular','ObstetricsandGynecology','Radiologist','Pediatrics'
                                    ,'Surgery-Cardiovascular','DCPTEAM', 'Podiatry' ,'Psychiatry'
                                    ,'Endocrinology' ,'Psychology' ,'PhysicalMedicineandRehabilitation'
                                    ,'Surgery-Thoracic' ,'Endocrinology-Metabolism' ,'Pediatrics-Endocrinology'
                                    ,'Hematology' ,'Osteopath' ,'Pediatrics-Pulmonology' ,'Otolaryngology'
                                    ,'Obstetrics' ,'Resident' ,'Pediatrics-CriticalCare' ,'Gynecology'
                                    ,'SurgicalSpecialty', 'Radiology' ,'Surgery-Plastic' ,'Hospitalist'
                                    ,'Pathology', 'Surgery-Colon&Rectal' ,'InfectiousDiseases'
                                    ,'Pediatrics-Hematology-Oncology' ,'Surgery-Maxillofacial'
                                    ,'Psychiatry-Child/Adolescent', 'Anesthesiology-Pediatric' ,'Anesthesiology'
                                    ,'PhysicianNotFound' ,'Cardiology-Pediatric' ,'Ophthalmology' ,'Surgeon'
                                    ,'Psychiatry-Addictive' ,'Pediatrics-Neurology'
                                    ,'Obsterics&Gynecology-GynecologicOnco', 'Rheumatology'
                                    ,'AllergyandImmunology'],
                "has_prosthesis": [False,True],
                "complete_vaccination_status":['Complete','Incomplete','None'],
                "num_lab_procedures": [],
                "num_procedures": [1,0,4,3,2,6,5],
                "num_medications": range(1,71),
                "number_outpatient": [ 0 ,2  ,1 , 3 , 6 , 9 , 4 , 7 , 5 ,15 ,22 , 8 ,20 ,18 ,10 ,28 ,12 ,24 ,13 ,11 ,23 ,35 ,19, 25, 14],
                "number_emergency": range(0,23),
                "number_inpatient": range(0,19),
                "diag_1":[],
                "diag_2":[],
                "diag_3":[],
                "number_diagnoses":range(1,17),
                "blood_type": ['A-','O+','A+','B+','O-','AB-','AB+','B-'],
                "hemoglobin_level": range(9, 20),#float
                "blood_transfusion": [True, False],
                "max_glu_serum": ['NONE','>200','None','>300','NORM','Norm'],
                "A1Cresult":['None','>8','>7', 'Norm'],
                "diuretics": ['No', 'Yes'],
                "insulin": ['No', 'Yes'],
                "change":['No','Ch'],
                "diabetesMed":['No', 'Yes']
    }
    for key in observation.keys():
        if key not in valid_category_map.keys():
            error = '{} is not valid input.'.format(key)
            return jsonify({"observation_id":_id,"error":error})

    '''
    for key, valid_categories in valid_category_map.items():
        if key in observation:
            value = observation[key]
            if value not in valid_categories:
                error = "Invalid value provided for {}: {}. Allowed values are: {}".format(
                    key, value, ",".join(["'{}'".format(v) for v in valid_categories]))
                return jsonify({"observation_id":_id,"error":error})
        else:
            error = "Categorical field {} missing".format(key)
            return jsonify({"observation_id":_id,"error":error})
    '''

    obs = pd.DataFrame([observation], columns=columns).astype(dtypes)
    prediction = pipeline.predict(obs)[0]
    #proba = pipeline.predict_proba(obs)[0,1]

    response = dict()
    #response['admission_id'] = _id
    response['readmitted'] = prediction
    #response['prediction'] = bool(prediction)
    #response['probability'] = proba
    p = Prediction(
        admission_id=_id,
        #proba=proba,
        #observation=request.data

        #observation_data=jsonify(observation),
        observation_data=observation,
        predicted_readmitted = prediction
    )
    try:
        print(observation)
        p.save()
    except IntegrityError:
        error_msg = 'Admission ID: "{}" already exists'.format(_id)
        response['error'] = error_msg
        print(error_msg)
        DB.rollback()
    return jsonify(response)

@app.route('/update', methods=['POST'])
def update():
    obs = request.get_json()
    try:
        p = Prediction.get(Prediction.admission_id == obs['admission_id'])
        p.actual_readmitted = obs['readmitted']
        p.save()
        ret_dict = model_to_dict(p)
        del ret_dict['observation_data']
        del ret_dict['id']
        return jsonify(ret_dict)
        #return jsonify(model_to_dict(p))
    except Prediction.DoesNotExist:
        error_msg = 'Admission ID: "{}" does not exist'.format(obs['admission_id'])
        return jsonify({'error': error_msg})

@app.route('/list-db-contents')
def list_db_contents():
    return jsonify([model_to_dict(obs) for obs in Prediction.select()])

# End webserver stuff
########################################

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, port=5000)


import sys
n, r, c = map(int, sys.stdin.readline().split())
target = 0

while True:
    h = 2**(2*(n-1))
    if r >=2**(n-1):
        r -= 2**(n-1)
        target += 2*h
    if c >=2**(n-1):
        c -= 2**(n-1)
        target += h
    n -= 1
    if r == 0 and c == 0:
        break
print(target)

import sys
n = int(sys.stdin.readline())
rem_cnt = sys.stdin.readline()
rem = list(map(int, sys.stdin.readline().split()))
arr = [x for x in range(10) if x not in rem]
a = b = 0
n2 = n - 1
if int(rem_cnt) == 0:
    pass
while True:
    flag = 1
    n2 += 1
    for i in str(n2):
        if int(i) not in arr:
            flag = 0
            break
    if flag == 1:
        a = len(str(n2)) + (n2-n)
        break
n2 = n
while True:
    flag = 1
    n2 -= 1
    for i in str(n2):
        if int(i) not in arr:
            flag = 0
            break
    if flag == 1 or n2 < 0:
        b = len(str(n2)) + (n-n2)
        break
print(min(a, b))

import sys
from collections import deque
def bfs(graph, root):
    visited = []
    queue = deque([root])
    cnt = 0
    while queue:
        n = queue.popleft()
        if n not in visited:
            visited.append(n)
            if n in graph:
                tmp = list(set(graph[n])-set(visited))
                tmp.sort()
                queue += tmp
        cnt += 1
    return cnt

graph = {}
n, m = map(int, sys.stdin.readline().split())
for i in range(m):
    n1, n2 = map(int, sys.stdin.readline().split())
    if n1 not in graph:
        graph[n1] = [n2]
    elif n2 not in graph:
        graph[n2] = [n1]

    if n2 not in graph:
        graph[n2] = [n1]
    elif n1 not in graph:
        graph[n1] = [n2]
ans = []
for i in graph:
    ans.append(bfs(graph, i))
print(min(ans))

import sys
from math import inf
n = int(sys.stdin.readline())
m = int(sys.stdin.readline())

graph = [[inf]*n for x in range(n)]
for i in range(m):
    a, b, c = map(int, sys.stdin.readline().split())
    graph[a-1][b-1] = min(graph[a-1][b-1], c)

for i in range(n):
    graph[i][i] = 0
    for j in range(n):
        for k in range(n):
            graph[j][k] = min(graph[j][k], graph[j][i]+graph[i][k])

for i in graph:
    for j in i:
        if j == inf:
            j = 0
        print(j, end=" ")
    print()

import sys

a, b = map(int, sys.stdin.readline().split())
graph = [[a]*a for x in range(a)]
for i in range(b):
    n1, n2 = map(int, sys.stdin.readline().split())
    graph[n1-1][n2-1] = min(graph[n1-1][n2-1], 1)
    graph[n2-1][n1-1] = min(graph[n2-1][n1-1], 1)
for k in range(a):
    graph[k][k] = 0
for k in range(a):
    for i in range(a):
        for j in range(a):
            graph[i][j] = min(graph[i][j], graph[i][k]+graph[k][j])
minarr = []
for i in graph:
    if sum(i) not in graph:
        minarr.append(sum(i))
    else:
        minarr.append(sum(i)+1)
print(minarr.index(min(minarr))+1)


from machine import I2C, Pin
from time import sleep
from pico_i2c_lcd import I2cLcd

i2c = I2C(0, sda=Pin(20), scl=Pin(21), freq=400000)
print(i2c)
# I2C_ADDR = i2c.scan()[0]
I2C_ADDR = i2c.scan()[0]

print(I2C_ADDR)
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)

while True:
    print(I2C_ADDR)
    lcd.blink_cursor_on()
    for i in range(20):
        lcd.putstr(str(i))
        sleep(0.4)
        lcd.clear()


from django.shortcuts import render, redirect, HttpResponse, Http404
from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import method_decorator
from django.template .context_processors import csrf
from django.views.generic import ListView, DetailView, CreateView, UpdateView, View
from ratelimit.decorators import ratelimit
from .models import *
import json

class IndexView(ListView):
    model = SKU
    context_object_name = 'skus'
    template_name = 'products/index.html'
    paginate_by = 8

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['nodes'] = Category.objects.all()
        context['can_search'] = True
        return context

    def get_queryset(self):
        only_fields = ['product__name', 'product__manufacturer__name', 'batch',]
        queryset = self.model.objects.select_related().only(*only_fields).order_by('-batch__count', '-likes')
        return queryset

class FavouritesView(LoginRequiredMixin, ListView):
    model = SKU
    context_object_name = 'liked_skus'
    template_name = 'products/favourites.html'
    paginate_by = 12

    def get_context_data(self, **kwargs):
        context = super(FavouritesView, self).get_context_data(**kwargs)
        context['can_search'] = True
        context['is_empty'] = not bool(context[self.context_object_name].count())
        return context

    def get_queryset(self):
        user_profile = UserProfile.objects.get(user__id=self.request.user.id)

        only_fields = ['product__name', 'product__manufacturer__name', 'batch',]
        queryset = user_profile.favourites.select_related().only(*only_fields)
        return queryset

class SearchView(ListView):
    model = SKU
    context_object_name = 'skus'
    template_name = 'products/search.html'

    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            self.object_list = self.get_queryset()
            context = self.get_context_data_for_ajax()
            html = render_to_string('products/includes/search-div.html', context)
            return HttpResponse(html)

        return super(SearchView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(SearchView, self).get_context_data(**kwargs)
        context['can_search'] = True
        context['categories'] = Category.objects.only('name').order_by('level')
        context['manufacturers'] = Manufacturer.objects.only('name').order_by('name')
        context['is_empty'] = not bool(context[self.context_object_name].count())
        context['colors'] = sorted([x[1] for x in SKU.COLOR_CHOICES])
        context['expr'] = self.get_expr()
        return context

    def get_context_data_for_ajax(self, **kwargs):
        context = super(SearchView, self).get_context_data(**kwargs)
        context['is_empty'] = not bool(context[self.context_object_name].count())
        context['expr'] = self.get_expr()
        return context

    def get_queryset(self):
        only_fields = ['product__name', 'product__manufacturer__name', 'batch',]
        queryset = self.model.objects.select_related().only(*only_fields)

        try:
            if 'cat' in self.request.GET:
                category = self.request.GET['cat']
                queryset = queryset.filter(product__in=Category.objects.get(name=category).products.only('id'))

            if 'clrs' in self.request.GET:
                colors = json.loads(self.request.GET['clrs'])
                queryset = queryset.filter(color__in=colors)

            if 'manufs' in self.request.GET:
                manufacturers = json.loads(self.request.GET['manufs'])
                queryset = queryset.filter(product__manufacturer__name__in=manufacturers)

            if 'has_wifi' in self.request.GET:
                if self.request.GET['has_wifi']:
                    queryset = queryset.filter(product__has_wifi=True)

            if 'has_bluetooth' in self.request.GET:
                if self.request.GET['has_bluetooth']:
                    queryset = queryset.filter(product__has_bluetooth=True)

            if 'expr' in self.request.GET:
                string = self.get_expr()
                strings = string.split(' ')

                skus = list(queryset)

                for s in strings:
                    skus = list(filter(lambda x: re.search(s, x.product.manufacturer.name +
                                                           ' ' + x.product.name, re.IGNORECASE), skus))

                ids = map(lambda x: x.id, skus)
                queryset = SKU.objects.filter(id__in=ids)
        except:
            queryset = self.model.objects.none()

        return queryset.order_by('-batch__count', '-likes')

    def get_expr(self):
        return self.request.GET.get('expr', None)

    @method_decorator(ratelimit(key='ip', rate='5/s', block=True))
    def dispatch(self, request, *args, **kwargs):
        return super(SearchView, self).dispatch(request, *args, **kwargs)

class ProductView(DetailView):
    model = SKU
    context_object_name = 'sku'
    template_name = 'products/product.html'

    def get_context_data(self, **kwargs):
        context = super(ProductView, self).get_context_data(**kwargs)
        context['can_search'] = False
        context['product'] = self.object.product
        context['comments'] = self.object.comments.select_related().only('owner__user__username').order_by('-time')
        context['is_liked'] = self.is_liked_product()
        context['batch'] = self.object.batch
        return context

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()

        try:
            sku_id = self.kwargs['sku_id']
            obj = queryset.get(id=sku_id)
        except:
            raise Http404()

        return obj

    def is_liked_product(self):
        try:
            user_profile = UserProfile.objects.get(user__id=self.request.user.id)
            return bool(user_profile.favourites.filter(id=self.kwargs['sku_id']))
        except:
            return False

class LikeUpdate(LoginRequiredMixin, UpdateView):
    http_method_names = ['get']
    template_name = 'products/includes/btns.html'

    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            sku_id = int(request.GET['id'])
            sku = SKU.objects.get(id=sku_id)

            action = request.GET['action']
            status = self.get_action_status(action, sku_id)
            batch = sku.batch
            product = sku.product

            context = {'is_liked': status, 'batch': batch, 'product': product}
            html = render_to_string(self.template_name, context)
            return HttpResponse(html)

        raise Http404()

    def get_action_status(self, action, sku_id):
        user_profile = UserProfile.objects.get(user__id=self.request.user.id)
        sku = SKU.objects.get(id=sku_id)
        result = True

        if action == 'lk':
            sku.likes = sku.likes + 1
            user_profile.favourites.add(sku_id)
        else:
            sku.likes = sku.likes - 1
            user_profile.favourites.remove(sku_id)
            result = False

        sku.save()
        user_profile.save()
        return result

    def http_method_not_allowed(self, request, *args, **kwargs):
        raise Http404()

class CommentCreate(LoginRequiredMixin, CreateView):
    model = Comment
    context_object_name = 'comments'
    http_method_names = ['post']
    template_name = 'products/includes/comments.html'
    fields = ['content']

    def post(self, request, *args, **kwargs):
        if request.is_ajax():
            text = request.POST['content']
            sku_id = int(self.kwargs['sku_id'])

            self.create_comment(text, sku_id)

            html = render_to_string(self.template_name, self.get_context_data())
            return HttpResponse(html)

        raise Http404()

    def create_comment(self, text, sku_id):
        user_profile = UserProfile.objects.only('id').get(user__id=self.request.user.id)
        self.sku = SKU.objects.get(id=sku_id)
        self.sku.comments.create(owner=user_profile, content=text)

    def get_context_data(self, **kwargs):
        context ={self.context_object_name: self.get_queryset()}
        return context

    def get_queryset(self):
        only_fields = ['owner__user__username']
        queryset = self.sku.comments.select_related().only(*only_fields).order_by('-time')
        return queryset

    def http_method_not_allowed(self, request, *args, **kwargs):
        raise Http404()

    @method_decorator(ratelimit(key='user', rate='5/m', block=True))
    def dispatch(self, request, *args, **kwargs):
        return super(CommentCreate, self).dispatch(request, *args, **kwargs)

class Payment(LoginRequiredMixin, View):
    http_method_names = ['post',]

    # UPDATE
    def post(self, request, *args, **kwargs):
        prev_cost = int(self.kwargs['cost'])
        sku_id = self.kwargs['sku_id']
        batch = SKU.objects.get(id=sku_id).batch

        if batch.count == 0:
            print('no products')
        elif prev_cost != batch.cost:
            print('product cost changed')
        else:
            batch.count = batch.count - 1
            batch.save()

        redirect_url = '/product/id' + sku_id
        return redirect(redirect_url)

    def http_method_not_allowed(self, request, *args, **kwargs):
        raise Http404()