问:
How to link two classes from two different python files
So I'm building a website for my school project using tkinter (specifically customtkinter).  What i want to achieve is that when I click the manager button on the main window, the manager window to open up. The main window and manager window exist in two different python files. Unfortunately its been nothing but errors for the past 5 hours for me.

Below is the code for the main window

```<code>from tkinter import *
from tkinter import messagebox,ttk
from PIL import ImageTk, Image
import Py_SQL_conn as PS
import tkinter.messagebox
import customtkinter
from customtkinter import *
from tkcalendar import Calendar, DateEntry
from datetime import date
from datetime import datetime
import trailtk19 as tr

#try to increase window size...
customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

import tkinter as tk                # python 3
from tkinter import font as tkfont # python 3

class SampleApp(customtkinter.CTk):

    def __init__(self, *args, **kwargs):
        customtkinter.CTk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = CTkFrame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage,Booking_page,Ava_Sch_page,Passenger_page):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class Booking_page(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        main_frame=CTkFrame(master=self)
        main_frame.pack(fill=BOTH, expand=1)
        but1=CTkButton(master=main_frame,width=190,text="Main",command=lambda: controller.show_frame("StartPage"))
        but1.pack(side=LEFT,pady=0,padx=0)
        but2=CTkButton(master=main_frame,width=190,text="See sch",command=lambda: controller.show_frame("Ava_Sch_page"))
        but2.pack(side=LEFT,pady=0,padx=0)

class Ava_Sch_page(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        frame1 = CTkFrame(master=self)
        frame1.pack(fill=BOTH, expand=1)

        my_canvas = Canvas(frame1)
        my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
        ctk_textbox_scrollbar = customtkinter.CTkScrollbar(frame1, command=my_canvas.yview)
        ctk_textbox_scrollbar.pack(side=RIGHT, fill=Y)
        my_canvas.configure(yscrollcommand=ctk_textbox_scrollbar.set)
        my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

        main_frame=CTkFrame(my_canvas,width=1300,height=2000+1000,fg_color="white")
        main_frame.pack()
        my_canvas.create_window((0,0), window=main_frame, anchor="nw")
        header=CTkFrame(main_frame,width=1300,height=55,corner_radius=0,fg_color="#57a1f8")
        header.place(x=0,y=0)

        man_lab=CTkLabel(header,text="Welcome Manager",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        #Navigation bar
        nav_frame=CTkFrame(main_frame,width=925,corner_radius=0,fg_color="#1f6aa5",height=35)
        nav_frame.place(x=0,y=55)

        but1=CTkButton(nav_frame,text="Bookings",fg_color="#144870",corner_radius=0,height=35,width=90,state=DISABLED,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="Passengers",corner_radius=0,height=35,width=100,state=DISABLED,command=lambda: controller.show_frame("Pass_det"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but3.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

        path = "aurora.jpeg"
        self.img = ImageTk.PhotoImage(Image.open(path))
        Label(master=main_frame,image=self.img,height=650,width=510).place(x=500,y=50)
        customtkinter.CTkButton(master=main_frame,width=190,text="Booking",command=lambda: controller.show_frame("Booking_page")).place(x=1000,y=150)
        customtkinter.CTkButton(master=main_frame,width=190,text="details",command=lambda: controller.show_frame("Passenger_page")).place(x=1000,y=1950)

class Passenger_page(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        main_frame=CTkFrame(master=self)
        main_frame.pack(fill=BOTH, expand=1)

        customtkinter.CTkButton(master=main_frame,width=190,text="Avail",command=lambda: controller.show_frame("Ava_Sch_page")).pack(side=LEFT,pady=0,padx=0)
        customtkinter.CTkButton(master=main_frame,width=190,text="Main",command=lambda: controller.show_frame("StartPage")).pack(side=LEFT,pady=0,padx=0)

class StartPage(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        def confirm():
            global na
            u=user.get()
            p=passw.get()
            datsum=PS.connectorconn("Select * from managers;")
            for x in datsum:
                if (u==x[3]) and (p==x[4]):
                    con="yes"
                    break
                else:
                    con="yes"

            if con=="yes":
                controller.show_frame("Booking_page")

        #Website opens into booking page

        frame1 = CTkFrame(master=self)
        frame1.pack(fill=BOTH, expand=1)

        # Create A Canvas
        my_canvas = Canvas(frame1)
        my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

        # Add A Scrollbar To The Canvas
        ctk_textbox_scrollbar = customtkinter.CTkScrollbar(frame1, command=my_canvas.yview)
        ctk_textbox_scrollbar.pack(side=RIGHT, fill=Y)
        ##my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
        ##my_scrollbar.pack(side=RIGHT, fill=Y)

        # Configure The Canvas
        my_canvas.configure(yscrollcommand=ctk_textbox_scrollbar.set)
        my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

        # Create ANOTHER Frame INSIDE the Canvas

        main_frame=CTkFrame(my_canvas,width=1300,height=2000)
        main_frame.pack()
        # Add that New frame To a Window In The Canvas
        my_canvas.create_window((0,0), window=main_frame, anchor="nw")

        #Code for scroll bar ends here. To use again, copy paste the above code and when adding widgets to the frame, make sure to put master=mainframe.
        #NOTE: Only use place geometry manager to add subsequent widgets.

        header=CTkFrame(main_frame,width=1300,height=55,corner_radius=0,fg_color="#57a1f8")
        header.place(x=0,y=55)

        man_lab=CTkLabel(header,text="  ",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        #Navigation bar
        nav_frame=CTkFrame(main_frame,width=925,corner_radius=0,fg_color="#1f6aa5",height=35)
        nav_frame.place(x=0,y=108)

        but=CTkButton(nav_frame,text="Schedule",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Pass_det"))
        but.pack(side=LEFT,pady=0,padx=0)

        but1=CTkButton(nav_frame,text="Book flight",fg_color="#144870",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="View ticket",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Booking_page"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text="Cancel ticket",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Booking_page"))
        but3.pack(side=LEFT,pady=0,padx=0)

        but4=CTkButton(nav_frame,text="About us",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Booking_page"))
        but4.pack(side=LEFT,pady=0,padx=0)

        def y():
            tr.Display()

        but5=CTkButton(nav_frame,text="Manager Log",corner_radius=0,height=35,command=lambda: y)
        but5.pack(side=LEFT,pady=0,padx=0)

        but6=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but6.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

root=SampleApp()
root.title("Main_window")
root.attributes('-fullscreen',True)
root.resizable(False,False)
root.configure(bg="white")
def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
</code>```

And below is the manger window

