import os.path
import datetime
import pickle
import tkinter as tk
import cv2
from PIL import Image, ImageTk
import face_recognition
import os
import objectTracking
import util
import cv2
from gaze_tracking import GazeTracking
import numpy as np
import matplotlib.pyplot as plt
import example
import threading
#from test import test
import facialexp
import cv2
import mediapipe as mp
from onedollar import TrajectoryClasification, OneDollarRecognizer
import head_nodding
import laser_tracker
class App:
    def __init__(self):
        self.main_window = tk.Tk()
        self.main_window.geometry("1200x520+350+100")
        self.ss = False
        self.login_button_main_window = util.get_button(self.main_window, 'login', 'green', self.login)
        self.login_button_main_window.place(x=750, y=100)
        self.x = 0
        self.startss = 0
        self.end = False
        self.blink=0
        self.right=0
        self.left=0
        self.center=0
        self.left_pupil_coordinates = []
        self.right_pupil_coordinates = []
        self.text = 'Not Yet'
        self.left_pupil = None
        self.right_pupil = None
        # self.logout_button_main_window = util.get_button(self.main_window, 'logout', 'red', self.logout)
        # self.logout_button_main_window.place(x=750, y=200)
        self.font = cv2.FONT_HERSHEY_SIMPLEX
        self.text_position = (10, 50)  # (x, y) coordinates of the text start point
        self.font_scale = 1
        self.font_color = (255, 0, 0)  # BGR color; (255, 0, 0) is blue
        self.state_color = (0,255,0)
        self.line_type = 2
        self.register_new_user_button_main_window = util.get_button(self.main_window, 'Register new user', 'gray',
                                                                    self.register_new_user, fg='black')
        self.register_new_user_button_main_window.place(x=750, y=300)

        self.webcam_label = util.get_img_label(self.main_window)
        self.webcam_label.place(x=10, y=0, width=700, height=500)

        self.add_webcam(self.webcam_label)

        self.db_dir = './db'
        if not os.path.exists(self.db_dir):
            os.mkdir(self.db_dir)

        self.log_path = './log.txt'

        self.FRAME_SKIP = 70
        self.head_tracker = TrajectoryClasification(OneDollarRecognizer())
        self.alarm = False
        # Initialize Mediapipe face detection and landmark models
        self.mp_face_detection = mp.solutions.face_detection
        self.mp_drawing = mp.solutions.drawing_utils
        self.mp_face_mesh = mp.solutions.face_mesh

        # Initialize variables
        self.frame_count = 0
        self.type_of_movement = None
        self.confidence = 0
        self.Pos = 'None'
        self.facexp = 'None'
        self.errors= 0

    def add_webcam(self, label):
        if 'cap' not in self.__dict__:
            self.cap = cv2.VideoCapture(0)

        self._label = label
        self.process_webcam()

    def headturn(self):
        # Number of frame2s to skip before adding nose point to the list
        frame2_SKIP = 70
        head_tracker = TrajectoryClasification(OneDollarRecognizer())

        # Initialize Mediapipe face detection and landmark models
        mp_face_detection = mp.solutions.face_detection
        mp_drawing = mp.solutions.drawing_utils
        mp_face_mesh = mp.solutions.face_mesh

        # Initialize variables
        frame2_count = 0
        type_of_movement = None
        confidence = 0

        # Start cap2turing video from default camera

        # Initialize face detection and landmark models
        with mp_face_detection.FaceDetection(min_detection_confidence=0.5) as face_detection, \
                mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) as face_mesh:

            while True:
                # Read a frame2 from the video cap2ture
                ret2, frame2 = self.cap.read()
                if not ret2:
                    break

                # Convert the BGR frame2 to RGB
                frame2_rgb = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB)

                # Process the frame2 with face detection
                results_detection = face_detection.process(frame2_rgb)

                # Check if any faces are detected
                if results_detection.detections:
                    for detection in results_detection.detections:
                        # Extract the face landmarks
                        face_landmarks = face_mesh.process(frame2_rgb)

                        # Check if face landmarks are available
                        if face_landmarks.multi_face_landmarks:
                            for face_landmark in face_landmarks.multi_face_landmarks:
                                # Draw the face landmarks on the frame2
                                mp_drawing.draw_landmarks(
                                    frame2, face_landmark, mp_face_mesh.FACEMESH_CONTOURS)

                                # Extract the nose landmark (landmark index 4)
                                nose_landmark = face_landmark.landmark[4]
                                nose_x = int(nose_landmark.x * frame2.shape[1])
                                nose_y = int(nose_landmark.y * frame2.shape[0])

                                # Append the nose point to the list every 70 frame2s
                                frame2_count += 1
                                head_tracker.append_to_list((nose_x, nose_y))
                                if frame2_count % frame2_SKIP == 0:
                                    # Call dollarpy
                                    type_of_movement, confidence = head_tracker.trajectoryType()
                                    head_tracker.resetPoints()
                if type_of_movement == "yes" and confidence>0.25:
                    cv2.putText(frame2, "Turn off alarm YES", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
                    cv2.destroyAllWindows()
                    return frame2
                if type_of_movement == "no" and confidence>0.5:
                    cv2.putText(frame2, "NO", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
                    #ret2urn "no"
                cv2.putText(frame2, "Type of movement: " + str(type_of_movement) + " Confidence: " + str(confidence), (10, 10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))

                # Show the frame2 with landmarks
                cv2.imshow('Facial Landmarks', frame2)

                # Exit the loop if 'q' is pressed
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

        # Release the video cap2ture and close all windows
        #cap2.release()
        cv2.destroyAllWindows()

    def process_webcam(self):
        if not self.end:
            ret, frame = self.cap.read()
            if self.ss:
                if self.startss % 100 == 0 and not self.alarm:
                    self.x = objectTracking.main(frame)
                    self.text,self.blink,self.right,self.left,self.center,self.left_pupil,self.right_pupil=example.gazetrack(self.blink,self.right,self.left,self.center,frame)
                    self.Pos = laser_tracker.laser_tracker(frame)
                    self.facexp = facialexp.facialexp(frame)
                    if self.facexp=='sad' or self.facexp == 'angry' or self.facexp=='fear':
                        if self.facexp:
                            self.state_color = (0,0,255)
                            self.alarm = True
                            self.errors+=1
                    if self.left_pupil != None and self.right_pupil != None:
                        self.left_pupil_coordinates.append((self.left_pupil[0], self.left_pupil[1]))
                        self.right_pupil_coordinates.append((self.right_pupil[0], self.right_pupil[1]))

                self.startss += 1

                cv2.putText(frame,'Persons: ' + str(self.x), self.text_position, self.font, self.font_scale, self.font_color, self.line_type)
                cv2.putText(frame,'Position: ' + str(self.Pos), (10, 100), self.font, self.font_scale, self.font_color, self.line_type)
                cv2.putText(frame,str(self.text), (400,50), self.font, self.font_scale, self.font_color, self.line_type)
                cv2.putText(frame,str(self.facexp), (250,50), self.font, self.font_scale, self.state_color, self.line_type)

                #cv2.imshow('Webcam Feed', frame)
                #cv2.waitKey(1)
            # print('frame: ', frame)
            self.most_recent_capture_arr = frame
            # print('most_recent_capture_arr: ', self.most_recent_capture_arr)

            img_ = cv2.cvtColor(self.most_recent_capture_arr, cv2.COLOR_BGR2RGB)
            self.most_recent_capture_pil = Image.fromarray(img_)
            imgtk = ImageTk.PhotoImage(image=self.most_recent_capture_pil)
            self._label.imgtk = imgtk
            self._label.configure(image=imgtk)
            try:
                if self.alarm:
                        backupframe = np.copy(frame)
                        self.headturn()
                        self.alarm=False
                        self.state_color=(0,255,0)
                        frame = backupframe
            except:
                pass
            self._label.after(20, self.process_webcam)

    def login(self):

        name = util.recognize(self.most_recent_capture_arr,self.db_dir)
        if name == 'unknown_person' or name == 'no_persons_found':
            util.msg_box('Failed','Unknown user')
        else:
            filename = 'users/{}.txt'.format(name)
            util.msg_box('Welcome Back', 'Welcome, {}.'.format(name))
            with open(filename, 'r') as file:
                content = file.read()
                print(content[-1])
            self.loginuser_window = tk.Toplevel(self.main_window)
            self.loginuser_window.geometry("520x520+370+120")
            self.start_rideb = util.get_button(self.loginuser_window, 'Start Ride', 'Green', self.startride)
            self.start_rideb.place(x=100, y=100)
            if int(content[-1]) == 1:
                self.update_userb = util.get_button(self.loginuser_window, 'Update User', 'Blue', self.update_user)
                self.update_userb.place(x=100, y=200)

                self.delete_userb = util.get_button(self.loginuser_window, 'Delete User', 'red', self.delete_user)
                self.delete_userb.place(x=100, y=300)

                # os.remove(unknown_img_path)
        with open(self.log_path, 'a') as f:
            f.write('{},{},in\n'.format(name, datetime.datetime.now()))
            f.close()
    def startride(self):
        self.starride = tk.Toplevel(self.main_window)
        self.starride.geometry("1200x520+350+100")
        self.webcam_label = util.get_img_label(self.starride)
        self.webcam_label.place(x=10, y=0, width=700, height=500)
        self.add_webcam(self.webcam_label)
        self.endrideb = util.get_button(self.starride, 'End Ride', 'red', self.endride)
        self.endrideb.place(x=750, y=300)

        self.ss = True
        # self.login_button_main_window = util.get_button(self.starride, 'login', 'green', self.login)
        # self.login_button_main_window.place(x=750, y=100)

        # # self.logout_button_main_window = util.get_button(self.main_window, 'logout', 'red', self.logout)
        # # self.logout_button_main_window.place(x=750, y=200)

        # self.register_new_user_button_main_window = util.get_button(self.starride, 'Register new user', 'gray',
        #                                                             self.register_new_user, fg='black')
        # self.register_new_user_button_main_window.place(x=750, y=300)

        # self.webcam_label = util.get_img_label(self.starride)
        # self.webcam_label.place(x=10, y=0, width=700, height=500)

        # self.add_webcam(self.webcam_label)
        #self.main_window.destroy()
    def endride(self):
        self.end = True
        self.left_pupil_coordinates = np.array(self.left_pupil_coordinates)
        self.right_pupil_coordinates = np.array(self.right_pupil_coordinates)

        # Generate a heatmap for the left and right pupil coordinates
        heatmap_left, xedges_left, yedges_left = np.histogram2d(self.left_pupil_coordinates[:, 1], self.left_pupil_coordinates[:, 0], bins=50)
        heatmap_right, xedges_right, yedges_right = np.histogram2d(self.right_pupil_coordinates[:, 1], self.right_pupil_coordinates[:, 0], bins=50)

        # Create a meshgrid from the histogram bin edges
        X_left, Y_left = np.meshgrid(xedges_left, yedges_left)
        X_right, Y_right = np.meshgrid(xedges_right, yedges_right)

        # Plot the left pupil heatmap
        plt.figure()
        plt.imshow(heatmap_left.T, origin='lower', extent=[xedges_left[0], xedges_left[-1], yedges_left[0], yedges_left[-1]])
        plt.colorbar()
        plt.title('Left Pupil Heatmap')
        plt.xlabel('X Coordinate')
        plt.ylabel('Y Coordinate')
        plt.show()

        # Plot the right pupil heatmap
        plt.figure()
        plt.imshow(heatmap_right.T, origin='lower', extent=[xedges_right[0], xedges_right[-1], yedges_right[0], yedges_right[-1]])
        plt.colorbar()
        plt.title('Right Pupil Heatmap')
        plt.xlabel('X Coordinate')
        plt.ylabel('Y Coordinate')
        plt.show()

        tot=self.blink+self.right+self.left+self.center
        blinkp=(self.blink/tot)*100
        rightp=(self.right/tot)*100
        leftp=(self.left/tot)*100
        centerp=(self.center/tot)*100
        # text_file = open(chosentxt, "w")
        # text_file.write(my_text_box.get(1.0, END))
        # text_file.close()

        with open("output.txt","w+") as file:
            file.write(f'You spent { str(blinkp)} % of your ride blinking \n')
            file.write(f'You spent { str(rightp)} % of your ride looking at the right \n')
            file.write(f'You spent { str(leftp)} % of your ride looking at the left \n')
            file.write(f'You spent { str(centerp)} % of your ride looking at the center \n')
            file.write(f' { str(self.errors)} Errors were made during the ride \n')
            print(str(blinkp))
        cv2.destroyAllWindows()
        self.main_window.destroy()
        self.starride.destroy()

    def delete_user(self):
        self.delete_user_window = tk.Toplevel(self.main_window)
        self.delete_user_window.geometry("520x520+370+120")
        self.loginuser_window.destroy()
        self.deletelabel = util.get_text_label(self.delete_user_window, 'Username:')
        self.deletelabel.place(x=100, y=20)
        self.delete_text = util.get_entry_text(self.delete_user_window)
        self.delete_text.place(x=100, y=55)
        self.delete_button = util.get_button(self.delete_user_window, 'Delete User', 'Red', self.confirm_delete)
        self.delete_button.place(x=100, y=365)
    def confirm_delete(self):
        name = self.delete_text.get(1.0, "end-1c")
        if name:
            filename = 'users/{}.txt'.format(name)
            picklefilename = 'db/{}.pickle'.format(name)
            if os.path.exists(filename):
                os.remove(filename)
                os.remove(picklefilename)
                util.msg_box('Success!', 'User was deleted successfully !')
    def update_user(self):

        self.update_user_window = tk.Toplevel(self.main_window)
        self.update_user_window.geometry("520x520+370+120")
        self.loginuser_window.destroy()
        self.text_label_register_upload_user = util.get_text_label(self.update_user_window, 'Username:')
        self.text_label_register_upload_user.place(x=100, y=20)
        self.entry_text_register_upload_user = util.get_entry_text(self.update_user_window)
        self.entry_text_register_upload_user.place(x=100, y=55)

        self.text_label_register_upload_user1 = util.get_text_label(self.update_user_window, 'Seat Level:')
        self.text_label_register_upload_user1.place(x=100, y=90)
        self.entry_text_register_upload_user1 = util.get_entry_text(self.update_user_window)
        self.entry_text_register_upload_user1.place(x=100, y=125)

        self.text_label_register_upload_user2 = util.get_text_label(self.update_user_window, 'Volume Level:')
        self.text_label_register_upload_user2.place(x=100, y=160)
        self.entry_text_register_upload_user2 = util.get_entry_text(self.update_user_window)
        self.entry_text_register_upload_user2.place(x=100, y=195)

        self.text_label_register_upload_user3 = util.get_text_label(self.update_user_window, 'Position:')
        self.text_label_register_upload_user3.place(x=100, y=230)
        self.entry_text_register_upload_user3 = util.get_entry_text(self.update_user_window)
        self.entry_text_register_upload_user3.place(x=100, y=265)

        self.update_user_button = util.get_button(self.update_user_window, 'Update User', 'Blue', self.confirm_update)
        self.update_user_button.place(x=100, y=365)
    def confirm_update(self):
        alles = []
        name = self.entry_text_register_upload_user.get(1.0, "end-1c")
        SeatLevel = self.entry_text_register_upload_user1.get(1.0, "end-1c")
        VolumeLevel = self.entry_text_register_upload_user2.get(1.0, "end-1c")
        Position = self.entry_text_register_upload_user3.get(1.0, "end-1c")

        if name and SeatLevel and VolumeLevel and Position:

            filename = 'users/{}.txt'.format(name)
            if os.path.exists(filename):
                if SeatLevel.isdigit() and VolumeLevel.isdigit() and Position.isdigit():
                    if Position == '0' or Position =='1':
                        alles.append(name)
                        alles.append(SeatLevel)
                        alles.append(VolumeLevel)
                        alles.append(Position)
                        joined = ','.join(alles)
                        try:
                            with open(filename, 'w') as file:
                                file.write(joined)
                        except Exception as e:
                            print(f"An error occurred: {e}")

                        util.msg_box('Success!', 'User was Updated successfully !')
                        self.update_user_window.destroy()
                    else:
                        util.msg_box('Error!', 'Invalid position')

                else:
                    util.msg_box('Error!', 'Only integer values for seat and volume level are allowed!')
            else:
                util.msg_box('Error!', 'No such user')

        else:
            util.msg_box('Error', 'No empty fields allowed')

    # def logout(self):

    #     # label = test(
    #     #         image=self.most_recent_capture_arr,
    #     #         model_dir='/home/phillip/Desktop/todays_tutorial/27_face_recognition_spoofing/code/face-attendance-system/Silent-Face-Anti-Spoofing/resources/anti_spoof_models',
    #     #         device_id=0
    #     #         )

    #     # if label == 1:

    #     name = util.recognize(self.most_recent_capture_arr, self.db_dir)

    #     if name == 'unknown_person' or name == 'no_persons_found':
    #         util.msg_box('Failed', 'Unknown user. Please register new user or try again.')
    #     else:
    #         util.msg_box('Logout', 'Goodbye, {}.'.format(name))
    #         with open(self.log_path, 'a') as f:
    #             f.write('{},{},out\n'.format(name, datetime.datetime.now()))
    #             f.close()

    #     # else:
    #     #     util.msg_box('Hey, you are a spoofer!', 'You are fake !')

    def register_new_user(self):
        self.register_new_user_window = tk.Toplevel(self.main_window)
        self.register_new_user_window.geometry("1200x520+370+120")

        self.accept_button_register_new_user_window = util.get_button(self.register_new_user_window, 'Add', 'green', self.accept_register_new_user)
        self.accept_button_register_new_user_window.place(x=750, y=300)

        self.try_again_button_register_new_user_window = util.get_button(self.register_new_user_window, 'New Photo', 'red', self.try_again_register_new_user)
        self.try_again_button_register_new_user_window.place(x=750, y=400)

        self.capture_label = util.get_img_label(self.register_new_user_window)
        self.capture_label.place(x=10, y=0, width=700, height=500)

        self.add_img_to_label(self.capture_label)

        self.text_label_register_new_user = util.get_text_label(self.register_new_user_window, 'Username:')
        self.text_label_register_new_user.place(x=750, y=20)
        self.entry_text_register_new_user = util.get_entry_text(self.register_new_user_window)
        self.entry_text_register_new_user.place(x=750, y=55)

        self.text_label_register_new_user1 = util.get_text_label(self.register_new_user_window, 'Seat Level:')
        self.text_label_register_new_user1.place(x=750, y=90)
        self.entry_text_register_new_user1 = util.get_entry_text(self.register_new_user_window)
        self.entry_text_register_new_user1.place(x=750, y=125)

        self.text_label_register_new_user2 = util.get_text_label(self.register_new_user_window, 'Volume Level:')
        self.text_label_register_new_user2.place(x=750, y=160)
        self.entry_text_register_new_user2 = util.get_entry_text(self.register_new_user_window)
        self.entry_text_register_new_user2.place(x=750, y=195)

        # self.text_label_register_new_user = util.get_text_label(self.register_new_user_window, 'Please, \nSeat Level:')
        # self.text_label_register_new_user.place(x=750, y=70)

    def try_again_register_new_user(self):
        self.register_new_user_window.destroy()

    def add_img_to_label(self, label):
        imgtk = ImageTk.PhotoImage(image=self.most_recent_capture_pil)
        label.imgtk = imgtk
        label.configure(image=imgtk)

        self.register_new_user_capture = self.most_recent_capture_arr.copy()

    def start(self):
        self.main_window.mainloop()

    def accept_register_new_user(self):
        name = self.entry_text_register_new_user.get(1.0, "end-1c")
        SeatLevel = self.entry_text_register_new_user1.get(1.0, "end-1c")
        VolumeLevel = self.entry_text_register_new_user2.get(1.0, "end-1c")
        namecheck = util.recognize(self.most_recent_capture_arr,self.db_dir)
        if namecheck == 'unknown_person' or namecheck=='no_persons_found':
            if name and SeatLevel and VolumeLevel:

                filename = 'users/{}.txt'.format(name)
                if os.path.exists(filename):
                    util.msg_box('User exists',f"User '{name}' already exists.")
                    self.register_new_user_window.destroy()
                else:
                    alles = []
                    if SeatLevel.isdigit() and VolumeLevel.isdigit():

                        alles.append(name)
                        alles.append(SeatLevel)
                        alles.append(VolumeLevel)
                        alles.append('0')
                        joined = ','.join(alles)
                        embeddings = face_recognition.face_encodings(self.register_new_user_capture)[0]

                        file = open(os.path.join(self.db_dir, '{}.pickle'.format(name)), 'wb')
                        pickle.dump(embeddings, file)
                        print('joined', joined)
                        with open(filename, 'w') as file:
                            file.write(joined)

                        util.msg_box('Success!', 'User was registered successfully !')
                        self.register_new_user_window.destroy()
                    else:
                        util.msg_box('Error!', 'Only integer values for seat and volume level are allowed!')
            else:
                util.msg_box('Welcome Back', 'Welcome, {}.'.format(name))
        else:
            util.msg_box('Error', '{}, You already exist!'.format(namecheck))
            self.register_new_user_window.destroy()

if __name__ == "__main__":
    app = App()
    app.start()


"""
The map function takes a function, and an iterable,
and returns a new iterable with the function applied
to it.
"""

def add_five(x):
    return x + 5

nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)

nums = [11, 22, 33, 44, 55]

result = list(map(lambda x: x + 5, nums))
print(result)

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

"""
The filter function filters an iterable by removing items
that do not match a predicate.
"""

nums = [11, 22, 33, 44, 55]
result = list(filter(lambda x: x%2==0, nums))
print(result)

SoloLearn Projects/Python/7. Functional Programming/65 Map & Filter/65.1 Lesson.py


import create
import edit
import delete
#MAIN CONDITION
if __name__ == '__main__':
    default_path = "C:/Users/Amito/Desktop/File Manager/"
    a = int(input("Press...\n- (1) to create a new file? \n- (2) to read/write a file \n- (3) to delete a file \n"))
    #CREATE
    if a == 1:
        create.create_file(default_path)
    #EDIT
    if a == 2:
        edit.edit_file()
    #DELETE
    if a == 3:
        delete.delete_file()


from __future__ import annotations

import pathlib
from typing import TYPE_CHECKING, Any

from .. import components, datatypes
from ..error_utils import catch_and_log_exceptions

if TYPE_CHECKING:
    from ..components import MediaType

def guess_media_type(path: str | pathlib.Path) -> MediaType | None:
    from ..components import MediaType

    ext = pathlib.Path(path).suffix.lower()
    if ext == ".glb":
        return MediaType.GLB
    elif ext == ".gltf":
        return MediaType.GLTF
    elif ext == ".obj":
        return MediaType.OBJ
    else:
        return None

class Asset3DExt:
    """Extension for [Asset3D][rerun.archetypes.Asset3D]."""

    def __init__(
        self: Any,
        *,
        path: str | pathlib.Path | None = None,
        contents: components.BlobLike | None = None,
        media_type: datatypes.Utf8Like | None = None,
        transform: datatypes.Transform3DLike | None = None,
    ):
        """
        Create a new instance of the Asset3D archetype.

        Parameters
        ----------
        path:
            A path to an file stored on the local filesystem. Mutually
            exclusive with `contents`.

        contents:
            The contents of the file. Can be a BufferedReader, BytesIO, or
            bytes. Mutually exclusive with `path`.

        media_type:
            The Media Type of the asset.

            For instance:
             * `model/gltf-binary`
             * `model/obj`

            If omitted, it will be guessed from the `path` (if any),
            or the viewer will try to guess from the contents (magic header).
            If the media type cannot be guessed, the viewer won't be able to render the asset.

        transform:
            An out-of-tree transform.

            Applies a transformation to the asset itself without impacting its children.
        """

        with catch_and_log_exceptions(context=self.__class__.__name__):
            if (path is None) == (contents is None):
                raise ValueError("Must provide exactly one of 'path' or 'contents'")

            if path is None:
                blob = contents
            else:
                blob = pathlib.Path(path).read_bytes()
                if media_type is None:
                    media_type = guess_media_type(str(path))

            self.__attrs_init__(blob=blob, media_type=media_type, transform=transform)
            return

        self.__attrs_clear__()


import pandas as pd
import numpy as np
import pickle

with open('data/final_sales_history.pkl', 'rb') as picklefile:
    sales_history = pickle.load(picklefile)

sales_history.head()

## Add a num_sales (frequency) column
sales_history['num_sales'] = sales_history.groupby('shoe_name')['shoe_name'].transform('count')

## Limit everything below this to shoes with over 50 sales recorded
print(len(sales_history))
sales_history = sales_history[sales_history.num_sales > 50]
print(len(sales_history))

# Creates the shoe_info csv for the flask app
info_cols = ['release_date', 'image_url', 'style_code', 'colorway', 'original_retail',
                          'main_color', 'line', 'brand']

sales_history = sales_history.set_index(['name', 'sale_date_time'])
shoe_info = sales_history[info_cols].reset_index()

# number of transactions in last month
shoe_info = shoe_info[shoe_info.sale_date_time > '2017-02-21']
shoe_info['transactions_last_month'] = shoe_info.groupby('name')['name'].transform('count')

# shoe image URL - remove extra stuff at the end
shoe_info.image_url = shoe_info['image_url'].apply(lambda x: x.split('?')[0])
shoe_info = shoe_info.drop('sale_date_time', 1)
shoe_info = shoe_info.drop_duplicates()
print(shoe_info.head())

# send to CSV
shoe_info.to_csv('data/shoe_info.csv', index = False)

# For the historical sales chart
chart_data = sales_history.reset_index()
chart_data = chart_data.set_index('sale_date_time')
chart_data['date'] = chart_data.index.date
chart_data = chart_data.reset_index()
chart_data = chart_data[['name', 'sale_date', 'sale_price']].groupby(['name', 'sale_date'])

chart_data = chart_data.aggregate(['count', 'mean', 'min', 'max']).reset_index()
chart_data.columns = chart_data.columns.droplevel(0)
chart_data = pd.DataFrame(chart_data)

# rename columns for clarity
chart_data.columns = ['name', 'date', 'volume', 'sale_mean', 'sale_min', 'sale_max']
chart_data.sale_mean = chart_data['sale_mean'].apply(lambda x: round(x))

# write to CSV
chart_data.to_csv('data/chart_data.csv', index = False)
print(chart_data.head())


"""Utils for dataintegration plugins."""
import os
import re
from typing import Optional

from cmem.cmempy.workspace.projects.datasets.dataset import post_resource

from cmem_plugin_base.dataintegration.context import UserContext

def generate_id(name: str) -> str:
    """Generates a valid DataIntegration identifier from a string.
    Characters that are not allowed in an identifier are removed.
    """
    return re.sub(r"[^a-zA-Z0-9_-]", "", name)

def setup_cmempy_user_access(context: Optional[UserContext]):
    """Setup environment for accessing CMEM with cmempy."""
    if context is None:
        raise ValueError("No UserContext given.")
    if context.token() is None:
        raise ValueError("UserContext has no token.")
    os.environ["OAUTH_GRANT_TYPE"] = "prefetched_token"
    os.environ["OAUTH_ACCESS_TOKEN"] = context.token()
    if "CMEM_BASE_URI" not in os.environ:
        os.environ["CMEM_BASE_URI"] = os.environ["DEPLOY_BASE_URL"]

def setup_cmempy_super_user_access():
    """Setup environment for accessing CMEM with cmempy.

    The helper function is used to setup the environment for accessing CMEM with cmempy.
    It does nothing if there is already a working environment.
    If not, it will try to use the configured DI environment.
    """
    try:
        os.environ["OAUTH_GRANT_TYPE"] = "client_credentials"
        if "CMEM_BASE_URI" not in os.environ:
            os.environ["CMEM_BASE_URI"] = os.environ["DEPLOY_BASE_URL"]
        if "OAUTH_CLIENT_ID" not in os.environ:
            os.environ["OAUTH_CLIENT_ID"] = os.environ[
                "DATAINTEGRATION_CMEM_SERVICE_CLIENT"
            ]
        if "OAUTH_CLIENT_SECRET" not in os.environ:
            os.environ["OAUTH_CLIENT_SECRET"] = os.environ[
                "DATAINTEGRATION_CMEM_SERVICE_CLIENT_SECRET"
            ]
    except KeyError as error:
        raise ValueError("Super user configuration not available.") from error

def split_task_id(task_id: str) -> tuple:
    """Split a combined task ID.

    Args:
        task_id (str): The combined task ID.

    Returns:
        The project and task ID

    Raises:
        ValueError: in case the task ID is not splittable
    """
    try:
        project_part = task_id.split(":")[0]
        task_part = task_id.split(":")[1]
    except IndexError as error:
        raise ValueError(f"{task_id} is not a valid task ID.") from error
    return project_part, task_part

def write_to_dataset(
    dataset_id: str, file_resource=None, context: Optional[UserContext] = None
):
    """Write to a dataset.

    Args:
        dataset_id (str): The combined task ID.
        file_resource (file stream): Already opened byte file stream
        context (UserContext):
            The user context to setup environment for accessing CMEM with cmempy.

    Returns:
        requests.Response object

    Raises:
        ValueError: in case the task ID is not splittable
        ValueError: missing parameter
    """
    setup_cmempy_user_access(context=context)
    project_id, task_id = split_task_id(dataset_id)

    return post_resource(
        project_id=project_id,
        dataset_id=task_id,
        file_resource=file_resource,
    )


def is_trap(row, pos):
    return (pos - 1 >= 0 and row[pos - 1]) != (pos + 1 < len(row) and row[pos + 1])

def answer(first_row, n):
    row = [(c == "^") for c in first_row]
    count = row.count(False)
    for i in range(1, n):  # Generate row #i
        row = [is_trap(row, j) for j in range(len(row))]
        count += row.count(False)
    return count

if __name__ == "__main__":
    r = open("input.txt", "rt").read().strip()
    print("Part 1: %d" % (answer(r, 40),))
    print("Part 2: %d" % (answer(r, 400000),))


# -------------------------------------------------------------------------
# * A Monte Carlo simulation of Buffon's needle experiment.
# *
# * Name              : buffon.c
# * Author            : Steve Park & Dave Geyer
# * Language          : ANSI C
# * Latest Revision   : 9-11-98
#   Translated by   : Philip Steele
#   Language        : Python 3.3
#   Latest Revision : 3/26/14
# * -------------------------------------------------------------------------
# */

from rng import random, putSeed, getSeed
from math import cos, atan

N =      10000                      # number of replications */
HALF_PI =(2.0 * atan(1.0))          # 1.5707963...           */
R   =    1.0                        # length of the needle   */

def Uniform(a,b):
# --------------------------------------------
# * generate a Uniform random variate, use a < b
# * --------------------------------------------
# */
  return (a + (b - a) * random())

################################Main Program#############################

putSeed(-1)                   # any negative integer will do      */
seed = getSeed()              # trap the value of the intial seed */
crosses = 0                   # tracks number of crosses

for i in range(0,N):
  u     = random() #get first endpoint
  theta = Uniform(-HALF_PI, HALF_PI) #get Angle
  v     = u + R * cos(theta) #get second endpoint
  if (v > 1.0):
    crosses += 1 #increase number of crosses

p = float(crosses / N)                # estimate the probability */

print("\nbased on {0:1d} replications and a needle of length {1:5.2f}".format(N, R))
print("with an initial seed of {0:1d}".format(seed))
print("the estimated probability of a cross is {0:5.3f}".format(p))

#C output:
# based on 10000 replications and a needle of length  1.00
# with an initial seed of 1396907952
# the estimated probability of a cross is 0.640


lista = []
while True:
    num = int(input('Digite um número: '))
    lista.append(num)
    resp = str(input('Quer continuar? [S/N] ')).strip().upper()
    if resp in 'Nn':
        break
lista.sort(reverse=True)
print(f'Foram digitados {len(lista)} números.')
print(f'Lista de valores na ordem decrescente: {lista}')
if 5 in lista:
    print('O valor 5 está na lista.')
else:
    print('O valor 5 não está na lista.')


# HomeMode class: home screen that allows user to navigate through the game

from cmu_112_graphics import *

# HomeMode class
class HomeMode(Mode):
    def appStarted(mode):
        mode.initButtonDimensions()
        mode.initBackground()

    # button dimensions
    def initButtonDimensions(mode):
        mode.buttonCoords = []
        numberOfButtons = 3
        width = 100
        height = 50
        margin = 20
        sideOffset = mode.width / 2 - width / 2 - margin - width
        topOffset = mode.height / 2
        for i in range(numberOfButtons):
            bx0 = sideOffset + i * width + margin * i
            bx1 = bx0 + width
            by0 = topOffset
            by1 = topOffset + height
            mode.buttonCoords.append((bx0, bx1, by0, by1))
        width = 50
        height = 20
        bx1 = mode.width - 20
        bx0 = bx1 - width
        by1 = mode.height - 20
        by0 = by1 - width
        mode.buttonCoords.append((bx0, bx1, by0, by1))
        mode.buttonText = ['Play', 'Create', 'Scores', 'Help']
        mode.buttonModes = [mode.app.PlayMode, mode.app.CreateMode, mode.app.ScoreMode, mode.app.HelpMode]

    def keyPressed(mode, event):
        if event.key == 'p':
            mode.app.setActiveMode(mode.app.PlayMode)
        elif event.key == 's':
            mode.app.setActiveMode(mode.app.ScoreMode)
        elif event.key == 'c':
            mode.app.setActiveMode(mode.app.CreateMode)

    def mousePressed(mode, event):
        x, y = event.x, event.y
        mode.checkPressedButtons(x, y)

    # check if buttons are pressed
    def checkPressedButtons(mode, x, y):
        for i in range(len(mode.buttonCoords)):
            bx0, bx1, by0, by1 = mode.buttonCoords[i]
            if bx0 < x < bx1 and by0 < y < by1:
                mode.app.setActiveMode(mode.buttonModes[i])

    # draw buttons
    def drawButtons(mode, canvas):
        for i in range(len(mode.buttonCoords)):
            bx0, bx1, by0, by1 = mode.buttonCoords[i]
            if i != 3:
                canvas.create_rectangle(bx0, by0, bx1, by1, fill='black', outline='white', width=4)
                style = 'System 24 bold'
            else:
                style = 'System 18 bold'
            textX, textY = (bx0 + bx1) / 2, (by0 + by1) / 2
            canvas.create_text(textX, textY, text=mode.buttonText[i], font=style, fill='white')

    # retreive background image
    def initBackground(mode):
        # image from https://www.mobilebeat.com/wp-content/uploads/2016/07/Background-Music-768x576-1280x720.jpg
        mode.background = mode.scaleImage(mode.loadImage("pictures/homebackground.png"), 1/2)

    # draw background
    def drawBackground(mode, canvas):
        canvas.create_image(mode.width / 2, mode.height / 2, image=ImageTk.PhotoImage(mode.background))

    def redrawAll(mode, canvas):
        canvas.create_rectangle(0, 0, mode.width, mode.height, fill='black')
        mode.drawBackground(canvas)
        canvas.create_text(mode.width / 2, mode.height / 3,
                           text='Rhythm Keys!', fill='white', font='System 48 bold')
        mode.drawButtons(canvas)


from hqca.core import *
from functools import reduce
import sys
from copy import deepcopy as copy
from hqca.tools import *
from hqca.operators import *
import numpy as np
from pyscf import gto,mcscf,scf
import timeit
from timeit import default_timer as dt

class MolecularHamiltonian(Hamiltonian):
    def __init__(self,
            mol,
            transform=None,
            int_thresh=1e-14,
            active_space=None,
            integral_basis='hf',
            generate_operators=True,
            verbose=True,
            en_c=None,
            solver='casci',
            print_transformed=True,
            compact_K2=False,
            ):
        if verbose:
            print('-- -- -- -- -- -- -- -- -- -- --')
            print('      -- HAMILTONIAN --  ')
            print('-- -- -- -- -- -- -- -- -- -- --')
        self._mo_basis = integral_basis
        self.verbose = verbose
        self.S = mol.intor('int1e_ovlp')
        self.T_1e = mol.intor('int1e_kin')
        self.V_1e = mol.intor('int1e_nuc')
        self.ints_1e_ao = self.V_1e+self.T_1e
        self._model='molecule'
        self.ints_2e_ao = mol.intor('int2e')
        self.real=True
        self.imag=False
        self._print_transformed=print_transformed
        self._compact = compact_K2
        self._transform = transform
        if type(transform)==type(None):
            raise HamiltonianError('Need to specify transform for Hamiltonian.')
        self.hf = scf.ROHF(mol)
        self.hf.kernel()
        self.hf.analyze()
        self.e0 = self.hf.e_tot
        self.C = self.hf.mo_coeff
        self.f = self.hf.get_fock()
        self._order = 2
        self.mol = mol
        if isinstance(active_space,tuple) or isinstance(active_space,list):
            self._use_active_space = True
            self.Ne_as = int(active_space[0])
            self.No_as = int(active_space[1])
        else:
            self.No_as = self.C.shape[0]
            self._use_active_space = False
            self.Ne_as = mol.nelec[0]+mol.nelec[1]
        self.Ne_tot = mol.nelec[0]+mol.nelec[1]
        self.Ne_core = self.Ne_tot - self.Ne_as
        self.Ne_alp = mol.nelec[0]-self.Ne_core//2
        self.Ne_bet = mol.nelec[1]-self.Ne_core//2
        self.No_core = self.Ne_core//2
        self._core = [i for i in range(self.No_core)]
        self._active = [i+self.No_core for i in range(self.No_as)]
        if self.verbose:
            print('Hartree-Fock Energy: {:.12f}'.format(float(self.hf.e_tot)))
        self.No_tot = self.C.shape[0]
        self.r = 2*self.No_as
        if self.verbose:
            print('N electrons total: {}'.format(self.Ne_tot))
            print('N electrons active: {}'.format(self.Ne_as))
            print('N core orbitals: {}'.format(self.No_core))
            print('N active orbitals: {}'.format(self.No_as))

        self._generate_spin2spac_mapping()
        if solver in ['casci','fci','ci'] and self.No_as<=8:
            self.mc = mcscf.CASCI(
                    self.hf,
                    self.No_as,
                    self.Ne_as)
            self.mc.fcisolver.nroots = 4
            self.mc.kernel()
            if abs(self.mc.e_tot[1]-self.mc.e_tot[0])<0.01:
                print('Energy gaps:')
                for i in range(self.mc.fcisolver.nroots-1):
                    print(self.mc.e_tot[i+1]-self.mc.e_tot[i])
                print('Ground excited state energy gap less than 10 mH')
            self.ef  = self.mc.e_tot[0]
            self.mc_coeff = self.mc.mo_coeff
            if self.verbose:
                print('CASCI Energy: {:.12f}'.format(float(self.ef)))

        elif solver in ['casscf']:
            n_states = 2
            weights = np.ones(n_states)/n_states
            self.mc = mcscf.CASSCF(
                    self.hf,
                    self.No_as,
                    self.Ne_as).state_average_((1,0,0))
            self.mc.kernel()
            self.ef  = self.mc.e_tot
            self.mc_coeff = self.mc.mo_coeff
            if self.verbose:
                print('CASSCF Energy: {:.8f}'.format(float(self.ef)))
        else:
            self.ef = 0
        self.spin = mol.spin
        self.Ci = np.linalg.inv(self.C)
        self._generate_active_space()
        if self._mo_basis in ['default','hf']:
            mo_coeff_a,mo_coeff_b = copy(self.C),copy(self.C)
        elif self._mo_basis in ['no','natural','canonical']:
            print('Stating with natural orbital.... ')
            mo_coeff_a,mo_coeff_b = self.mc_coeff,self.mc_coeff
        if verbose:
            print('Transforming 1e integrals...')
        self.energy_nuclear = mol.energy_nuc()
        self._gen_operators = generate_operators
        self._int_thresh = int_thresh
        self._update_ints(mo_coeff_a,mo_coeff_b)

    def _update_ints(self,mo_coeff_a,mo_coeff_b):
        self.mo_a =  mo_coeff_a
        self.mo_b = mo_coeff_b
        self.ints_1e = generate_spin_1ei(
                self.ints_1e_ao.copy(),
                mo_coeff_a.T,
                mo_coeff_b.T,
                self.alpha_mo,
                self.beta_mo,
                region='full',
                spin2spac=self.s2s
                )
        self.ints_2e = generate_spin_2ei(
                self.ints_2e_ao.copy(),
                mo_coeff_a.T,
                mo_coeff_b.T,
                self.alpha_mo,
                self.beta_mo,
                region='full',
                spin2spac=self.s2s
                )
        self._build_K2()
        if self._gen_operators:
            self._build_operator(self._int_thresh)
        else:
            self._qubOp = None
            self._ferOp = None

    def _build_K2(self):
        self.K2 = np.zeros((self.r, self.r, self.r, self.r))
        if self._use_active_space:
            active = self.alpha_mo['active']+self.beta_mo['active']
            core = self.alpha_mo['inactive'] + self.beta_mo['inactive']
            core_1e = np.zeros((self.r,self.r))
            for i in range(0,self.r):
                I = active[i]
                for j in range(0,self.r):
                    J = active[j]
                    core_1e[i,j]+= self.ints_1e[I,J]
                    for k in range(0,self.No_core*2):
                        # active-core electrons
                        K = core[k]
                        core_1e[i,j]+= self.ints_2e[I,K,J,K]
                        core_1e[i,j]-= self.ints_2e[I,K,K,J]
                    for k in range(0,self.r):
                        # active active 1e
                        K = active[k]
                        self.K2[i,k,j,k]+= core_1e[i,j]/(4*(self.Ne_as-1))
                        self.K2[k,i,k,j]+= core_1e[i,j]/(4*(self.Ne_as-1))
                        self.K2[i,k,k,j]-= core_1e[i,j]/(4*(self.Ne_as-1))
                        self.K2[k,i,j,k]-= core_1e[i,j]/(4*(self.Ne_as-1))
                        for l in range(0,self.r):
                            # active active 2e
                            L = active[l]
                            self.K2[i,k,j,l]+= 0.5*self.ints_2e[I,K,J,L]
        else:
            self.K2+= self.ints_2e*0.5
            for i in range(0,self.r):
                for j in range(0,self.r):
                    for k in range(self.r):
                        self.K2[i, k, j, k] += self.ints_1e[i, j] / (4 * (self.Ne_tot - 1))
                        self.K2[k, i, k, j] += self.ints_1e[i, j] / (4 * (self.Ne_tot - 1))
                        self.K2[i, k, k, j] -= self.ints_1e[i, j] / (4 * (self.Ne_tot - 1))
                        self.K2[k, i, j, k] -= self.ints_1e[i, j] / (4 * (self.Ne_tot - 1))
                        #self.K2[i, k, j, k]+= self.ints_1e[i, j] / (2 * (self.Ne_tot - 1))
                        #self.K2[k, i, k, j]+= self.ints_1e[i, j] / (2 * (self.Ne_tot - 1))
        self._matrix = contract(self.K2)
        self._model = 'molecular'
        if self._use_active_space:
            # need to trace over the other degrees of freedom...i.e.
            core_ab = self.alpha_mo['inactive']+self.beta_mo['inactive']
            E_core = 0
            for i in core_ab:
                E_core += self.ints_1e[i,i]
                for j in core_ab:
                    E_core+= 0.5*self.ints_2e[i,j,i,j]
                    E_core-= 0.5*self.ints_2e[i,j,j,i]
            self._en_c = E_core+self.energy_nuclear
        else:
            self._en_c = self.energy_nuclear
        if self.verbose:
            print('Core energy', self._en_c)

    @property
    def order(self):
        return self._order

    @property
    def qubit_operator(self):
        return self._qubOp

    @qubit_operator.setter
    def qubit_operator(self,b):
        self._qubOp = b

    @property
    def fermi_operator(self):
        return self._ferOp

    @fermi_operator.setter
    def fermi_operator(self,b):
        self._ferOp = b

    @property
    def matrix(self):
        return self._matrix

    def _update_integrals(self):
        pass

    def _generate_active_space(self,
            spin_mapping='default',
            **kw
            ):
        '''
        Note, all orb references are in spatial orbitals.
        '''
        self.No_v = self.No_tot - self.No_core-self.No_as
        self.alpha_mo={
                'inactive':[i for i in range(self.No_core)],
                'active':[i+self.No_core for i in range(self.No_as)],
                'virtual':[self.No_tot-self.No_v+i for i in range(self.No_v)],
                'qubit':[i for i in range(self.No_as)]
                }
        self.beta_mo={
                'inactive':[i+self.No_tot for i in range(self.No_core)],
                'active':[i+self.No_core+self.No_tot for i in range(self.No_as)],
                'virtual':[i+2*self.No_tot-self.No_v for i in range(self.No_v)],
                'qubit':[i+self.No_as for i in range(self.No_as)]
                }
        #print(self.alpha_mo)
        #print(self.beta_mo)
        self.spin = spin_mapping
        self.No_v  = self.No_tot-self.No_core-self.No_as

    def _generate_spin2spac_mapping(self):
        self.s2s = {}
        for i in range(0,self.No_tot):
            self.s2s[i]=i
        for i in range(self.No_tot,2*self.No_tot):
            self.s2s[i]=i-self.No_tot

    def _build_operator(self,int_thresh=1e-14,compact=False):
        if self.verbose:
            print('Time: ')
        t1 = timeit.default_timer()
        alp = self.alpha_mo['active']
        bet = self.beta_mo['active']
        o2q = {}
        for i in range(self.No_as):
            o2q[alp[i]]=i
            o2q[bet[i]]=i+self.No_as
        qubOp = Operator()
        ferOp = Operator()
        # 1e terms
        #
        #
        for p in alp+bet:
            P = o2q[p]
            for q in alp+bet:
                Q = o2q[q]
                if abs(self.ints_1e[p,q])<=int_thresh:
                    continue
                newOp = FermiString(
                        N=len(alp+bet),
                        coeff=self.ints_1e[p,q],
                        indices=[P,Q],
                        ops='+-',
                        )
                ferOp+= newOp
        t2 = timeit.default_timer()
        if self.verbose:
            print('1e terms: {}'.format(t2-t1))
        t_transform = 0
        n=0
        # starting 2 electron terms
        for p in alp+bet:
            P = o2q[p]
            for r in alp+bet:
                R = o2q[r]
                if p==r:
                     continue
                i1 = (p==r)
                for s in alp+bet:
                    S = o2q[s]
                    i2,i3 = (s==p),(s==r)
                    if i1+i2+i3==3:
                        continue
                    for q in alp+bet:
                        Q = o2q[q]
                        i4,i5,i6 = (q==p),(q==r),(q==s)
                        if i1+i2+i3+i4+i5+i6>=3:
                            continue
                        if q==s:
                            continue
                        if abs(self.ints_2e[p,r,q,s])<=int_thresh:
                            continue
                        #if abs(self.K2[P,R,Q,S])<=int_thresh:
                        #    continue
                        newOp = FermiString(
                                N=len(alp+bet),
                                coeff=0.5*self.ints_2e[p,r,q,s],
                                #coeff=self.K2[P,R,Q,S],
                                indices=[P,R,S,Q],
                                ops='++--',
                                )
                        ferOp+= newOp
                        #t0 = dt()
                        #qubOp+= self._transform(newOp)
                        #t_transform+= dt()-t0
                        #n+=1
        t3 = timeit.default_timer()
        #ferOp += FermiString(
        #                s = 'i'*len(alp+bet),
        #                coeff=copy(self._en_c)
        #                )
        #self._en_c = 0
        if self.verbose:
            print('2e terms: {}'.format(t3-t2))
        new = ferOp.transform(self._transform)
        qubOp = Operator()
        for i in new:
            if abs(i.c)>int_thresh:
                qubOp+= i
        qubOp.clean(1e-8)
        ferOp.clean(1e-8)
        self._qubOp = qubOp
        self._ferOp = ferOp
        t4 = timeit.default_timer()
        if self.verbose:
            print('2e transform: {}'.format(t4-t3))
        print('2e transform: {}'.format(t_transform))
        # adding identitiy
        try:
            lq = len(next(iter(qubOp)).s)
        except StopIteration:
            fer = Operator()+FermiString(s='i'*len(alp+bet),coeff=1)
            qub = fer.transform(self._transform)
            lq = len(next(iter(qub)).s)
        iden = PauliString(coeff=copy(self._en_c),pauli='I'*lq)
        qubOp += iden
        #if self.verbose and self._print_transformed:
        print('2e terms: {}'.format(t3-t2))
        print('-- -- -- -- -- -- -- -- -- -- --')
        #    print('Second Quantized Hamiltonian')
        #    print(ferOp)
        #    print('Pauli String Hamiltonian:')
        #    print(qubOp)
        #    print('-- -- -- -- -- -- -- -- -- -- --')

    def pivoted_chol(self, M='max',err_tol = 1e-6):
        """
    #  pivoted_chol.py Author "Nathan Wycoff <nathanbrwycoff@gmail.com>" Date 01.14.2020

    ## A pivoted cholesky function for kernel functions
        A simple python function which computes the Pivoted Cholesky decomposition/approximation of positive semi-definite operator. Only diagonal elements and select rows of that operator's matrix represenation are required.
        get_diag - A function which takes no arguments and returns the diagonal of the matrix when called.
        get_row - A function which takes 1 integer argument and returns the desired row (zero indexed).
        M - The maximum rank of the approximate decomposition; an integer.
        err_tol - The maximum error tolerance, that is difference between the approximate decomposition and true matrix, allowed. Note that this is in the Trace norm, not the spectral or frobenius norm.
        Returns: R, an upper triangular matrix of column dimension equal to the target matrix. It's row dimension will be at most M, but may be less if the termination condition was acceptably low error rather than max iters reached.
        """
        #temp = 1e-8 *np.identity(self.No_as**2)
        ints_2e = rotate_spatial_ei2(self.ints_2e_ao.copy(),self.C.T)
        V = np.reshape(ints_2e,(self.No_as**2,self.No_as**2))

        def get_diag():
            diag = np.diagonal(V)
            diag.flags.writeable=True
            return diag

        def get_row(i):
            return V[i,:]
        if M=='max':
            M = self.No_as**2

        d = np.copy(get_diag())
        N = len(d)
        n = int(N**(0.5))

        pi = list(range(N))

        R = np.zeros([M,N])

        err = np.sum(np.abs(d))

        m = 0
        while (m < M) and (err > err_tol):

            i = m + np.argmax([d[pi[j]] for j in range(m,N)])

            tmp = pi[m]
            pi[m] = pi[i]
            pi[i] = tmp

            R[m,pi[m]] = np.sqrt(d[pi[m]])
            Apim = get_row(pi[m])
            for i in range(m+1, N):
                if m > 0:
                    ip = np.inner(R[:m,pi[m]], R[:m,pi[i]])
                else:
                    ip = 0
                R[m,pi[i]] = (Apim[pi[i]] - ip) / R[m,pi[m]]
                d[pi[i]] -= pow(R[m,pi[i]],2)

            err = np.sum([d[pi[i]] for i in range(m+1,N)])
            m += 1

        R = R[:m,:]
        if self.verbose:
            print('Final rank: {}'.format(m))
            print('Error: {}'.format(err))
        self.ints_2e_chol = R

        self.chol_H1 = self.build_cholesky_operator_Hp()
        self.chol_H2 = []
        for i in range(m):
            Li = np.zeros((n,n))
            for j in range(N):
                a,b = j//n,j%n
                Li[a,b] = R[i,j]
            #print(Li)
            #print(np.linalg.eigvalsh(Li))
            Up,Np = self.build_cholesky_operator_Vp(Li)
            self.chol_H2.append([Up,Np])

    def build_cholesky_operator_Hp(self):
        alp = self.alpha_mo['active']
        bet = self.beta_mo['active']
        n= len(alp)
        H = Operator()
        for i in alp:
            for j in alp:
                for k in alp+bet:
                    if abs(self.ints_2e[i,k,j,k])<1e-8:
                        continue
                    H+= FermiString(
                        N=2*n,
                        coeff=0.5*self.ints_2e[i,k,j,k],
                        indices=[i,j],
                        ops='+-',
                        )
                    if abs(self.ints_2e[i,k,j,k])<1e-8:
                        continue
        for i in bet:
            for j in bet:
                for k in alp+bet:
                    H+= FermiString(
                        N=2*n,
                        coeff=0.5*self.ints_2e[i,k,j,k],
                        indices=[i,j],
                        ops='+-',
                        )
        for i in alp+bet:
            for j in alp+bet:
                if abs(self.ints_1e[i,j])<1e-8:
                    continue
                H+= FermiString(
                    N=2*n,
                    coeff=0.5*self.ints_1e[i,j],
                    indices=[i,j],
                    ops='+-',
                    )
        Hp = H.transform(self._transform)
        Hp.clean(1e-8)
        return Hp

    def build_cholesky_operator_Vp(self,Li):
        eigval, U = np.linalg.eig(Li)
        # QR decomposition
        done = False
        n = len(eigval)
        temp = np.copy(U)
        #print(U)
        Uf = Operator()
        for c in range(0,n):
            for r in reversed(range(c+1,n)):
                #print(r,c)
                if abs(temp[r,c])<1e-8:
                    # already 0
                    continue
                elif abs(temp[r-1,c])<1e-8:
                    # swap circuit
                    theta = np.pi/2
                else:
                    tan  = temp[r,c]/temp[r-1,c]

                    theta = np.arctan(tan)
                givens = np.identity(n)
                givens[r,r]=np.cos(theta)
                givens[r-1,r-1]=np.cos(theta)
                givens[r-1,r]= + np.sin(theta)
                givens[r,r-1]= - np.sin(theta)

                temp = np.dot(givens,temp)
                Uf+= FermiString(
                        N=2*n,
                        coeff=theta,
                        indices=[r,r-1],
                        ops='+-',
                        )
                Uf+= FermiString(
                        N=2*n,
                        coeff=-theta,
                        indices=[r-1,r],
                        ops='+-',
                        )
                Uf+= FermiString(
                        N=2*n,
                        coeff=theta,
                        indices=[r+n,r+n-1],
                        ops='+-',
                        )
                Uf+= FermiString(
                        N=2*n,
                        coeff=-theta,
                        indices=[r+n-1,r+n],
                        ops='+-',
                        )
        Nf = Operator()
        for i in range(n):
            if abs(eigval[i])<1e-6:
                continue
            for j in range(n):
                if abs(eigval[j])<1e-6:
                    continue
                Nf+= FermiString( #aa
                        N=2*n,
                        coeff=eigval[i]*eigval[j]*0.5,
                        ops='+-+-',
                        indices=[i,i,j,j]
                        )
                Nf+= FermiString( #ab
                        N=2*n,
                        coeff=eigval[i]*eigval[j]*0.5,
                        ops='+-+-',
                        indices=[i+n,i+n,j,j]
                        )
                Nf+= FermiString( #ab
                        N=2*n,
                        coeff=eigval[i]*eigval[j]*0.5,
                        ops='+-+-',
                        indices=[i,i,j+n,j+n]
                        )
                Nf+= FermiString( #ab
                        N=2*n,
                        coeff=eigval[i]*eigval[j]*0.5,
                        ops='+-+-',
                        indices=[i+n,i+n,j+n,j+n]
                        )
        Up = Uf.transform(self._transform)
        Up.clean(1e-8)
        Np = Nf.transform(self._transform)
        Np.clean(1e-8)
        return Up, Np

    @property
    def model(self):
        return self._model

    @model.setter
    def model(self,mod):
        self._model = mod


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='home'),
    url(r'^jobs/.*$', views.jobs, name='jobs'),
    url(r'^resubmit-job/.*$', views.resubmit_job, name='resubmit_job'),
    url(r'^compare/.*$', views.compare, name='compare'),
    url(r'^checklist/.*$', views.checklist, name='checklist'),
    url(r'^submit-jobs/.*$', views.submit_lava_jobs, name='submit_jobs'),
    url(r'^test-report/.*$', views.test_report, name='test_report'),
    url(r'^add-bug/.*$', views.add_bug, name='add_bug'),
    url(r'^add-comment/.*$', views.add_comment, name='add_comment'),
    url(r'^show-trend/.*$', views.show_trend, name='show_trend'),
    url(r'^show-cts-vts-failures/.*$', views.show_cts_vts_failures, name='show_cts_vts_failures'),
    url(r'^file-bug/.*$', views.file_bug, name='file_bug'),
]