```<code>from tkinter import *
from tkinter import messagebox,ttk
from PIL import ImageTk, Image
import Py_SQL_conn as PS
import tkinter.messagebox
import customtkinter
from customtkinter import *

#try to increase window size...
customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

import tkinter as tk                # python 3
from tkinter import font as tkfont # python 3

class SampleApp(customtkinter.CTk):

    def __init__(self, *args, **kwargs):
        customtkinter.CTk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = CTkFrame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage,Book_det,Pass_det):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        def confirm():
            global na
            u=user.get()
            p=passw.get()
            datsum=PS.connectorconn("Select * from managers;")
            #error if not in datsum and then the stuff i guess....good prgress
            for x in datsum:
                if (u==x[3]) and (p==x[4]):
                    con="yes"
                    break
                else:
                    con="no"

            if con=="yes":
                controller.show_frame("Book_det")
            else:
                messagebox.showwarning("Warning","Invalid Credentials.")

        main_frame=CTkFrame(master=self)
        main_frame.pack(fill=BOTH, expand=1)

        path = "aurora.jpeg"
        self.img = ImageTk.PhotoImage(Image.open(path))
        Label(master=main_frame,image=self.img,height=650,width=510).place(x=85,y=50)

        frame=CTkFrame(master=main_frame,width=350,height=350,bg="white")
        frame.place(x=480,y=83)

        heading=CTkLabel(master=frame,text="Manager Login",fg="#57a1f8",bg='white',text_font=('Microsoft YaHei UI Light',23))
        heading.place(x=61,y=25)

        #username
        user= CTkEntry(master=frame,width=290,placeholder_text="Username", border=0,bg='white',text_font=('Microsoft YaHei UI Light',11))
        user.place(x=30,y=120)
        ##user.bind('<FocusIn>',on_enter)
        ##user.bind('<FocusOut>',on_leave)
        ##CTkFrame(master=frame,width=295,bg='black').place(x=25,y=107)

        #Password
        passw= customtkinter.CTkEntry(master=frame,width=290,placeholder_text="Password",bg='white',border=0,text_font=('Microsoft YaHei UI Light',11))
        passw.place(x=30,y=180)
        ##passw.bind('<FocusIn>',on_enter)
        ##passw.bind('<FocusOut>',on_leave)
        ##CTkFrame(master=frame,width=295,bg='black').place(x=25,y=177)

        #Submit button
        customtkinter.CTkButton(master=frame,width=190,text="Log in",command=lambda: confirm()).place(x=80,y=270)

class Book_det(CTkFrame):

    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        #For every frame...
        self.controller = controller
        main_frame1=CTkFrame(master=self)
        main_frame1.pack(fill=BOTH, expand=1)

        header=CTkFrame(main_frame1,width=925,height=55,corner_radius=0,fg_color="#57a1f8")
        header.pack()

        man_lab=CTkLabel(header,text="Welcome Manager",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        nav_frame=CTkFrame(main_frame1,width=925,corner_radius=0,fg_color="#1f6aa5",height=35)
        nav_frame.pack(anchor="w",fill=BOTH)

        but1=CTkButton(nav_frame,text="Bookings",fg_color="#144870",corner_radius=0,height=35,width=90,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="Passengers",corner_radius=0,height=35,width=100,command=lambda: controller.show_frame("Pass_det"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but3.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

        fs_frame = CTkFrame(main_frame1)
        fs_frame.pack(fill=BOTH,expand=1,pady=25,padx=25)
       # fs_frame.pack()

        reg_dep = ttk.Treeview(fs_frame,height=18)

        reg_dep['columns'] = ('BookingID', 'Dep_Des_Code', 'Arr_Des_Code', 'Passenger_ID','Departure_Date','Return_Date','Booked_Seat')

        reg_dep.column("#0", width=0,  stretch=NO)
        reg_dep.column('BookingID',anchor=CENTER, width=120)
        reg_dep.column('Dep_Des_Code',anchor=CENTER, width=140)
        reg_dep.column('Arr_Des_Code',anchor=CENTER,width=140)
        reg_dep.column('Passenger_ID',anchor=CENTER,width=140)
        reg_dep.column('Departure_Date',anchor=CENTER,width=160)
        reg_dep.column('Return_Date',anchor=CENTER,width=160)
        reg_dep.column('Booked_Seat',anchor=CENTER,width=140)

        reg_dep.heading("#0",text="",anchor=CENTER)
        reg_dep.heading('BookingID',text='BookingID',anchor=CENTER)
        reg_dep.heading('Dep_Des_Code',text='Dep_Des_Code',anchor=CENTER)
        reg_dep.heading('Arr_Des_Code',text='Arr_Des_Code',anchor=CENTER)
        reg_dep.heading('Passenger_ID',text='Passenger_ID',anchor=CENTER)
        reg_dep.heading('Departure_Date',text='Departure_Date',anchor=CENTER)
        reg_dep.heading('Return_Date',text='Return_Date',anchor=CENTER)
        reg_dep.heading('Booked_Seat',text='Booked_Seat',anchor=CENTER)

        import mysql.connector as mycon
        conn=mycon.connect(host="localhost",user="root",passwd="12345678",database="aurora_airlines")
        cursor=conn.cursor()
        cursor.execute("Select * from bookings;")
        data=cursor.fetchall()
        Records=[]
        for row in data:
                Records.append(row)
        count=cursor.rowcount
        for iid in range(count):
            reg_dep.insert(parent='',index='end',iid=iid,text='',
            values=(Records[iid][0],Records[iid][1],Records[iid][2],Records[iid][3], Records[iid][4],Records[iid][5],Records[iid][6]))
        reg_dep.pack(pady=85)

##        button = customtkinter.CTkButton(main_frame1,corner_radius=0,height=10,text="Go to the start page",
##                           command=lambda: controller.show_frame("StartPage"))
##        button.grid(row=0,column=0)
##        button1 = customtkinter.CTkButton(main_frame1, text="go to page two",
##                           command=lambda: controller.show_frame("PageTwo"))
##        button1.grid(row=0,column=1)

class Pass_det(CTkFrame):

    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        #For every frame...
        self.controller = controller
        main_frame1=CTkFrame(master=self)
        main_frame1.pack(fill=BOTH, expand=1)

        header=CTkFrame(main_frame1,width=925,height=55,corner_radius=0,fg_color="#57a1f8")
        header.pack()

        man_lab=CTkLabel(header,text="Welcome Manager",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        nav_frame=CTkFrame(main_frame1,height=37,width=925,corner_radius=0,fg_color="#1f6aa5")
        nav_frame.pack(anchor="w",fill=BOTH,padx=0,pady=0)

        but1=CTkButton(nav_frame,text="Bookings",corner_radius=0,height=35,width=90,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="Passengers",fg_color="#144870",corner_radius=0,height=35,width=100,command=lambda: controller.show_frame("Pass_det"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but3.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

        fs_frame = CTkFrame(main_frame1)
        fs_frame.pack(fill=BOTH,expand=1,pady=25,padx=25)
       # fs_frame.pack()

        reg_dep = ttk.Treeview(fs_frame,height=22)
        CTkLabel(fs_frame,text="").pack()
        reg_dep['columns'] = ('Passenger_ID', 'First_Name', 'Last_Name',
                              'Passport_ID', 'Meal_Preference','Phone_number',
                              'Email', 'Class')

        reg_dep.column("#0", width=0,  stretch=NO)
        reg_dep.column('Passenger_ID',anchor=CENTER, width=120)
        reg_dep.column('First_Name',anchor=CENTER, width=140)
        reg_dep.column('Last_Name',anchor=CENTER,width=140)
        reg_dep.column('Passport_ID',anchor=CENTER,width=140)
        reg_dep.column('Meal_Preference',anchor=CENTER,width=160)
        reg_dep.column('Phone_number',anchor=CENTER,width=160)
        reg_dep.column('Email',anchor=CENTER,width=140)
        reg_dep.column('Class',anchor=CENTER,width=160)

        reg_dep.heading("#0",text="",anchor=CENTER)
        reg_dep.heading('Passenger_ID',text='Passenger_ID',anchor=CENTER)
        reg_dep.heading('First_Name',text='First_Name',anchor=CENTER)
        reg_dep.heading('Last_Name',text='Last_Name',anchor=CENTER)
        reg_dep.heading('Passport_ID',text='Passport_ID',anchor=CENTER)
        reg_dep.heading('Meal_Preference',text='Meal_Preference',anchor=CENTER)
        reg_dep.heading('Phone_number',text='Phone_number',anchor=CENTER)
        reg_dep.heading('Email',text='Email',anchor=CENTER)
        reg_dep.heading('Class',text='Class',anchor=CENTER)

        import mysql.connector as mycon
        conn=mycon.connect(host="localhost",user="root",passwd="12345678",database="aurora_airlines")
        cursor=conn.cursor()
        cursor.execute("Select * from passengers;")
        data=cursor.fetchall()
        Records=[]
        for row in data:
                Records.append(row)
        count=cursor.rowcount
        for iid in range(count):
            reg_dep.insert(parent='',index='end',iid=iid,text='',
            values=(Records[iid][0],Records[iid][1],Records[iid][2],Records[iid][3], Records[iid][4],Records[iid][5],Records[iid][6],Records[iid][7]))
        reg_dep.pack(pady=44)

def Display():
    root=SampleApp()
    root.title("Manager_Login")
    root.geometry('925x500+300+200')
    root.resizable(False,False)
    root.configure(bg="white")
    root.mainloop()
</code>```

I keep getting the 'image "pyimage2" doesn't exist' error. Then when I used the call method, it kept opening another python window which I don't want. I also don't want to merge the above codes into one file since I have a lot of code to add for the other parts of the project.

I apologize for the messy code since these were just test files

I'm just a beginner in python so I might have made some mistakes I'm not aware of. I would be grateful if anyone could help me! Thank you!

Body:
So I'm building a website for my school project using tkinter (specifically customtkinter).  What i want to achieve is that when I click the manager button on the main window, the manager window to open up. The main window and manager window exist in two different python files. Unfortunately its been nothing but errors for the past 5 hours for me.

Below is the code for the main window

from tkinter import *
from tkinter import messagebox,ttk
from PIL import ImageTk, Image
import Py_SQL_conn as PS
import tkinter.messagebox
import customtkinter
from customtkinter import *
from tkcalendar import Calendar, DateEntry
from datetime import date
from datetime import datetime
import trailtk19 as tr

#try to increase window size...
customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

import tkinter as tk                # python 3
from tkinter import font as tkfont # python 3