from core.models import (BaseEntity, BaseEntityManager, User, asure_boolean,
                         asure_string, asure_user)
from django.db import models

###############################################################################
#                               validators                                    #
###############################################################################

def asure_language(language):
  """check if language is submitted"""
  if not language:
    raise ValueError('language is not submitted')
  if not isinstance(language, Language):
    raise ValueError('language is not a Language')

def asure_word(word, language=None):
  """check if word is submitted"""
  if not word:
    raise ValueError('word is not submitted')
  if not isinstance(word, Word):
    raise ValueError('word is not a Word')
  if language is not None:
    if not isinstance(language, Language):
      raise ValueError('language is not a Language')
    if not word.language == language:
      raise ValueError('word is not in the given language')

def asure_languages(languages):
  """check if languages is submitted"""
  if not languages:
    raise ValueError('languages is not submitted')
  if not isinstance(languages, list):
    raise ValueError('languages is not a list')
  if not len(languages) == 2:
    raise ValueError('languages is too short')
  for language in languages:
    if not isinstance(language, Language):
      raise ValueError('language is not a Language')
  if languages[0] == languages[1]:
    raise ValueError('languages are the same')

def asure_words(words, language=None):
  """check if words is submitted"""
  if not words:
    raise ValueError('words is not submitted')
  if not isinstance(words, list):
    raise ValueError('words is not a list')
  if not len(words) > 0:
    raise ValueError('words must be at least 1')
  for word in words:
    if not isinstance(word, Word):
      raise ValueError('word is not a Word')
    if language is not None:
      if not isinstance(language, Language):
        raise ValueError('language is not a Language')
    if not word.language == language:
      raise ValueError('word is not in the given language')

###############################################################################
#                           Managers                                          #
###############################################################################

class LanguageManager(BaseEntityManager):
  """Language manager"""

  def create_language(self, name=None, author=None, official=None, **kwargs):
    """Creates and saves a new language"""

    asure_string(name, 1)
    asure_user(author, "user")
    asure_boolean(official)

    language = self.model(name=name, author=author, official=official, **kwargs)
    language.save(using=self._db)

    return language

class WordManager(BaseEntityManager):
  """Word manager"""

  def create_word(self, name=None, language=None, description=None, author=None, official=None, **kwargs):
    """Creates and saves a new word"""

    asure_string(name, 1)
    asure_language(language)
    asure_string(description)
    asure_user(author, "user")
    asure_boolean(official)

    word = self.model(name=name, language=language, description=description, author=author, official=official, **kwargs)
    word.save(using=self._db)

    return word

  def create_word_with_synonyms(self, name=None, language=None, description=None, synonyms=None, author=None,
                                official=None, category=None, **kwargs):
    """Creates and saves a new word with synonyms"""

    asure_string(name, 1)
    asure_language(language)
    asure_string(description)
    for synonym in synonyms:
      asure_word(synonym, language)
    asure_user(author, "user")
    asure_boolean(official)
    asure_string(category)

    word = self.create_word(name=name, language=language, description=description,
                            author=author, official=official, **kwargs)
    for synonym in synonyms:
      word.synonyms.add(synonym)
    word.save(using=self._db)

    return word