class SampleApp(customtkinter.CTk):

    def __init__(self, *args, **kwargs):
        customtkinter.CTk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = CTkFrame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage,Booking_page,Ava_Sch_page,Passenger_page):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class Booking_page(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        main_frame=CTkFrame(master=self)
        main_frame.pack(fill=BOTH, expand=1)
        but1=CTkButton(master=main_frame,width=190,text="Main",command=lambda: controller.show_frame("StartPage"))
        but1.pack(side=LEFT,pady=0,padx=0)
        but2=CTkButton(master=main_frame,width=190,text="See sch",command=lambda: controller.show_frame("Ava_Sch_page"))
        but2.pack(side=LEFT,pady=0,padx=0)

class Ava_Sch_page(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        frame1 = CTkFrame(master=self)
        frame1.pack(fill=BOTH, expand=1)

        my_canvas = Canvas(frame1)
        my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
        ctk_textbox_scrollbar = customtkinter.CTkScrollbar(frame1, command=my_canvas.yview)
        ctk_textbox_scrollbar.pack(side=RIGHT, fill=Y)
        my_canvas.configure(yscrollcommand=ctk_textbox_scrollbar.set)
        my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

        main_frame=CTkFrame(my_canvas,width=1300,height=2000+1000,fg_color="white")
        main_frame.pack()
        my_canvas.create_window((0,0), window=main_frame, anchor="nw")
        header=CTkFrame(main_frame,width=1300,height=55,corner_radius=0,fg_color="#57a1f8")
        header.place(x=0,y=0)

        man_lab=CTkLabel(header,text="Welcome Manager",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        #Navigation bar
        nav_frame=CTkFrame(main_frame,width=925,corner_radius=0,fg_color="#1f6aa5",height=35)
        nav_frame.place(x=0,y=55)

        but1=CTkButton(nav_frame,text="Bookings",fg_color="#144870",corner_radius=0,height=35,width=90,state=DISABLED,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="Passengers",corner_radius=0,height=35,width=100,state=DISABLED,command=lambda: controller.show_frame("Pass_det"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but3.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

        path = "aurora.jpeg"
        self.img = ImageTk.PhotoImage(Image.open(path))
        Label(master=main_frame,image=self.img,height=650,width=510).place(x=500,y=50)
        customtkinter.CTkButton(master=main_frame,width=190,text="Booking",command=lambda: controller.show_frame("Booking_page")).place(x=1000,y=150)
        customtkinter.CTkButton(master=main_frame,width=190,text="details",command=lambda: controller.show_frame("Passenger_page")).place(x=1000,y=1950)

class Passenger_page(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        main_frame=CTkFrame(master=self)
        main_frame.pack(fill=BOTH, expand=1)

        customtkinter.CTkButton(master=main_frame,width=190,text="Avail",command=lambda: controller.show_frame("Ava_Sch_page")).pack(side=LEFT,pady=0,padx=0)
        customtkinter.CTkButton(master=main_frame,width=190,text="Main",command=lambda: controller.show_frame("StartPage")).pack(side=LEFT,pady=0,padx=0)

class StartPage(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        def confirm():
            global na
            u=user.get()
            p=passw.get()
            datsum=PS.connectorconn("Select * from managers;")
            for x in datsum:
                if (u==x[3]) and (p==x[4]):
                    con="yes"
                    break
                else:
                    con="yes"

            if con=="yes":
                controller.show_frame("Booking_page")

        #Website opens into booking page

        frame1 = CTkFrame(master=self)
        frame1.pack(fill=BOTH, expand=1)

        # Create A Canvas
        my_canvas = Canvas(frame1)
        my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

        # Add A Scrollbar To The Canvas
        ctk_textbox_scrollbar = customtkinter.CTkScrollbar(frame1, command=my_canvas.yview)
        ctk_textbox_scrollbar.pack(side=RIGHT, fill=Y)
        ##my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
        ##my_scrollbar.pack(side=RIGHT, fill=Y)

        # Configure The Canvas
        my_canvas.configure(yscrollcommand=ctk_textbox_scrollbar.set)
        my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))

        # Create ANOTHER Frame INSIDE the Canvas

        main_frame=CTkFrame(my_canvas,width=1300,height=2000)
        main_frame.pack()
        # Add that New frame To a Window In The Canvas
        my_canvas.create_window((0,0), window=main_frame, anchor="nw")

        #Code for scroll bar ends here. To use again, copy paste the above code and when adding widgets to the frame, make sure to put master=mainframe.
        #NOTE: Only use place geometry manager to add subsequent widgets.

        header=CTkFrame(main_frame,width=1300,height=55,corner_radius=0,fg_color="#57a1f8")
        header.place(x=0,y=55)

        man_lab=CTkLabel(header,text="  ",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        #Navigation bar
        nav_frame=CTkFrame(main_frame,width=925,corner_radius=0,fg_color="#1f6aa5",height=35)
        nav_frame.place(x=0,y=108)

        but=CTkButton(nav_frame,text="Schedule",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Pass_det"))
        but.pack(side=LEFT,pady=0,padx=0)

        but1=CTkButton(nav_frame,text="Book flight",fg_color="#144870",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="View ticket",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Booking_page"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text="Cancel ticket",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Booking_page"))
        but3.pack(side=LEFT,pady=0,padx=0)

        but4=CTkButton(nav_frame,text="About us",corner_radius=0,height=35,state=DISABLED,command=lambda: controller.show_frame("Booking_page"))
        but4.pack(side=LEFT,pady=0,padx=0)

        def y():
            tr.Display()

        but5=CTkButton(nav_frame,text="Manager Log",corner_radius=0,height=35,command=lambda: y)
        but5.pack(side=LEFT,pady=0,padx=0)

        but6=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but6.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

root=SampleApp()
root.title("Main_window")
root.attributes('-fullscreen',True)
root.resizable(False,False)
root.configure(bg="white")
def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

And below is the manger window

from tkinter import *
from tkinter import messagebox,ttk
from PIL import ImageTk, Image
import Py_SQL_conn as PS
import tkinter.messagebox
import customtkinter
from customtkinter import *

#try to increase window size...
customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

import tkinter as tk                # python 3
from tkinter import font as tkfont # python 3

class SampleApp(customtkinter.CTk):

    def __init__(self, *args, **kwargs):
        customtkinter.CTk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = CTkFrame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage,Book_det,Pass_det):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(CTkFrame):
    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        self.controller = controller
        def confirm():
            global na
            u=user.get()
            p=passw.get()
            datsum=PS.connectorconn("Select * from managers;")
            #error if not in datsum and then the stuff i guess....good prgress
            for x in datsum:
                if (u==x[3]) and (p==x[4]):
                    con="yes"
                    break
                else:
                    con="no"

            if con=="yes":
                controller.show_frame("Book_det")
            else:
                messagebox.showwarning("Warning","Invalid Credentials.")

        main_frame=CTkFrame(master=self)
        main_frame.pack(fill=BOTH, expand=1)

        path = "aurora.jpeg"
        self.img = ImageTk.PhotoImage(Image.open(path))
        Label(master=main_frame,image=self.img,height=650,width=510).place(x=85,y=50)

        frame=CTkFrame(master=main_frame,width=350,height=350,bg="white")
        frame.place(x=480,y=83)

        heading=CTkLabel(master=frame,text="Manager Login",fg="#57a1f8",bg='white',text_font=('Microsoft YaHei UI Light',23))
        heading.place(x=61,y=25)

        #username
        user= CTkEntry(master=frame,width=290,placeholder_text="Username", border=0,bg='white',text_font=('Microsoft YaHei UI Light',11))
        user.place(x=30,y=120)
        ##user.bind('<FocusIn>',on_enter)
        ##user.bind('<FocusOut>',on_leave)
        ##CTkFrame(master=frame,width=295,bg='black').place(x=25,y=107)

        #Password
        passw= customtkinter.CTkEntry(master=frame,width=290,placeholder_text="Password",bg='white',border=0,text_font=('Microsoft YaHei UI Light',11))
        passw.place(x=30,y=180)
        ##passw.bind('<FocusIn>',on_enter)
        ##passw.bind('<FocusOut>',on_leave)
        ##CTkFrame(master=frame,width=295,bg='black').place(x=25,y=177)

        #Submit button
        customtkinter.CTkButton(master=frame,width=190,text="Log in",command=lambda: confirm()).place(x=80,y=270)

class Book_det(CTkFrame):

    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        #For every frame...
        self.controller = controller
        main_frame1=CTkFrame(master=self)
        main_frame1.pack(fill=BOTH, expand=1)

        header=CTkFrame(main_frame1,width=925,height=55,corner_radius=0,fg_color="#57a1f8")
        header.pack()

        man_lab=CTkLabel(header,text="Welcome Manager",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        nav_frame=CTkFrame(main_frame1,width=925,corner_radius=0,fg_color="#1f6aa5",height=35)
        nav_frame.pack(anchor="w",fill=BOTH)

        but1=CTkButton(nav_frame,text="Bookings",fg_color="#144870",corner_radius=0,height=35,width=90,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="Passengers",corner_radius=0,height=35,width=100,command=lambda: controller.show_frame("Pass_det"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but3.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

        fs_frame = CTkFrame(main_frame1)
        fs_frame.pack(fill=BOTH,expand=1,pady=25,padx=25)
       # fs_frame.pack()

        reg_dep = ttk.Treeview(fs_frame,height=18)

        reg_dep['columns'] = ('BookingID', 'Dep_Des_Code', 'Arr_Des_Code', 'Passenger_ID','Departure_Date','Return_Date','Booked_Seat')

        reg_dep.column("#0", width=0,  stretch=NO)
        reg_dep.column('BookingID',anchor=CENTER, width=120)
        reg_dep.column('Dep_Des_Code',anchor=CENTER, width=140)
        reg_dep.column('Arr_Des_Code',anchor=CENTER,width=140)
        reg_dep.column('Passenger_ID',anchor=CENTER,width=140)
        reg_dep.column('Departure_Date',anchor=CENTER,width=160)
        reg_dep.column('Return_Date',anchor=CENTER,width=160)
        reg_dep.column('Booked_Seat',anchor=CENTER,width=140)

        reg_dep.heading("#0",text="",anchor=CENTER)
        reg_dep.heading('BookingID',text='BookingID',anchor=CENTER)
        reg_dep.heading('Dep_Des_Code',text='Dep_Des_Code',anchor=CENTER)
        reg_dep.heading('Arr_Des_Code',text='Arr_Des_Code',anchor=CENTER)
        reg_dep.heading('Passenger_ID',text='Passenger_ID',anchor=CENTER)
        reg_dep.heading('Departure_Date',text='Departure_Date',anchor=CENTER)
        reg_dep.heading('Return_Date',text='Return_Date',anchor=CENTER)
        reg_dep.heading('Booked_Seat',text='Booked_Seat',anchor=CENTER)

        import mysql.connector as mycon
        conn=mycon.connect(host="localhost",user="root",passwd="12345678",database="aurora_airlines")
        cursor=conn.cursor()
        cursor.execute("Select * from bookings;")
        data=cursor.fetchall()
        Records=[]
        for row in data:
                Records.append(row)
        count=cursor.rowcount
        for iid in range(count):
            reg_dep.insert(parent='',index='end',iid=iid,text='',
            values=(Records[iid][0],Records[iid][1],Records[iid][2],Records[iid][3], Records[iid][4],Records[iid][5],Records[iid][6]))
        reg_dep.pack(pady=85)

##        button = customtkinter.CTkButton(main_frame1,corner_radius=0,height=10,text="Go to the start page",
##                           command=lambda: controller.show_frame("StartPage"))
##        button.grid(row=0,column=0)
##        button1 = customtkinter.CTkButton(main_frame1, text="go to page two",
##                           command=lambda: controller.show_frame("PageTwo"))
##        button1.grid(row=0,column=1)

class Pass_det(CTkFrame):

    def __init__(self, parent, controller):
        CTkFrame.__init__(self, parent)
        #For every frame...
        self.controller = controller
        main_frame1=CTkFrame(master=self)
        main_frame1.pack(fill=BOTH, expand=1)

        header=CTkFrame(main_frame1,width=925,height=55,corner_radius=0,fg_color="#57a1f8")
        header.pack()

        man_lab=CTkLabel(header,text="Welcome Manager",bg='white',text_font=('Microsoft YaHei UI Light',23))
        man_lab.place(x=10,y=6)

        nav_frame=CTkFrame(main_frame1,height=37,width=925,corner_radius=0,fg_color="#1f6aa5")
        nav_frame.pack(anchor="w",fill=BOTH,padx=0,pady=0)

        but1=CTkButton(nav_frame,text="Bookings",corner_radius=0,height=35,width=90,command=lambda: controller.show_frame("Book_det"))
        but1.pack(side=LEFT,pady=0,padx=0)

        but2=CTkButton(nav_frame,text="Passengers",fg_color="#144870",corner_radius=0,height=35,width=100,command=lambda: controller.show_frame("Pass_det"))
        but2.pack(side=LEFT,pady=0,padx=0)

        but3=CTkButton(nav_frame,text='',corner_radius=0,height=35,width=1000,state=DISABLED)
        but3.pack(side=LEFT,pady=0,padx=0,fill=BOTH)

        fs_frame = CTkFrame(main_frame1)
        fs_frame.pack(fill=BOTH,expand=1,pady=25,padx=25)
       # fs_frame.pack()

        reg_dep = ttk.Treeview(fs_frame,height=22)
        CTkLabel(fs_frame,text="").pack()
        reg_dep['columns'] = ('Passenger_ID', 'First_Name', 'Last_Name',
                              'Passport_ID', 'Meal_Preference','Phone_number',
                              'Email', 'Class')

        reg_dep.column("#0", width=0,  stretch=NO)
        reg_dep.column('Passenger_ID',anchor=CENTER, width=120)
        reg_dep.column('First_Name',anchor=CENTER, width=140)
        reg_dep.column('Last_Name',anchor=CENTER,width=140)
        reg_dep.column('Passport_ID',anchor=CENTER,width=140)
        reg_dep.column('Meal_Preference',anchor=CENTER,width=160)
        reg_dep.column('Phone_number',anchor=CENTER,width=160)
        reg_dep.column('Email',anchor=CENTER,width=140)
        reg_dep.column('Class',anchor=CENTER,width=160)

        reg_dep.heading("#0",text="",anchor=CENTER)
        reg_dep.heading('Passenger_ID',text='Passenger_ID',anchor=CENTER)
        reg_dep.heading('First_Name',text='First_Name',anchor=CENTER)
        reg_dep.heading('Last_Name',text='Last_Name',anchor=CENTER)
        reg_dep.heading('Passport_ID',text='Passport_ID',anchor=CENTER)
        reg_dep.heading('Meal_Preference',text='Meal_Preference',anchor=CENTER)
        reg_dep.heading('Phone_number',text='Phone_number',anchor=CENTER)
        reg_dep.heading('Email',text='Email',anchor=CENTER)
        reg_dep.heading('Class',text='Class',anchor=CENTER)

        import mysql.connector as mycon
        conn=mycon.connect(host="localhost",user="root",passwd="12345678",database="aurora_airlines")
        cursor=conn.cursor()
        cursor.execute("Select * from passengers;")
        data=cursor.fetchall()
        Records=[]
        for row in data:
                Records.append(row)
        count=cursor.rowcount
        for iid in range(count):
            reg_dep.insert(parent='',index='end',iid=iid,text='',
            values=(Records[iid][0],Records[iid][1],Records[iid][2],Records[iid][3], Records[iid][4],Records[iid][5],Records[iid][6],Records[iid][7]))
        reg_dep.pack(pady=44)

def Display():
    root=SampleApp()
    root.title("Manager_Login")
    root.geometry('925x500+300+200')
    root.resizable(False,False)
    root.configure(bg="white")
    root.mainloop()

I keep getting the 'image "pyimage2" doesn't exist' error. Then when I used the call method, it kept opening another python window which I don't want. I also don't want to merge the above codes into one file since I have a lot of code to add for the other parts of the project.

I apologize for the messy code since these were just test files

I'm just a beginner in python so I might have made some mistakes I'm not aware of. I would be grateful if anyone could help me! Thank you!


来源: stackexchange

问:
Why my create Event function is giving me "An unhandled exception occurred while processing the request"?
Now I am working to fix the Administration Area web page for my ASP .NET Core MVC project. I have an issue with my Create Function. I don't have any idea where is coming from. I am able to access my Create web page. It looks like this
enter image description here
The issue is that when I fill out the form and press the Save button I got an "InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ArtGallery.Core.Models.Administrator.EventCreateInputViewModel', but this ViewDataDictionary instance requires a model item of type 'ArtGallery.Core.Models.Home.IndexViewModel'." Here is a screenshot of the error: enter image description here

Here is my create function from the EventController

```<code>public IActionResult Create()
{
    return this.View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EventCreateInputViewModel model)
{
    if (!this.ModelState.IsValid)
    {
       return this.View(model);
    }

    await eventService.AddAsync(model);
    return Redirect("All");
}
</code>```

My EventService for the Create is:

```<code>   public async Task AddAsync(EventCreateInputViewModel model)
   {
         await _applicationDbContext.Events.AddAsync(new Event
         {
             Name = model.Name,
             Price = model.Price,
             Date = DateTime.ParseExact(model.Date,
                     DateTimeFormat, CultureInfo.InvariantCulture),
             Description = model.Description,
         });

         await _applicationDbContext.SaveChangesAsync();
  }
</code>```

Create View page code:

```<code>@using ArtGallery.Core.Models.Administrator;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model EventCreateInputViewModel
@{
    ViewData["Title"] = "Create Event";
    Layout = "/Areas/Administration/Views/Shared/_AdminLayout.cshtml";
    var evenOne = (List<SelectListItem>)ViewBag.EventType;
    var evenTwo = (List<SelectListItem>)ViewBag.TicketType;
}

<div class="row">
    <div class="col-8">
        <form asp-area="Administration" asp-controller="Event" asp-action="Create" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-floating">
                <label asp-for="Name" class="form-lable"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-floating">
                <label asp-for="Price" class="form-lable"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-floating">
                <label asp-for="Date" class="form-lable"></label>
                <input asp-for="Date" class="form-control" />
                <span asp-validation-for="Date" class="text-danger"></span>
            </div>
            <div class="form-floating">
                <label asp-for="Type" class="form-lable"></label>
                <select asp-for="Type" asp-items="@evenOne" class="form-control">
                    <option selected="selected" value="">Please select...</option>
                    <option selected="selected" value="1">InPerson</option>
                    <option selected="selected" value="2">Online</option>
                </select>
                <span asp-validation-for="Type" class="text-danger"></span>
            </div>
            <div class="form-floating">
                <label asp-for="TicketSelection" class="form-lable"></label>
                <select asp-for="TicketSelection" asp-items="@evenTwo" class="form-control">
                    <option selected="selected" value="">Please select...</option>
                    <option selected="selected" value="1">Free</option>
                    <option selected="selected" value="2">Paid</option>
                </select>
                <span asp-validation-for="TicketSelection" class="text-danger"></span>
            </div>
            <div class="form-floating">
                <label asp-for="Description" class="form-lable"></label>
                <input asp-for="Description" class="form-control" />
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-block btn-success">Save</button>
        </form>
    </div>
</div>
</code>```

This view is working and look like this enter image description here

I try to fix the Create Function by implement it additional Service method

```<code>       public async Task<bool> CreateEventAsync(string name, decimal price, string date,
            string type, string ticketSelection, string description)
        {
            bool isCreated = false;
            var createEvent = new EventCreateInputViewModel();

            if (createEvent != null)
            {
                createEvent.Name = name;
                createEvent.Price = price;
                createEvent.Date = date;
                createEvent.Type = Enum.Parse<EventType>(type);
                createEvent.TicketSelection = Enum.Parse<TicketType>(ticketSelection);
                createEvent.Description = description;

                //this._eventRepo.AddAsync(createEvent);
                //await this._eventRepo.SaveChangesAsync();

                _applicationDbContext.Events.Add(new Event()
                {
                    Name = name,
                    Price = price,
                    Date = Convert.ToDateTime(date),
                    Type = Enum.Parse<EventType>(type),
                    TicketSelection = Enum.Parse<TicketType>(ticketSelection),
                    Description = description,
                    CreatedOn = DateTime.UtcNow,

                });

                _applicationDbContext.SaveChanges();

            }

            return isCreated;
        }
</code>```

It seems that looking for my Index DTO. My index for the Home page with the public access should only get UpcommingEvents and LatestBlogs not saving events. My Create page has to create event and save them in "All Events" web page. The Create DTO that I am using is "EventCreateInputViewModel" but when I try to save my new Event it looking for my Index DTO. I don't have idea why I am getting this issue. It look like to me is my Create page is trying to save my new events using Index DTO. Could somebody help me with this issue, please? Is my code have any issues that it could cause this error?

ContentLicense: CC BY-SA 4.0

Body:
Now I am working to fix the Administration Area web page for my ASP .NET Core MVC project. I have an issue with my Create Function. I don't have any idea where is coming from. I am able to access my Create web page. It looks like this
enter image description here
The issue is that when I fill out the form and press the Save button I got an "InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ArtGallery.Core.Models.Administrator.EventCreateInputViewModel', but this ViewDataDictionary instance requires a model item of type 'ArtGallery.Core.Models.Home.IndexViewModel'." Here is a screenshot of the error: enter image description here

Here is my create function from the EventController

public IActionResult Create()
{
    return this.View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EventCreateInputViewModel model)
{
    if (!this.ModelState.IsValid)
    {
       return this.View(model);
    }

    await eventService.AddAsync(model);
    return Redirect("All");
}

My EventService for the Create is:

   public async Task AddAsync(EventCreateInputViewModel model)
   {
         await _applicationDbContext.Events.AddAsync(new Event
         {
             Name = model.Name,
             Price = model.Price,
             Date = DateTime.ParseExact(model.Date,
                     DateTimeFormat, CultureInfo.InvariantCulture),
             Description = model.Description,
         });

         await _applicationDbContext.SaveChangesAsync();
  }

Create View page code:

@using ArtGallery.Core.Models.Administrator;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model EventCreateInputViewModel
@{
    ViewData["Title"] = "Create Event";
    Layout = "/Areas/Administration/Views/Shared/_AdminLayout.cshtml";
    var evenOne = (List<SelectListItem>)ViewBag.EventType;
    var evenTwo = (List<SelectListItem>)ViewBag.TicketType;
}

        <form asp-area="Administration" asp-controller="Event" asp-action="Create" method="post">

                <input asp-for="Name" class="form-control" />

                <input asp-for="Price" class="form-control" />

                <input asp-for="Date" class="form-control" />

                <select asp-for="Type" asp-items="@evenOne" class="form-control">
                    <option selected="selected" value="">Please select...</option>
                    <option selected="selected" value="1">InPerson</option>
                    <option selected="selected" value="2">Online</option>
                </select>

                <select asp-for="TicketSelection" asp-items="@evenTwo" class="form-control">
                    <option selected="selected" value="">Please select...</option>
                    <option selected="selected" value="1">Free</option>
                    <option selected="selected" value="2">Paid</option>
                </select>

                <input asp-for="Description" class="form-control" />

            <button type="submit" class="btn btn-block btn-success">Save</button>
        </form>

This view is working and look like this enter image description here

I try to fix the Create Function by implement it additional Service method

       public async Task<bool> CreateEventAsync(string name, decimal price, string date,
            string type, string ticketSelection, string description)
        {
            bool isCreated = false;
            var createEvent = new EventCreateInputViewModel();

            if (createEvent != null)
            {
                createEvent.Name = name;
                createEvent.Price = price;
                createEvent.Date = date;
                createEvent.Type = Enum.Parse<EventType>(type);
                createEvent.TicketSelection = Enum.Parse<TicketType>(ticketSelection);
                createEvent.Description = description;

                //this._eventRepo.AddAsync(createEvent);
                //await this._eventRepo.SaveChangesAsync();

                _applicationDbContext.Events.Add(new Event()
                {
                    Name = name,
                    Price = price,
                    Date = Convert.ToDateTime(date),
                    Type = Enum.Parse<EventType>(type),
                    TicketSelection = Enum.Parse<TicketType>(ticketSelection),
                    Description = description,
                    CreatedOn = DateTime.UtcNow,

                });

                _applicationDbContext.SaveChanges();

            }

            return isCreated;
        }

It seems that looking for my Index DTO. My index for the Home page with the public access should only get UpcommingEvents and LatestBlogs not saving events. My Create page has to create event and save them in "All Events" web page. The Create DTO that I am using is "EventCreateInputViewModel" but when I try to save my new Event it looking for my Index DTO. I don't have idea why I am getting this issue. It look like to me is my Create page is trying to save my new events using Index DTO. Could somebody help me with this issue, please? Is my code have any issues that it could cause this error?


问:
Android Studio won't install from scratch and directly launches on running the .exe
I was facing some issues with my Android Studio, related to the SDK Manager and SDK itself. I tried to fix them but nothing worked. So I thought to uninstall Android Studio and set it up from scratch again.

But when I install the .exe file from the site and run it, it directly launches Android Studio without asking me to set it up again. I've deleted the Android folder, the gradle folder, everything I could think of to not have the app revert back to old settings. But it just launches on its own without letting me set everything up from scratch.

I tried uninstalling Android Studio from my system along with the files and folders I could think of. I tried installing Android Studio from the site, just the exe and also the zip file (also different versions of the same). But still, upon running the application it just launches Android Studio without asking me to set anything up.


问:
How could I create an array using a field id in a field form
I have a form with the following text fields that I would want to push as an array:

```<code><input type="text" name="qty" placeholder="regular-price" class="ticket-quantity" id="tickets" value="1">
<input type="text" name="qty" placeholder="vip-price" class="ticket-quantity" id="tickets" value="1">
<input type="text" name="qty" placeholder="viip-price" class="ticket-quantity" id="tickets" value="1">
</code>```

Am using this function but not getting the desired output:

```<code>var tickets = [];
    $.each($("input#tickets"), function(){
    var quantity = $(this).parent().find('input.ticket-quantity').val();
    tickets.push({"tickets" : $(this).val(), "value" : quantity});
    });
    ajax_data.tickets = tickets;
</code>```

How do I write my Javascript to pull:

```<code>tickets[0][ticket]  "regular-ticket"
tickets[0][value]   "2"
tickets[1][ticket]  "vip-ticket"
tickets[1][value]   "1"
tickets[2][ticket]  "viip-ticket"
tickets[2][value]   "0"
</code>```

Body:
I have a form with the following text fields that I would want to push as an array:

<input type="text" name="qty" placeholder="regular-price" class="ticket-quantity" id="tickets" value="1">
<input type="text" name="qty" placeholder="vip-price" class="ticket-quantity" id="tickets" value="1">
<input type="text" name="qty" placeholder="viip-price" class="ticket-quantity" id="tickets" value="1">

Am using this function but not getting the desired output:

var tickets = [];
    $.each($("input#tickets"), function(){
    var quantity = $(this).parent().find('input.ticket-quantity').val();
    tickets.push({"tickets" : $(this).val(), "value" : quantity});
    });
    ajax_data.tickets = tickets;

How do I write my Javascript to pull:

tickets[0][ticket]  "regular-ticket"
tickets[0][value]   "2"
tickets[1][ticket]  "vip-ticket"
tickets[1][value]   "1"
tickets[2][ticket]  "viip-ticket"
tickets[2][value]   "0"


问:
Get custom Error message from backend API and access on frontend
I am working on an Angular 9 project with a Flask backend server. In some of my API's there are multiple checks and areas where it can fail and I want to return custom messages to the frontend but I can't seem to access the error message.

As an example, if this was a basic route:

```<code>@app.route('/api/test/<int:test_id>/', method=['PUT', 'OPTIONS])
def test_route(test_id):
  if test_id < 0:
    abort(400, f'Custom Error Message')
  else:
    #Query data base, update something, return updated entry...
</code>```

And this was my service function on the frontend (API_URL refers to the root url for the backend):

```<code>callTestRoute(id: number): Observable<any> {
   const url = `${API_URL}/test/id/`;
   return this.http.put(url, httpOptions);
}
</code>```

And in my component where I call the service function:

```<code>updateEntry(id:number) {
  this.db_api.callTestRoute(id).subscribe( success => {
    console.log(success);
  }, (error: HttpErrorResponse) => {
    console.log("API ERROR RESP: ", error);
  }
}
</code>```

In the console, my logged message above outputs
"API ERROR RESP: Error Code: 400
Message: Https failure response for http://slate:3660/test/66/: 400 BAD REQUEST"

however, the network request response shows my custom error message. I cannot access this message within my angular component.

I have tried using jsonify() to return the error in my API like:
return jsonify({'errMsg': "Custom error message"}), 400

but I can still not access the error message, when I try to access error.error or any fields, they all show undefined. How do I return a custom message for failed API requests and how do I access those messages on the frontend?

Body:
I am working on an Angular 9 project with a Flask backend server. In some of my API's there are multiple checks and areas where it can fail and I want to return custom messages to the frontend but I can't seem to access the error message.

As an example, if this was a basic route:

@app.route('/api/test/<int:test_id>/', method=['PUT', 'OPTIONS])
def test_route(test_id):
  if test_id < 0:
    abort(400, f'Custom Error Message')
  else:
    #Query data base, update something, return updated entry...

And this was my service function on the frontend (API_URL refers to the root url for the backend):

callTestRoute(id: number): Observable<any> {
   const url = `${API_URL}/test/id/`;
   return this.http.put(url, httpOptions);
}

And in my component where I call the service function:

updateEntry(id:number) {
  this.db_api.callTestRoute(id).subscribe( success => {
    console.log(success);
  }, (error: HttpErrorResponse) => {
    console.log("API ERROR RESP: ", error);
  }
}

In the console, my logged message above outputs
"API ERROR RESP: Error Code: 400
Message: Https failure response for http://slate:3660/test/66/: 400 BAD REQUEST"

however, the network request response shows my custom error message. I cannot access this message within my angular component.

I have tried using jsonify() to return the error in my API like:
return jsonify({'errMsg': "Custom error message"}), 400

but I can still not access the error message, when I try to access error.error or any fields, they all show undefined. How do I return a custom message for failed API requests and how do I access those messages on the frontend?


问:
Can I deploy an event trigger to Function App via Bicep?
I aim to create such a bicep file that would deploy a function app with an event trigger in it, however, I'm not sure if it's possible. I've tried googling but Function App deployment via bicep tutorials tend to stop right after the deployment of an empty function app. I need to go a step further and add triggers to it.

Why do I want to deploy at least an empty event trigger via bicep?

The core of the issue is: I would like to perform two stages of CD, where the first one will be all about bicep (preparing all of the resources) and the second one about code deployment.

However, at the first CD stage, the following error occurs:

{"code":"Endpoint validation","message":"Destination endpoint not
found. Resource details: resourceId:
/subscriptions/.../functionAppNameHere/functions/eventTriggerFuncName.
Resource should pre-exist before attempting this operation.}

I assume that EventGrid EventSubscriptions requires prior presence of a resource with the trigger (seems understandable though).

Is it even possible to add an event trigger via bicep so it would move smoothly to event subscription creation? If yes: can you please give me some tips?, if no: do you have any ideas on how to circumvent this?

Here are my bicep files that may come in handy when thinking about the issue:

main.bicep

```<code>module azStorageAccount 'modules/azStorageAccount.bicep'=  {
  name: '${deployName}-st'
  params: {
    location: location
    name: '${stNamePrefix}${resourceSuffix}'
  }
}

module azAppInsights 'modules/azAppInsights.bicep' = {
  name: '${deployName}-appi'
  params: {
    location: location
    name: '${appiNamePrefix}${resourceSuffix}'
  }
}

module azHostingPlan 'modules/azHostingPlan.bicep' = {
  name: '${deployName}-asp'
  params: {
    location: location
    name: '${aspNamePrefix}${resourceSuffix}'
  }
}

module azFunctionApp 'modules/azFunctionApp.bicep' = {
  name: '${deployName}-func'
  params: {
    storageId:azStorageAccount.outputs.storageId
    storageName: azStorageAccount.outputs.storageName
    azAppInsightsInstrumentationKey: azAppInsights.outputs.azAppInsightsInstrumentationKey

    location: location
    name: '${funcNamePrefix}${resourceSuffix}'
    serverFarmId: azHostingPlan.outputs.azHostingPlaniD

  }
}

module azEventGrid 'modules/azEventGrid.bicep' = {
  name: '${deployName}-evg'
  params: {
    subscription: subscription
    evgtName: '${evgtNamePrefix}${resourceSuffix}'
    evgsName: '${evgsNamePrefix}${resourceSuffix}'
    resourceId: '/subscriptions/${subscription}/resourceGroups/${resourceGroup}/providers/Microsoft.Web/sites/${funcNamePrefix}${resourceSuffix}/functions/${eventFunction}'
  }
}
</code>```

modules/azFunctionApp

```<code>// params here

resource azFunctionApp 'Microsoft.Web/sites@2021-03-01' = {
  name: name
  kind: kind
  location: location
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    httpsOnly: true
    serverFarmId: serverFarmId

    clientAffinityEnabled: true
    reserved: true

    siteConfig: {
      appSettings: [
        {
          name: 'FUNCTIONS_EXTENSION_VERSION'
          value: '~3'
        }
        // more settings here
      ]
      alwaysOn: false
    }
  }
}
</code>```

modules/azEventGrid

```<code>// params here

resource azEventGridSystemTopic 'Microsoft.EventGrid/systemTopics@2022-06-15' = {
  name: evgtName
  location: 'global'
  tags: {
    // tags
  }
  properties: {
    source: '/subscriptions/${subscription}'
    topicType: 'Microsoft.Resources.Subscriptions'
  }
}
resource azEventGridEventSubscriptions 'Microsoft.EventGrid/systemTopics/eventSubscriptions@2022-06-15' = {
  parent: azEventGridSystemTopic
  name: evgsName
  properties: {
    destination: {
      properties: {
        resourceId: resourceId
        maxEventsPerBatch: 1
        preferredBatchSizeInKilobytes: 64
      }
      endpointType: 'AzureFunction'
    }
    filter: {
      includedEventTypes: [
        'Microsoft.Resources.ResourceWriteSuccess'
        'Microsoft.Resources.ResourceDeleteSuccess'
      ]
      enableAdvancedFilteringOnArrays: true
    }
    labels: []
    eventDeliverySchema: 'EventGridSchema'
    retryPolicy: {
      maxDeliveryAttempts: 30
      eventTimeToLiveInMinutes: 1440
    }
  }
}
</code>```

Body:
I aim to create such a bicep file that would deploy a function app with an event trigger in it, however, I'm not sure if it's possible. I've tried googling but Function App deployment via bicep tutorials tend to stop right after the deployment of an empty function app. I need to go a step further and add triggers to it.

Why do I want to deploy at least an empty event trigger via bicep?

The core of the issue is: I would like to perform two stages of CD, where the first one will be all about bicep (preparing all of the resources) and the second one about code deployment.

However, at the first CD stage, the following error occurs:

{"code":"Endpoint validation","message":"Destination endpoint not
found. Resource details: resourceId:
/subscriptions/.../functionAppNameHere/functions/eventTriggerFuncName.
Resource should pre-exist before attempting this operation.}

I assume that EventGrid EventSubscriptions requires prior presence of a resource with the trigger (seems understandable though).

Is it even possible to add an event trigger via bicep so it would move smoothly to event subscription creation? If yes: can you please give me some tips?, if no: do you have any ideas on how to circumvent this?

Here are my bicep files that may come in handy when thinking about the issue:

main.bicep

module azStorageAccount 'modules/azStorageAccount.bicep'=  {
  name: '${deployName}-st'
  params: {
    location: location
    name: '${stNamePrefix}${resourceSuffix}'
  }
}

module azAppInsights 'modules/azAppInsights.bicep' = {
  name: '${deployName}-appi'
  params: {
    location: location
    name: '${appiNamePrefix}${resourceSuffix}'
  }
}

module azHostingPlan 'modules/azHostingPlan.bicep' = {
  name: '${deployName}-asp'
  params: {
    location: location
    name: '${aspNamePrefix}${resourceSuffix}'
  }
}

module azFunctionApp 'modules/azFunctionApp.bicep' = {
  name: '${deployName}-func'
  params: {
    storageId:azStorageAccount.outputs.storageId
    storageName: azStorageAccount.outputs.storageName
    azAppInsightsInstrumentationKey: azAppInsights.outputs.azAppInsightsInstrumentationKey

    location: location
    name: '${funcNamePrefix}${resourceSuffix}'
    serverFarmId: azHostingPlan.outputs.azHostingPlaniD

  }
}

module azEventGrid 'modules/azEventGrid.bicep' = {
  name: '${deployName}-evg'
  params: {
    subscription: subscription
    evgtName: '${evgtNamePrefix}${resourceSuffix}'
    evgsName: '${evgsNamePrefix}${resourceSuffix}'
    resourceId: '/subscriptions/${subscription}/resourceGroups/${resourceGroup}/providers/Microsoft.Web/sites/${funcNamePrefix}${resourceSuffix}/functions/${eventFunction}'
  }
}

modules/azFunctionApp

// params here

resource azFunctionApp 'Microsoft.Web/sites@2021-03-01' = {
  name: name
  kind: kind
  location: location
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    httpsOnly: true
    serverFarmId: serverFarmId

    clientAffinityEnabled: true
    reserved: true

    siteConfig: {
      appSettings: [
        {
          name: 'FUNCTIONS_EXTENSION_VERSION'
          value: '~3'
        }
        // more settings here
      ]
      alwaysOn: false
    }
  }
}

modules/azEventGrid

// params here

resource azEventGridSystemTopic 'Microsoft.EventGrid/systemTopics@2022-06-15' = {
  name: evgtName
  location: 'global'
  tags: {
    // tags
  }
  properties: {
    source: '/subscriptions/${subscription}'
    topicType: 'Microsoft.Resources.Subscriptions'
  }
}
resource azEventGridEventSubscriptions 'Microsoft.EventGrid/systemTopics/eventSubscriptions@2022-06-15' = {
  parent: azEventGridSystemTopic
  name: evgsName
  properties: {
    destination: {
      properties: {
        resourceId: resourceId
        maxEventsPerBatch: 1
        preferredBatchSizeInKilobytes: 64
      }
      endpointType: 'AzureFunction'
    }
    filter: {
      includedEventTypes: [
        'Microsoft.Resources.ResourceWriteSuccess'
        'Microsoft.Resources.ResourceDeleteSuccess'
      ]
      enableAdvancedFilteringOnArrays: true
    }
    labels: []
    eventDeliverySchema: 'EventGridSchema'
    retryPolicy: {
      maxDeliveryAttempts: 30
      eventTimeToLiveInMinutes: 1440
    }
  }
}


问:
Marketo API export lead job fails with "Invalid smartListId" error
We are trying to export leads via Bulk Lead Extract Marketo API endpoint using smartListId filter.

Create lead export job:

Enqueue lead export job:

The job fails with "Invalid smartListId 2017":

We are having trouble understanding what might be preventing this job from succeeding. The smart list in question does not seem to be special in any way:

```<code>GET {{endpoint}}/rest/asset/v1/smartList/2017.json?includeRules=true

{
    "success": true,
    "errors": [],
    "requestId": "a435...9089f2",
    "warnings": [],
    "result": [
        {
            "id": 2017,
            "name": "Sync Error",
            "description": "jh",
            "createdAt": "2018-07-18T20:20:22Z+0000",
            "updatedAt": "2022-08-16T16:55:27Z+0000",
            "url": "https://app-sj24.marketo.com/#SL2017A1LA1",
            "folder": {
                "id": 1010,
                "type": "Program"
            },
            "workspace": "Default",
            "rules": {
                "filterMatchType": "all",
                "triggers": [],
                "filters": []
            }
        }
    ]
}

</code>```

What could be the reason for this smart list not working with the bulk lead extraction endpoint?

Body:
We are trying to export leads via Bulk Lead Extract Marketo API endpoint using smartListId filter.

Create lead export job:

Enqueue lead export job:

The job fails with "Invalid smartListId 2017":

We are having trouble understanding what might be preventing this job from succeeding. The smart list in question does not seem to be special in any way:

GET {{endpoint}}/rest/asset/v1/smartList/2017.json?includeRules=true

{
    "success": true,
    "errors": [],
    "requestId": "a435...9089f2",
    "warnings": [],
    "result": [
        {
            "id": 2017,
            "name": "Sync Error",
            "description": "jh",
            "createdAt": "2018-07-18T20:20:22Z+0000",
            "updatedAt": "2022-08-16T16:55:27Z+0000",
            "url": "https://app-sj24.marketo.com/#SL2017A1LA1",
            "folder": {
                "id": 1010,
                "type": "Program"
            },
            "workspace": "Default",
            "rules": {
                "filterMatchType": "all",
                "triggers": [],
                "filters": []
            }
        }
    ]
}

What could be the reason for this smart list not working with the bulk lead extraction endpoint?


问:
Python: Getting Local Nameserver information from Windows 95/XP/7
I'm trying to get local nameserver information for a reverse DNS lookup. In Linux I can parse the resolv.conf file. How do I get the same information for Windows programmatically using Python? What I'm looking for is an IP similar to 192.168.0.1 or 192.168.2.2.</p>

ContentLicense: CC BY-SA 3.0


问:
Add a text file as a resource in Visual Studio 2022
I am creating a WebView2 app (WPF using C#) and I want to have a index.html file as a resource.
The idea is that when I create a project, a new folder is created.
This folder will contain an index.html file for the WebView control to load.
The index.html file then points to project specific data as relative paths.

I would like to have a file embedded in my resources that I can use at runtime like this

```<code>`void newProject()
{
   string strHTML = /** code to read from resource file **/
   createFile(projDir + "\\index.html") /** code to create a new file **/
   /** code to write strHTML string to new index.html file **/
}
`
</code>```

I know I can create a static string to do this, but editing is easier if I have the resource as a file.

Thanks in advance.

D

Update:
I put the file into the resources. Then, I added this code

```<code>var assem = Assembly.GetExecutingAssembly();
String[] resources = assem.GetManifestResourceNames();
html = assem.GetManifestResourceStream("index.html")
</code>```

The resources string array always has two elements regardless of what I have in my resources file.
"WebView2Testing.g.resources"
"WebView2Testing.Properties.Resources.resources"
which has nothing to do with my file.
GetManifestResourceStream("index.html") returns null.

FYI I am using .net6 and WPF Windows app.

Any more ideas?

Body:
I am creating a WebView2 app (WPF using C#) and I want to have a index.html file as a resource.
The idea is that when I create a project, a new folder is created.
This folder will contain an index.html file for the WebView control to load.
The index.html file then points to project specific data as relative paths.

I would like to have a file embedded in my resources that I can use at runtime like this

`void newProject()
{
   string strHTML = /** code to read from resource file **/
   createFile(projDir + "\\index.html") /** code to create a new file **/
   /** code to write strHTML string to new index.html file **/
}
`

I know I can create a static string to do this, but editing is easier if I have the resource as a file.

Thanks in advance.

D

Update:
I put the file into the resources. Then, I added this code

var assem = Assembly.GetExecutingAssembly();
String[] resources = assem.GetManifestResourceNames();
html = assem.GetManifestResourceStream("index.html")

The resources string array always has two elements regardless of what I have in my resources file.
"WebView2Testing.g.resources"
"WebView2Testing.Properties.Resources.resources"
which has nothing to do with my file.
GetManifestResourceStream("index.html") returns null.

FYI I am using .net6 and WPF Windows app.

Any more ideas?


问:
Retain pandas dtype 'category' when using parquet file
I am using parquet to store pandas dataframes, and would like to keep the dtype of columns.
However It sometimes ins't working:
here is the example code:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'a': [pd.NA, 'a', 'b', 'c'],
    'b': [1,2,3,pd.NA] # dataframe has type pd.NA in it.
})

df['b'] = df['b'].astype("category")
df['a'] = df['a'].astype("category") # with this columsn works

print ("dtype before parquet write/read: ", df.dtypes, sep='\n')
df.to_parquet('trial.parquet.gzip',
              compression='gzip')

df = pd.read_parquet('trial.parquet.gzip')
print ("dtype after parquet write/read:", df.dtypes, sep='\n')

**OUT**:
dtype before parquet write/read:
a    category
b    category
dtype: object
dtype before parquet write/read:
a    category
b     float64
dtype: object
```


问:
Function to sum a column from start date until today and the same time frame before start date in python
The function i use do not work well, the amount of turnover before and after are not representative of the real turnover of the customer. Maybe an expert eye will understand why and can explain to me the issue there</p>
```<code>def sum_func(df: pd.DataFrame, start_date: str, date_col: str, sum_col: str):
    """
    Function to sum a column from start date until today and the same time frame before start date.

    Arguments:
        df: Original DataFrame
        start_date: when to start summing until today
        date_col: Name of the date Column
        sum_col: Name of the Column to sum

    Returns:
        Dictionary containing the sum "after" and "before"
    """
    selected_df = df.loc[
        (df[date_col] >= pd.to_datetime(df[start_date]))
        & (df[date_col] <= pd.Timestamp.today())
    ].copy()

    selected_df_before = (
        df.loc[(df[date_col] < pd.to_datetime(df[start_date]))]
        .iloc[-selected_df.shape[0] :]
        .copy()
    )

    assert (
        selected_df_before.shape[0] == selected_df.shape[0]
    ), "Error: Not enough time before start date"

    return {
        "after": selected_df.groupby(['customer_no'])[sum_col].sum(),
        "before": selected_df_before.groupby(['customer_no'])[sum_col].sum(),
    }
</code>```

Body:
The function i use do not work well, the amount of turnover before and after are not representative of the real turnover of the customer. Maybe an expert eye will understand why and can explain to me the issue there

def sum_func(df: pd.DataFrame, start_date: str, date_col: str, sum_col: str):
    """
    Function to sum a column from start date until today and the same time frame before start date.

    Arguments:
        df: Original DataFrame
        start_date: when to start summing until today
        date_col: Name of the date Column
        sum_col: Name of the Column to sum

    Returns:
        Dictionary containing the sum "after" and "before"
    """
    selected_df = df.loc[
        (df[date_col] >= pd.to_datetime(df[start_date]))
        & (df[date_col] <= pd.Timestamp.today())
    ].copy()

    selected_df_before = (
        df.loc[(df[date_col] < pd.to_datetime(df[start_date]))]
        .iloc[-selected_df.shape[0] :]
        .copy()
    )

    assert (
        selected_df_before.shape[0] == selected_df.shape[0]
    ), "Error: Not enough time before start date"

    return {
        "after": selected_df.groupby(['customer_no'])[sum_col].sum(),
        "before": selected_df_before.groupby(['customer_no'])[sum_col].sum(),
    }


问:
How to generate a CSV and return to browser in response
I'm trying to use the LinqToCsv NuGet package to output a CSV file to the browser. Creating the CSV part was previously done using a StringBuilder class, however we are trying to swap this out as it was messy.

Here is the code:

```<code>public HttpResponse ExportMessagesAsCSVNew()
{
    var messages = _myService.GetMessages();

    CsvContext cc = new CsvContext();

    MemoryStream memoryStream = new MemoryStream();
    TextWriter tw = new StreamWriter(memoryStream);

    cc.Write(messages, tw);

    var response = System.Web.HttpContext.Current.Response;

    response.BufferOutput = true;
    response.Clear();
    response.ClearHeaders();
    response.ContentEncoding = Encoding.Unicode;
    response.AddHeader("content-disposition", "attachment; filename=Messages.csv ");
    response.ContentType = "text/csv";
    response.Write(tw);
    response.End();

    return response;
}
</code>```

When I open the CSV from the browser, I just get the string System.IO.StreamWriter outputted.

Question

How can I successfully create a CSV in the memory stream using LinqToCsv and then output it to the browser using the http response without having to physically create the file and store it on a drive somewhere?

Body:
I'm trying to use the LinqToCsv NuGet package to output a CSV file to the browser. Creating the CSV part was previously done using a StringBuilder class, however we are trying to swap this out as it was messy.

Here is the code:

public HttpResponse ExportMessagesAsCSVNew()
{
    var messages = _myService.GetMessages();

    CsvContext cc = new CsvContext();

    MemoryStream memoryStream = new MemoryStream();
    TextWriter tw = new StreamWriter(memoryStream);

    cc.Write(messages, tw);

    var response = System.Web.HttpContext.Current.Response;

    response.BufferOutput = true;
    response.Clear();
    response.ClearHeaders();
    response.ContentEncoding = Encoding.Unicode;
    response.AddHeader("content-disposition", "attachment; filename=Messages.csv ");
    response.ContentType = "text/csv";
    response.Write(tw);
    response.End();

    return response;
}

When I open the CSV from the browser, I just get the string System.IO.StreamWriter outputted.

Question

How can I successfully create a CSV in the memory stream using LinqToCsv and then output it to the browser using the http response without having to physically create the file and store it on a drive somewhere?


问:
Running R scripts inside Spring on K8
Does anyone know if its possible to run R script inside spring boot and deployed on K8, The R script would need access to a DB. So anyone have any pointers or maybe a tutorial i can read.</p>

Title: Running R scripts inside Spring on K8


问:
Tootlip inside TextField helperText when error is true
I have a TextField like that:

```<code>          <TextField
            label='שם סקופ'
            onChange={(e) => onChangeValue('scopeName', e.target.value)}
            error={error.scopeNameError !== ''}
            helperText={error.scopeNameError}
          />
</code>```

For now I only display some message if the input is incorrect, but I want to add a tooltip there so I can give the user instructions of what to do. I tried followed the mui documentation but when I added the tooltip it broke the element and written over the next TextField like shown in the picture here

This is the code I wrote which have broken:

```<code><TextField
        label='שם סקופ'
        onChange={(e) => onChangeValue('scopeName', e.target.value)}
         error={error.scopeNameError !== ''}
         helperText={
          error.scopeNameError !== '' ? (
           <Tooltip title='שם סקופ אסור להכין תווים מיוחדים או רק מספרים'>
               <Button>{error.scopeNameError}</Button>
           </Tooltip>) : (error.scopeNameError)
     }/>
</code>```

Body:
I have a TextField like that:

          <TextField
            label='שם סקופ'
            onChange={(e) => onChangeValue('scopeName', e.target.value)}
            error={error.scopeNameError !== ''}
            helperText={error.scopeNameError}
          />

For now I only display some message if the input is incorrect, but I want to add a tooltip there so I can give the user instructions of what to do. I tried followed the mui documentation but when I added the tooltip it broke the element and written over the next TextField like shown in the picture here

This is the code I wrote which have broken:

<TextField
        label='שם סקופ'
        onChange={(e) => onChangeValue('scopeName', e.target.value)}
         error={error.scopeNameError !== ''}
         helperText={
          error.scopeNameError !== '' ? (
           <Tooltip title='שם סקופ אסור להכין תווים מיוחדים או רק מספרים'>
               <Button>{error.scopeNameError}</Button>
           </Tooltip>) : (error.scopeNameError)
     }/>


问:
How to react-paginate with local data?
I'm learning react and have 1 problem:

My list items page:

```<code>import React from "react";
import carsData from "../../data/CarsData";
import ReactDOM from 'react-dom';
import ReactPaginate from 'react-paginate';
import {
  CarItem,
  CarImage,
  CarBody,
  CarName,
  CarAttributesContainer,
  CarAttributesIcon,
  CarPrice,
  CarButtonLink,
} from "./CarSectionItemElements";
import MileageImg from "../../../img/mileage.png";
import EngineImg from "../../../img/engine.png";
import FuelImg from "../../../img/fuelType.png";
import TransImg from "../../../img/transmission.png";
import DriveImg from "../../../img/driveTrain.png";
import BootImg from "../../../img/bootType.png";

const CarSectionItem = () => {
  /*this is the list of items mapped from local data file i have. i want to make pagination for this list. */
  const products = carsData.map((product) => {
    return (
      <CarItem key={product.id}>
        <CarImage to={`/catalog/${product.id}`} target="_blank" >
          <img src={product.image[0]} />
        </CarImage>
        <CarBody>
          <CarName>
            <p>{product.title}</p>
          </CarName>
          <CarAttributesContainer>
            <CarAttributesIcon>
              <img src={MileageImg} />
              <span>{product.mileage}</span>
            </CarAttributesIcon>
            <CarAttributesIcon>
              <img src={EngineImg} />
              <span>{product.engine}</span>
            </CarAttributesIcon>
            <CarAttributesIcon>
              <img src={FuelImg} />
              <span>{product.fuelType}</span>
            </CarAttributesIcon>
            <CarAttributesIcon>
              <img src={TransImg} />
              <span>{product.transmission}</span>
            </CarAttributesIcon>
            <CarAttributesIcon>
              <img src={DriveImg} />
              <span>{product.driveTrain}</span>
            </CarAttributesIcon>
            <CarAttributesIcon>
              <img src={BootImg} />
              <span>{product.bootType}</span>
            </CarAttributesIcon>
          </CarAttributesContainer>
          <CarPrice>
            <p>{product.price}</p>
          </CarPrice>
        </CarBody>
        <CarButtonLink to={`/catalog/${product.id}`} target="_blank">
          {product.buttonLabel}
        </CarButtonLink>
      </CarItem>
    );
  });

  /* react paginate library */
  function PaginatedItems({ itemsPerPage }) {
    const [currentItems, setCurrentItems] = useState(null);
    const [pageCount, setPageCount] = useState(0);
    const [itemOffset, setItemOffset] = useState(0);
    const itemsPerPage = 6;

    useEffect(() => {
      const endOffset = itemOffset + itemsPerPage;
      setPageCount(Math.ceil(items.length / itemsPerPage));
    }, [itemOffset, itemsPerPage]);

    const handlePageClick = (event) => {
      const newOffset = event.selected * itemsPerPage % items.length;
      setItemOffset(newOffset);
    };

    return (
      <>
        <Items currentItems={currentItems} />
        <ReactPaginate
          nextLabel=">"
          onPageChange={handlePageClick}
          pageRangeDisplayed={3}
          marginPagesDisplayed={2}
          pageCount={pageCount}
          previousLabel="<"
          pageClassName="page-item"
          pageLinkClassName="page-link"
          previousClassName="page-item"
          previousLinkClassName="page-link"
          nextClassName="page-item"
          nextLinkClassName="page-link"
          breakLabel="..."
          breakClassName="page-item"
          breakLinkClassName="page-link"
          containerClassName="pagination"
          activeClassName="active"
          renderOnZeroPageCount={null}
        />
      </>
    );
  }

  return <>{products}</>;
};
export default CarSectionItem;
</code>```

CarsSection where all the components including CarsSectionItem is stored:

```<code>import React, { useState } from "react";
import { CarsSectionContainer, CarsContainer } from "./CarsSectionElements";
import CarsFilter from "./CarsFilter/CarsFilter";
import CarSectionItem from "./СarSectionItem/CarSectionItem";
import { carsData } from "../data/CarsData";

const CarsSection = () => {

  return (
    <CarsSectionContainer>
      <CarsFilter/>
      <CarsContainer>
        <CarSectionItem />
      </CarsContainer>
    </CarsSectionContainer>
  );
};

export default CarsSection;
</code>```

My local data file  :

```<code>import Car1 from '../../img/car1.jpg'
import Car2 from '../../img/car2.jpg'
const carsData = [
  {
    id: '1',
    image: [Car1, Car1, Car1, Car1],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  {
    id: '2',
    image: [Car2, Car2, Car2, Car2],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  {
    id: '3',
    image: [Car1, Car1, Car1, Car1],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  {
    id: '4',
    image: [Car1, Car1, Car1, Car1],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  ];

  export default carsData;
</code>```

How can i make a pagination using my local data? I saw lots of tutorials how to make pagination using fetch data. But can't make it using local data.

Title: How to react-paginate with local data?

Body:
I'm learning react and have 1 problem:

My list items page:

import React from "react";
import carsData from "../../data/CarsData";
import ReactDOM from 'react-dom';
import ReactPaginate from 'react-paginate';
import {
  CarItem,
  CarImage,
  CarBody,
  CarName,
  CarAttributesContainer,
  CarAttributesIcon,
  CarPrice,
  CarButtonLink,
} from "./CarSectionItemElements";
import MileageImg from "../../../img/mileage.png";
import EngineImg from "../../../img/engine.png";
import FuelImg from "../../../img/fuelType.png";
import TransImg from "../../../img/transmission.png";
import DriveImg from "../../../img/driveTrain.png";
import BootImg from "../../../img/bootType.png";

const CarSectionItem = () => {
  /*this is the list of items mapped from local data file i have. i want to make pagination for this list. */
  const products = carsData.map((product) => {
    return (
      <CarItem key={product.id}>
        <CarImage to={`/catalog/${product.id}`} target="_blank" >

        </CarImage>
        <CarBody>
          <CarName>

{product.title}

          </CarName>
          <CarAttributesContainer>
            <CarAttributesIcon>

              {product.mileage}
            </CarAttributesIcon>
            <CarAttributesIcon>

              {product.engine}
            </CarAttributesIcon>
            <CarAttributesIcon>

              {product.fuelType}
            </CarAttributesIcon>
            <CarAttributesIcon>

              {product.transmission}
            </CarAttributesIcon>
            <CarAttributesIcon>

              {product.driveTrain}
            </CarAttributesIcon>
            <CarAttributesIcon>

              {product.bootType}
            </CarAttributesIcon>
          </CarAttributesContainer>
          <CarPrice>

{product.price}

          </CarPrice>
        </CarBody>
        <CarButtonLink to={`/catalog/${product.id}`} target="_blank">
          {product.buttonLabel}
        </CarButtonLink>
      </CarItem>
    );
  });

  /* react paginate library */
  function PaginatedItems({ itemsPerPage }) {
    const [currentItems, setCurrentItems] = useState(null);
    const [pageCount, setPageCount] = useState(0);
    const [itemOffset, setItemOffset] = useState(0);
    const itemsPerPage = 6;

    useEffect(() => {
      const endOffset = itemOffset + itemsPerPage;
      setPageCount(Math.ceil(items.length / itemsPerPage));
    }, [itemOffset, itemsPerPage]);

    const handlePageClick = (event) => {
      const newOffset = event.selected * itemsPerPage % items.length;
      setItemOffset(newOffset);
    };

    return (
      <>
        <Items currentItems={currentItems} />
        <ReactPaginate
          nextLabel=">"
          onPageChange={handlePageClick}
          pageRangeDisplayed={3}
          marginPagesDisplayed={2}
          pageCount={pageCount}
          previousLabel="<"
          pageClassName="page-item"
          pageLinkClassName="page-link"
          previousClassName="page-item"
          previousLinkClassName="page-link"
          nextClassName="page-item"
          nextLinkClassName="page-link"
          breakLabel="..."
          breakClassName="page-item"
          breakLinkClassName="page-link"
          containerClassName="pagination"
          activeClassName="active"
          renderOnZeroPageCount={null}
        />
      </>
    );
  }

  return <>{products}</>;
};
export default CarSectionItem;

CarsSection where all the components including CarsSectionItem is stored:

import React, { useState } from "react";
import { CarsSectionContainer, CarsContainer } from "./CarsSectionElements";
import CarsFilter from "./CarsFilter/CarsFilter";
import CarSectionItem from "./СarSectionItem/CarSectionItem";
import { carsData } from "../data/CarsData";

const CarsSection = () => {

  return (
    <CarsSectionContainer>
      <CarsFilter/>
      <CarsContainer>
        <CarSectionItem />
      </CarsContainer>
    </CarsSectionContainer>
  );
};

export default CarsSection;

My local data file  :

import Car1 from '../../img/car1.jpg'
import Car2 from '../../img/car2.jpg'
const carsData = [
  {
    id: '1',
    image: [Car1, Car1, Car1, Car1],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  {
    id: '2',
    image: [Car2, Car2, Car2, Car2],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  {
    id: '3',
    image: [Car1, Car1, Car1, Car1],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  {
    id: '4',
    image: [Car1, Car1, Car1, Car1],
    price: '$80 000',
    brand: 'Genesis',
    title: "Genesis G90 3.8 AWD PRESTIGE 2020",
    mileage: "9300 км",
    engine: "3.3 л",
    fuelType: "Бензин",
    transmission: "Автомат",
    driveTrain: "Полный 4WD",
    bootType: "Седан",
    buttonLabel: 'Детали'
  },
  ];

  export default carsData;

How can i make a pagination using my local data? I saw lots of tutorials how to make pagination using fetch data. But can't make it using local data.


问:
SKScene in a SpriteView in SwiftUI has size 1?
I'm confused about the cooridinates in a SpriteView in a SwiftUI app.

I have a small program I use for fooling around in Swift. It draws a SKScene with a grid of 64 x 64 squares, which I call "pixels", and then does color animation by changing their color. At the top of the SKScene setup code is this:

```<code>let pixelSize = min(self.size.width / Double(numColumns), self.size.height / Double(numRows))
</code>```

Then I draw the grid by looping from -ve self.size.width/64 to +ve self.size.width/64 and making squares of pixelSize, thereby centering them in SK's 0-in-the-center. The resulting SKScene is then placed in NSViewController or UIView.

I was reading a SwiftUI intro on Hacking With Swift and became intrigued with the simplicity of the code, so I decided to convert the app SUI. This is trivial using SpriteView. Running this results in the content all being pushed to the lower left corner:

In the debugger, I find that the dimensions of the view are 0,0 to 1,1, which is unexpected. This results in the pixels being the correct size, because they're scaled to the view. However, as you can see, they are positioned incorrectly with all the -ve values off-screen.

I thought this was order of operations, that the SKScene was being called before the screen was laid out, but no. I wrapped the SpriteView in a GeometryReader and found that the size is indeed the 480x480 I expect, and that the Scene's initalizer is called after the SpriteView is set up.

So why is 0,0 in the lower left and not the center, and why is the size in the SKScene 1 by 1? I looked in SpriteView and SpriteView.options dox, but I don't see any hint of this. What have I missed?

```<code>@State private var scene = SpriteoscopeScene()

var body: some View {
    HStack {
        VStack {
            Spacer()
            Button("pause") { scene.pauseKalidescope() } .buttonStyle(DefaultButtonStyle())
        }.padding()
        SpriteView(scene: scene)
        VStack {
            Spacer()
            Button("reset") { scene.setupKalidescope() } .buttonStyle(DefaultButtonStyle())
        }.padding()

    }
    .frame(width: 640, height: 480)
}
</code>```

Body:
I'm confused about the cooridinates in a SpriteView in a SwiftUI app.

I have a small program I use for fooling around in Swift. It draws a SKScene with a grid of 64 x 64 squares, which I call "pixels", and then does color animation by changing their color. At the top of the SKScene setup code is this:

let pixelSize = min(self.size.width / Double(numColumns), self.size.height / Double(numRows))

Then I draw the grid by looping from -ve self.size.width/64 to +ve self.size.width/64 and making squares of pixelSize, thereby centering them in SK's 0-in-the-center. The resulting SKScene is then placed in NSViewController or UIView.

I was reading a SwiftUI intro on Hacking With Swift and became intrigued with the simplicity of the code, so I decided to convert the app SUI. This is trivial using SpriteView. Running this results in the content all being pushed to the lower left corner:

In the debugger, I find that the dimensions of the view are 0,0 to 1,1, which is unexpected. This results in the pixels being the correct size, because they're scaled to the view. However, as you can see, they are positioned incorrectly with all the -ve values off-screen.

I thought this was order of operations, that the SKScene was being called before the screen was laid out, but no. I wrapped the SpriteView in a GeometryReader and found that the size is indeed the 480x480 I expect, and that the Scene's initalizer is called after the SpriteView is set up.

So why is 0,0 in the lower left and not the center, and why is the size in the SKScene 1 by 1? I looked in SpriteView and SpriteView.options dox, but I don't see any hint of this. What have I missed?

@State private var scene = SpriteoscopeScene()

var body: some View {
    HStack {
        VStack {
            Spacer()
            Button("pause") { scene.pauseKalidescope() } .buttonStyle(DefaultButtonStyle())
        }.padding()
        SpriteView(scene: scene)
        VStack {
            Spacer()
            Button("reset") { scene.setupKalidescope() } .buttonStyle(DefaultButtonStyle())
        }.padding()

    }
    .frame(width: 640, height: 480)
}


问:
cloud logging labels with links
There are some option to add message link to labels in google logging?

I have this log entry and wont to place a link to file

```<code>_logger.WithLabels(new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>("file1", "/files/1.txt"),
                new KeyValuePair<string, string>("code", "555")
            }).LogInformation("test log message");
</code>```

so in google log explorer I can click on labels.file1  as a link to this file /files/1.txt?

Title: cloud logging labels with links

Body:
There are some option to add message link to labels in google logging?

I have this log entry and wont to place a link to file

_logger.WithLabels(new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>("file1", "/files/1.txt"),
                new KeyValuePair<string, string>("code", "555")
            }).LogInformation("test log message");

so in google log explorer I can click on labels.file1  as a link to this file /files/1.txt?