###############################################################################
#                           Models                                            #
###############################################################################

class Language(BaseEntity):
  """Language model"""
  name = models.CharField(max_length=255, unique=True)
  author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='composed_languages')
  subscribers = models.ManyToManyField(User, related_name='subscribed_languages')
  official = models.BooleanField(default=False)

  objects = LanguageManager()

  def add_subscriber(self, user):
    """Add a subscriber to the language"""
    if not isinstance(user, User):
      raise ValueError('The given user must be a user object')
    self.subscribers.add(user)

  def __eq__(self, other):
    return self.name == other.name and self.id == other.id and self.active == other.active

  def __str__(self):
    return f"language object {self.name} active: {self.active}"

class Word(BaseEntity):
  """Word model"""
  name = models.CharField(max_length=255, unique=True)
  language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='words')
  synonyms = models.ManyToManyField('self', blank=True)
  description = models.TextField(blank=True)
  author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='composed_words')
  official = models.BooleanField(default=False)
  type = models.CharField(max_length=511, blank=True)   # adj, noun, verb, ...
  gender = models.CharField(max_length=1, blank=True)   # only aplicable if noun
  practices = models.IntegerField(default=0)
  succesful_practices = models.IntegerField(default=0)

  objects = WordManager()

  def add_synonym(self, word):
    """Adds a synonym to this word"""
    if not isinstance(word, Word):
      raise ValueError('The given word must be a Word object')
    self.synonyms.add(word)
    self.save()

    return self

  def remove_synonym(self, word):
    """Removes a synonym from this word"""
    if not isinstance(word, Word):
      raise ValueError('The given word must be a Word object')
    self.synonyms.remove(word)
    self.save()

    return self

  def add_practice(self, successful):
    """Adds a practice to this word"""
    self.practices += 1
    if successful:
      self.successful_practices += 1
    self.save()

    return self

  # def set_context(self, word_context):
  #   """sets a word context"""
  #   if not isinstance(word_context, WordContext):
  #     raise ValueError('The given word context must be a WordContext object')
  #   self.context = word_context
  #   self.save()

  #   return self

  def ration(self):
    """Returns the ration of successful practices to all practices"""
    return self.successful_practices / self.practices * 100

  def __eq__(self, other):
    return (self.name == other.name and self.id == other.id and self.active == other.active and
            self.language == other.language and self.description == other.description and
            self.synonyms == other.synonyms)

  def __str__(self):
    return f"word object {self.name} active: {self.active} language: {self.language}"


from sys import stdin
a, b, c = map(int, stdin.readline().split())
graph = [[] for _ in range(a+1)]
dfs_c, bfs_c = [False] * (a+1), [False] * (a+1)

for _ in range(b):
    n, m = map(int, stdin.readline().split())
    graph[n].append(m)
    graph[m].append(n)

for _ in range(a+1):
    graph[_].sort()

dfs_result = []
def dfs(graph, c):
    dfs_result.append(c)
    dfs_c[c] = True
    for t in graph[c]:
        if dfs_c[t] == False:
            dfs_c[t] = True
            dfs(graph, t)

bfs_result = []
def bfs(graph, c):
    qu = [c]
    bfs_c[c] = True
    while len(qu):
        cur = qu.pop(0)
        bfs_result.append(cur)
        for t in graph[cur]:
            if bfs_c[t] == False:
                bfs_c[t] = True
                qu.append(t)

dfs(graph, c); bfs(graph, c)

for _ in dfs_result: print(_, end=' ')
print()
for _ in bfs_result: print(_, end=' ')


from __future__ import with_statement
import sys
import urllib
from mpx.lib import msglog
from mpx.service.interactive.tools import ByteBuffer
from mpx.service.interactive.tools import SimpleProducer
from mpx.service.interactive.tools import ByteProducer
from mpx.service.interactive.tools import LineProducer
from mpx.service.interactive.tools import QuoteProducer
from mpx.service.interactive.tools import AsyncChannel
from mpx.service.network.utilities.counting import Counter
from mpx.service.interactive.console import InteractiveSession

class ConsoleChannel(AsyncChannel):
    counter = Counter()
    def __init__(self, dispatcher, connection):
        super(ConsoleChannel, self).__init__(dispatcher, connection)
        self.number = self.counter.increment()
        self.buffer = ByteBuffer()
        self.setup_console()
    def setup_console(self):
        self.namespace = {'loadtools': self.loadtools}
        self.console = InteractiveSession(self)
        self.set_terminator('\r\n')
        self.console.start()
        self.initprompt()
    def initprompt(self):
        banner = [sys.version]
        banner.append("%s" % self.dispatcher)
        banner.append(str(self.dispatcher))
        banner.append(str(self))
        banner.append('<loadtools() will add standard tools>')
        self.console.prompt("\n".join(banner))
    def push(self, data):
        producer = SimpleProducer(data)
        producer = ByteProducer(producer)
        producer = QuoteProducer(producer)
        producer = LineProducer(producer)
        return self.push_with_producer(producer)
    def loadtools(self):
        from mpx.lib import msglog
        from mpx.lib.node import as_node
        from mpx.lib.node import as_node_url
        self.namespace['msglog'] = msglog
        self.namespace['as_node'] = as_node
        self.namespace['root'] = as_node('/')
        self.namespace['as_node_url'] = as_node_url
    def handle_connect(self):
        pass
    def handle_expt(self):
        self.debugout('%s handling exceptional event.', self, level=0)
        self.close()
    def handle_error(self):
        self.debugout('%s closing due to exception.', self, level=0)
        msglog.exception(prefix = 'handled')
        self.close()
    def close(self):
        self.console.stop()
        super(ConsoleChannel, self).close()
        self.debugout('%s closed and removed.', self, level=1)
    def recv(self, buffer_size):
        data = super(ConsoleChannel, self).recv(buffer_size)
        unquoted = urllib.unquote(data)
        self.debugout('%s << %r (%r)', self, data, unquoted, level=2)
        return data
    def send(self, data):
        result = super(ConsoleChannel, self).send(data)
        unquoted = urllib.unquote(data)
        self.debugout('%s >> %r (%r)', self, data, unquoted, level=2)
        return result
    def collect_incoming_data(self, bytes):
        self.buffer.write(bytes)
    def found_terminator(self):
        quoted = self.buffer.read()
        command = urllib.unquote(quoted)
        self.debugout('%s console.handle(%r)', self, command, level=1)
        self.console.handle(urllib.unquote(command))
    def __str__(self):
        status = [type(self).__name__]
        status.append('#%03d' % self.number)
        return ' '.join(status)
    def __repr__(self):
        status = [str(self)]
        return '<%s at %#x>' % (status, id(self))
    def debugout(self, message, *args, **kw):
        self.dispatcher.debugout(message, *args, **kw)


import singleFactorTest as sf
import pandas as pd

def read_data():
    factor1 = pd.read_csv('factors1.csv',index_col=0)
    industry = pd.read_csv('industryCiticsM.csv',index_col=0)
    futRet = pd.read_csv('futRet.csv',index_col=0)
    zz500 = pd.read_csv('zz500.csv',index_col=0)
    ffc = pd.read_csv('freeFloatCapM.csv',index_col=0)
    df= sf.DataDealing()
    industryM = df.dealing(factor1,industry)
    futRet = df.dealing(factor1,futRet)
    zz500 = df.dealing(factor1,zz500)
    ffc = df.dealing(factor1,ffc)
    return  factor1,futRet,industryM,zz500,ffc

# 标准化方法1：去异常值，ZScore法
def ZScore(ind_choice=True):
    factor1, futRet, industryM,_,_ = read_data()
    sf1 = sf.OutlierCleaner()
    sf1.Nstd_pannel(factor1)
    sf2 = sf.Standardization()
    if ind_choice: factor = sf2.ZScore(factor1)
    else: factor = sf2.ZScore_Ind(factor1,industryM)
    return factor

# 标准化方法2：直接取rank标准化
def Quantile(method_choice='maxmin'):
    factor1, futRet, industryM,_,_ = read_data()
    sf2 = sf.Standardization()
    if method_choice == 'sta': factor = sf2.QuantileChange_Ind(factor1,industryM)
    else: factor = sf2.QuantileMaxMin_Ind(factor1,industryM)
    return factor

# 因子行业中性处理
def ind_deal(method='Quantile'):
    if method=='Quantile':factor=Quantile()
    else: factor = ZScore()
    sf3 = sf.Orthogonalized()
    _,_,industryM,_,_ = read_data()
    factor = sf3.get(factor,industryM)
    return factor

# 回归计算序列t值
def tstats():
    factor = ind_deal()
    _,futRet,_,_ ,_= read_data()
    sf4 = sf.Regression()
    Para = sf4.get(factor,futRet)
    return Para

def cacu_rankIC():
    factor = ind_deal()
    _,futRet,_,_,_ = read_data()
    sf5 = sf.IC()
    ic, summary = sf5.rankIC(factor,futRet)
    return ic, summary

def split_test():
    factor, futRet, industryM, zz500,ffc = read_data()
    sf6 = sf.SpiltGroup()
    sf6.get(factor,futRet,industryM=industryM, zz500=zz500,ffc=ffc,isIndustryNeutral=True,SpiltGroupType = 'Industry_AVG')
    return

split_test()


from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserForm
import users.globalbaz
from .models import User

def register(request ) :

    if request.method == 'POST':
        user_form = UserForm(request.POST)

        if user_form.is_valid():
            user = user_form.save()

            messages.success(request, f'Your profile was successfully created!')

            return redirect('login')
        else:
            messages.error(request, f'Please correct the error below.')
    else:
        user_form = UserForm()

    return render(request, 'users/register.html', {
        'user_form': user_form,

    })

def get_user_profile(request,username):

    try:
        user_p = User.objects.get(username=username)

    except (User.DoesNotExist):
        messages.warning(request,'No such username exists')
        return redirect('blog-home')
    return render(request,'users/user_profile.html',{"user_p" : user_p })

'''
if request.method == 'POST':
    user_form = UserForm(request.POST)
    profile_form = ProfileForm(request.POST)
    if user_form.is_valid() and profile_form.is_valid():

        global user
        user = user_form.save()

        user.profile.type = profile_form.cleaned_data.get('type')
        user.profile.save()

        messages.success(request, f'Your profile was successfully created!')

        return redirect('register_student')
    else:
        messages.error(request, f'Please correct the error below.')
else:
    user_form = UserForm()
    profile_form = ProfileForm()
return render(request, 'users/register.html', {
    'user_form': user_form,
    'profile_form': profile_form
})
'''

'''
def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            #messages.success(request, f'Account created for {username}!')
            return redirect('blog-home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})
'''


from utils import *
import warnings
import config as cfg
import onnx

# Change these only when dataset changed
clean_json_file = cfg.CLEAN_JSON_FILE_TEST
noise_json_file = cfg.NOISE_JSON_FILE_TEST
noisy_saving_path_base = cfg.NOISY_TEST_FILE_SAVING_PATH
clean_saving_path_base = cfg.CLEAN_TEST_FILE_SAVING_PATH

# Change these for testing a new model
denoised_audio_path = cfg.DENOISED_TEST_FILE_SAVING_PATH
csv_path = cfg.TEST_STATS
model = cfg.TEST_MODEL
dumped_onnx = cfg.DUMPED_ONNX_MODEL

warnings.filterwarnings('ignore')
# generate_noisy_waveform_for_test_set(clean_json_file, noise_json_file, fs, noisy_saving_path_base, clean_saving_path_base)
evaluate_test_audios(noisy_saving_path_base,clean_saving_path_base,model,cfg.fs,cfg.window_length,denoised_audio_path,csv_path,cfg.numFeatures,cfg.numSegments)

# dump_onnx_model(model,[1,2,cfg.numFeatures,cfg.numSegments],dumped_onnx)


import sys
from PyQt5.QtWidgets import *
from form1 import Ui_MainWindow

class AnaFrom(Ui_MainWindow,QMainWindow):
    def __init__(self):
        super(AnaFrom,self).__init__()
        self.setupUi(self)
        self.show()
        self.pushButton.clicked.connect(self.Ekle)
        self.pushButton_3.clicked.connect(self.Doldur)
        self.pushButton_4.clicked.connect(self.Temizle)
        self.tableWidget.doubleClicked.connect(self.Sec)

    def Sec(self):
        secim=self.tableWidget.selectedItems() #tablo hücresindeki bir değeri liste yapar
        self.label.setText(secim[0].text()) #secilen elamanı labela yazar

    def Temizle(self):
          self.tableWidget.clear()

    def Doldur(self):
        self.tableWidget.setHorizontalHeaderLabels(('Öğr no','öğrenci ad','öğrenci soyad')) #başlık değiştirir
        ogrenci=[["12","Name","Surname"],["15","Name1","Surname2"],["15","Name1","Surname2"]
                 ,["15","Name1","Surname2"],["15","Name1","Surname2"]]
    #    self.tableWidget.setItem(0,0,QTableWidgetItem(ogrenci[0]))
    #   self.tableWidget.setItem(0,0,QTableWidgetItem(ogrenci[1]))
    #    self.tableWidget.setItem(0,0,QTableWidgetItem(ogrenci[2]))

        i=0
        for x in ogrenci :
            j=0
            self.tableWidget.insertRow(x) #table nesnesine ilk satırı ekledi
            for y in ogrenci:
                 self.tableWidget.setItem(i,j,QTableWidgetItem(ogrenci[y]))
                 j=j+1
            i+=1

    def Ekle(self):
        self.tableWidget.insertRow(0)
        self.tableWidget.setItem(1,1,QTableWidgetItem())

proje1=QApplication(sys.argv)
form1=AnaFrom()
sys.exit(proje1.exec())

#Ödev seçilen elemandan yeni liste oluşturacak list widget yap.


import gym

import numpy as np

from stable_baselines.common import make_vec_env
from stable_baselines import PPO2
from CARS_TRIAL_GymEnvironment_DiscreteActions import CustomEnv
from stable_baselines.common.schedules import ConstantSchedule, LinearSchedule

filename = "CARS_medium5_225_LSTM_ppo2_LR_LinearSchedule_timesteps_2000000ep_length_120turnrate_0.1963125maxspeed_2.5randomBall_TruebinaryReward_True"
#filename = "CARS_medium5_225_newObs_ppo2_LR_LinearSchedule_timesteps_4000000ep_length_120turnrate_0.1963125maxspeed_2.5randomBall_TruebinaryReward_True"
# Load signal parameters from file:
f = open("../Envparameters/envparameters_" + filename, "r")
envparameters = f.read()
envparameters = envparameters.strip('[')
envparameters = envparameters.strip(']')
f_list = [i for i in envparameters.split(",")]
print("envparameters: " + str(f_list))

my_step_limit = int(f_list[0])
my_step_size = float(f_list[1])
my_maxspeed = float(f_list[2])
my_acceleration = float(f_list[3])
my_randomBall = bool(f_list[4])
my_binaryReward = bool(f_list[5])

# Initialize environment with signal parameters:
env = make_vec_env(CustomEnv, n_envs=16, env_kwargs={'step_limit':my_step_limit, 'step_size' : my_step_size, 'maxspeed' : my_maxspeed, 'acceleration' : my_acceleration, 'randomBall' : my_randomBall, 'binaryReward' : my_binaryReward})

# Load trained model and execute it forever:
model = PPO2.load("../Models/" +filename)

while True:
    obs = env.reset()
    for i in range(my_step_limit*2):
        action, _states = model.predict(obs)
        #print(obs)
        obs, rewards, dones, info = env.step(action)
        print(rewards)
        for environment in env.envs:
            environment.renderSlow(50)
        # if(dones):
        #      env.render()
        #      break
        #env.envs[0].renderSlow(50)

# while True:
#     obs = env.reset()
#     #obs = env.envs[0].reset()
#     #obs = obs.reshape((1,4))
#     #print(env.observation_space.shape)
#     #obs, rewards, dones, info = env.step([0,0])
#     for i in range(my_step_limit*2): #my_step_limit
#         action, _states = model.predict(obs)
#         #print(action)
#         print(obs[0])
#         obs, rewards, dones, info = env.step(action)
#         #obs, rewards, dones, info = env.envs[0].step(action)
#         #obs = np.array(obs).reshape((1,4))
#         if(dones[0]):
#              env.envs[0].renderSlow(1)
#              break
#         env.envs[0].renderSlow(10)