问:
Pygame problem when loading game from file and trying to redraw it and play
When Ever I save the game it works but when loading the contents back it will load game correctly as long as i am on exact same round but if i load the game and i am on a different row/round to what the game was saved on it wont function correctly as i cannot click the squares or it will just not even load the squares or load the squares but extra squares will be generated
Below is the code

```
        import pygame
        import random
        import sys
        import pickle
        def main():
            # Initialize Pygame
            pygame.init()

            # Set the window size
            window_size = (600, 1000)

            #Create the window
            screen = pygame.display.set_mode(window_size)

            screen_width = 600
            screen_height = 800

            class Savegame:
                def __init__(self):
                    # Initialize Pygame and set up the display
                    pygame.init()
                    self.font = pygame.font.Font(None,32)
                    self.screen = screen

                def show_save_menu(self):

                    self.saveslot1 = self.font.render("savegame{1}",True,(255, 255, 255))
                    self.saveslot1_text_rect = self.saveslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 50))
                    self.saveslot2 = self.font.render("savegame{2}",True,(255, 255, 255))
                    self.saveslot2_text_rect = self.saveslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 80))
                    self.saveslot3 = self.font.render("saveslot{3}",True,(255, 255, 255))
                    self.saveslot3_text_rect = self.saveslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 110))

                    self.screen.blit(self.saveslot1,self.saveslot1_text_rect)
                    self.screen.blit(self.saveslot2,self.saveslot2_text_rect)
                    self.screen.blit(self.saveslot3,self.saveslot3_text_rect)

                    self.just_opened_savemenu = True
                    pygame.display.update()

                def hide_save_menu(self):
                    self.just_opened_savemenu = False
                    screen.fill((0,0,0))
                    Mastermind.show_pause_menu()
                    pygame.display.update()

                def updatesaveslot1(self):
                    Mastermind.save_game()
                def updatesaveslot2(self):
                    print("Saved in slot 2")
                def updatesaveslot3(self):
                    print("Saved in slot 3")

                def saveslotclicked(self,pos):
                    if self.saveslot1_text_rect.collidepoint(pos):
                        self.updatesaveslot1()
                    elif self.saveslot2_text_rect.collidepoint(pos):
                        self.updatesaveslot2()
                    elif self.saveslot3_text_rect.collidepoint(pos):
                        self.updatesaveslot3()

            class Loadgame:
                def __init__(self):
                    # Initialize Pygame and set up the display
                    pygame.init()
                    self.font = pygame.font.Font(None,32)
                    self.screen = screen

                def show_load_menu(self):

                    self.loadslot1 = self.font.render("loadslot{1}",True,(255, 255, 255))
                    self.loadslot1_text_rect = self.loadslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 50))
                    self.loadslot2 = self.font.render("loadslot{2}",True,(255, 255, 255))
                    self.loadslot2_text_rect = self.loadslot2.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 80))
                    self.loadslot3 = self.font.render("loadslot{3}",True,(255, 255, 255))
                    self.loadslot3_text_rect = self.loadslot3.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 110))

                    self.screen.blit(self.loadslot1,self.loadslot1_text_rect)
                    self.screen.blit(self.loadslot2,self.loadslot2_text_rect)
                    self.screen.blit(self.loadslot3,self.loadslot3_text_rect)

                    self.just_opened_loadmenu = True
                    pygame.display.update()

                def hide_load_menu(self):
                    self.just_opened_loadmenu = False
                    self.screen.fill((0, 0 , 0))
                    Mastermind.show_pause_menu()
                    pygame.display.update()

                def updateloadslot1(self):
                    print("loaded slot 1")
                    Mastermind.load_game()
                def updateloadslot2(self):
                    print("loaded slot 2")
                def updateloadslot3(self):
                    print("loaded  slot 3")

                def loadslotclicked(self,pos):
                    if self.loadslot1_text_rect.collidepoint(pos):
                        self.updateloadslot1()
                    elif self.loadslot2_text_rect.collidepoint(pos):
                        self.updateloadslot2()
                    elif self.loadslot3_text_rect.collidepoint(pos):
                        self.updateloadslot3()

            class PauseMenu:
                def __init__(self):
                    self.screen = screen
                    self.game_paused = False
                    self.game_status = f"Game in Progress..."
                    self.icon_visible = True
                def Return_game_paused(self):
                    return self.game_paused
                def hide_pause_menu(self):
                    self.screen.fill((0, 0 , 0))

                def show_pause_menu(self):
                    # Set the font and text for the menu options
                    self.font = pygame.font.Font(None, 32)
                    self.game_status_text = self.font.render(self.game_status, True,(255,255,255))
                    self.game_status_text_rect = self.game_status_text.get_rect(topleft =((screen_width - 200) / 2 + 20, (screen_height - 100) / 2))
                    self.resume_text = self.font.render("Resume", True, (255, 255, 255))
                    self.resume_text_rect = self.resume_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 20))
                    self.restart_text = self.font.render("Restart", True, (255, 255, 255))
                    self.restart_text_rect = self.restart_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 50))
                    self.savegame_text = self.font.render("savegame",True,(255, 255, 255))
                    self.savegame_text_rect = self.savegame_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 80))
                    self.loadgame_text = self.font.render("loadgame",True,(255,255,255))
                    self.loadgame_text_rect = self.loadgame_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 110))
                    self.quit_text = self.font.render("Quit", True, (255, 255, 255))
                    self.quit_text_rect = self.quit_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 140))

                    # Set the dimensions and position of the menu background
                    menu_width = 200
                    menu_height = 100
                    menu_x = (screen_width - menu_width) / 2
                    menu_y = (screen_height - menu_height) / 2

                    # Draw the menu background
                    pygame.draw.rect(self.screen, (0, 0, 0), (menu_x, menu_y, menu_width, menu_height))

                    # Display the menu options
                    self.screen.blit(self.game_status_text, self.game_status_text_rect)
                    self.screen.blit(self.resume_text, self.resume_text_rect)
                    self.screen.blit(self.restart_text, self.restart_text_rect)
                    self.screen.blit(self.savegame_text,self.savegame_text_rect)
                    self.screen.blit(self.loadgame_text,self.loadgame_text_rect)
                    self.screen.blit(self.quit_text, self.quit_text_rect)

                    # Update the display
                    pygame.display.update()

                def restart_button_clicked(self, pos):
                    global Mastermind, roundbutton
                    if self.restart_text_rect.collidepoint(pos):
                        main()
                def pause_button_clicked(self,pos):
                    if  self.resume_text_rect.collidepoint(pos):
                        self.game_paused = not self.game_paused
                        return True
                    return False
                def save_button_clicked(self,pos):
                    if self.savegame_text_rect.collidepoint(pos):
                        return True
                def load_button_clicked(self,pos):
                    if self.loadgame_text_rect.collidepoint(pos):
                        return True
                def quit_button_clicked(self,pos):
                    if self.quit_text_rect.collidepoint(pos):
                        return True

            class Square:
                def __init__(self, x, y, sizex,sizey, color,colors =  [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)],text = "", font =  pygame.font.Font('freesansbold.ttf', 32)):
                    self.colors =  colors
                    self.x = x
                    self.y = y
                    self.width= sizex
                    self.height = sizey
                    self.color = color
                    self.rect = pygame.Rect(self.x,self.y,self.width,self.height)
                    self.text = text
                    self.font =font
                    self.tempx = self.x + self.width // 2
                    self.tempy =self.y + self.height // 2
                    self.position = (self.x, self.y,self.width, self.height)
                def draw(self, screen):
                    pygame.draw.rect(screen, self.color,self.position)
                    text_surface = self.font.render(self.text,True,(255,255,255))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (self.tempx, self.tempy)
                    screen.blit(text_surface, text_rect)
                def clicked(self, pos):
                    # Check if the square was clicked by checking if the mouse position is inside the square
                    if int(self.x) <= int(pos[0]) <= int(self.x + self.width) and self.y <= int(pos[1]) <= int(self.y + self.height) and Mastermind.round*100 == self.y:
                        if self.colors.index(self.color) + 1 < len(self.colors):
                            self.color = self.colors[self.colors.index(self.color) + 1]
                        else:
                            self.color = self.colors[0]

            # Create four squares
            class Row:
                def __init__(self,row,colors=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]):
                    self.grey = (128,128,128)
                    self.squares = [Square(100, row*100, 50,50, colors[0]), Square(200, row*100, 50,50, colors[1]), Square(300, row*100, 50,50, colors[2]), Square(400, row*100, 50,50, colors[3])]
                    self.identifiers = [Square(0, row*100+20,20 ,20, self.grey), Square(50, row*100+20,20, 20, self.grey), Square(475, row*100+20,20, 20, self.grey), Square(525, row*100+20, 20,20, self.grey)]

            class Game(PauseMenu,Savegame,Loadgame):
                def __init__(self) -> None:
                    PauseMenu.__init__(self)
                    Savegame.__init__(self)
                    # Define a list of colors to cycle through
                    self.savemenuclicked = False
                    self.loadmenuclicked = False
                    self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]
                    self.randomcolors = [random.sample(self.colors,1)[0] for i in range(4)]
                    print(self.randomcolors)
                    self.round = 1
                    self.currentrow = Row(self.round,self.colors)
                    self.all_rows = [self.currentrow]
                    self.status = 0

                    pass
                def get_round(self):
                    return self.currentrow.squares[-1].y/100
                def get_colors(self):
                    return self.colors
                def get_essential_data(self):
                    return [self.round,self.all_rows]
                def save_game(self):
                    pickledata = [[self.round,self.randomcolors]]
                    squaredata = []
                    pindata = []
                    for row in self.all_rows:
                        for square in row.squares:
                            squaredata.append([square.x,square.y,square.color])
                        for pin in row.identifiers:
                            pindata.append([pin.x,pin.y,pin.color])
                    pickledata.append(squaredata)
                    pickledata.append(pindata)
                    data = pickle.dumps(pickledata)
                    with open("saveslot1","wb") as f:
                        f.write(data)

                def load_game(self):
                    with open("saveslot1", "rb") as file:
                        while True:
                            try:
                                data = pickle.load(file)
                            except EOFError:
                                break
                            self.round = data[0][0]

                            self.randomcolors = data[0][1]
                            colorlist = [0,0,0,0]

                            for square in data[1]:
                                x, y, color = square
                                print(x,y,color)
                                for row in self.all_rows:
                                    for i in range(0,4):
                                        colorlist[i] = color

                                        if row.squares[i].x == x and row.squares[i].y == y:
                                            row.squares[i].color = color

                                            break
                            for pin in data[2]:
                                x, y, identifier = pin
                                for row in self.all_rows:
                                    for i in range(0,4):
                                        if row.identifiers[i].x == x and row.identifiers[i].y == y:
                                            row.identifiers[i].identifiers = identifier
                                            break
                            self.currentrow = Row(self.round,colorlist)
                            self.update_screen()

                def eventhandling(self):
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            sys.exit()

                        elif event.type == pygame.MOUSEBUTTONUP:

                            if not self.game_paused:
                                self.status = roundbutton.clicked(event.pos,self.randomcolors)[1]
                                for row in self.all_rows:
                                    for square in row.squares:
                                            square.clicked(event.pos)
                            if self.game_paused:
                                if self.quit_button_clicked(event.pos):
                                    pygame.quit()
                                    sys.exit()
                                self.restart_button_clicked(event.pos)
                                if self.pause_button_clicked(event.pos):
                                    if self.game_paused:
                                        self.hide_pause_menu()
                                        self.hide_load_menu()
                                        self.hide_save_menu()
                                    else:
                                        self.show_pause_menu()
                                if self.savemenuclicked:
                                    self.saveslotclicked(event.pos)
                                if self.loadmenuclicked:
                                    self.loadslotclicked(event.pos)
                                if self.save_button_clicked(event.pos):
                                    print("savebuttonclick")
                                    self.savemenuclicked = not self.savemenuclicked
                                if self.load_button_clicked(event.pos):
                                    print("loadbuttonclicked")
                                    self.loadmenuclicked = not self.loadmenuclicked
                        elif event.type == pygame.KEYUP:
                            if event.key == pygame.K_ESCAPE:
                                self.game_paused = not self.game_paused
                                if self.game_paused:
                                    self.show_pause_menu()
                                else:
                                    self.hide_pause_menu()

                def update_screen(self):

                    for row in self.all_rows:
                        for square in row.squares:
                                square.draw(screen)
                        for square in row.identifiers:
                            square.draw(screen)
                        roundbutton.draw(screen)

                def Gameloop(self):
                    just_resumed = False
                    self.just_opened_savemenu = False
                    self.just_opened_loadmenu = False
                    self.show_pause_menu()
                    self.hide_pause_menu()
                    mysterycolor = pygame.image.load("questionbox.png").convert()
                    mysterycolor = pygame.transform.scale(mysterycolor,(50,50))
                    while True:
                        self.eventhandling()
                        if self.savemenuclicked:
                            self.show_save_menu()
                        elif self.just_opened_savemenu:
                            print("hiding")
                            self.hide_save_menu()
                        if self.loadmenuclicked:
                            self.show_load_menu()
                        elif self.just_opened_loadmenu:
                            self.hide_load_menu()

                        if not PauseMenu.Return_game_paused(self):
                            if just_resumed:
                                PauseMenu.hide_pause_menu(self)
                                just_resumed = False

                            else:
                                self.update_screen()
                                if self.status == -1:
                                    self.squares = [Square(100, 0, 50,50, self.randomcolors[0]).draw(screen), Square(200, 0, 50,50, self.randomcolors[1]).draw(screen), Square(300, 0, 50,50, self.randomcolors[2]).draw(screen), Square(400, 0, 50,50, self.randomcolors[3]).draw(screen)]
                                    self.game_status = "Game Won!"

                                elif self.get_round() >=9:
                                    self.squares = [Square(100, 0, 50,50, self.randomcolors[0]).draw(screen), Square(200, 0, 50,50, self.randomcolors[1]).draw(screen), Square(300, 0, 50,50, self.randomcolors[2]).draw(screen), Square(400, 0, 50,50, self.randomcolors[3]).draw(screen)]
                                    self.game_status = "Game Over!"

                                else:
                                    screen.blit(mysterycolor,(100,0))
                                    screen.blit(mysterycolor,(200,0))
                                    screen.blit(mysterycolor,(300,0))
                                    screen.blit(mysterycolor,(400,0))

                        else:
                            if not just_resumed:
                                screen.fill((0,0,0))
                                PauseMenu.show_pause_menu(self)
                                just_resumed = True

                        pygame.display.update()

            class Nextround(Game):
                def __init__(self, round):
                    self.font = pygame.font.Font(None, 25)
                    self.x = 500
                    self.round = round
                    self.y = 600
                    self.size = 20
                    self.currentcolors = []
                    self.next_round_text = self.font.render("Reveal", True, (0,0,0))
                    self.next_round_rect = self.next_round_text.get_rect(topleft=(self.x ,self.y))
                def draw(self, screen):
                    pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, 60, self.size))
                    screen.blit(self.next_round_text,self.next_round_rect)
                    pygame.display.update()
                def clicked(self, pos, randcolors):
                    count = 0
                    self.randcolors = randcolors
                    if self.next_round_rect.collidepoint(pos):
                        Mastermind.round +=1
                        self.round += 1
                        for i in range(0,4):
                            # Check if the current square's color matches the corresponding color in the randcolors list
                            if Mastermind.currentrow.squares[i].color == self.randcolors[i]:
                                Mastermind.currentrow.identifiers[i].color = (255,255,255)
                                count += 1

                            # Check if the current square's color is present in the randcolors list, but not in the correct position
                            elif Mastermind.currentrow.squares[i].color in self.randcolors:
                                Mastermind.currentrow.identifiers[i].color = (255,0,0)
                            # If the current square's color is not present in the randcolors list
                            else:
                                Mastermind.currentrow.identifiers[i].color = (128,128,128)
                        # If all the colors match, return -1
                        if count == 4:
                            return [self.round,-1,True]
                        # Create a new row of squares
                        new_row = Row(self.round,Mastermind.colors)
                        # Add the new row to the list of all rows
                        Mastermind.all_rows.append(new_row)
                        # Update the currentrow attribute to point to the new row
                        Mastermind.currentrow = new_row
                        return [self.round,self.round,True]
                    return [self.round,self.round,False]
            Mastermind = Game()
            roundbutton = Nextround(1)
            Mastermind.Gameloop()

        main()
```

I am expecting when the loadbutton is clicked it will resume the game at the exact point that the save button was clicked no matter if you close the program or click the restart button or play another game as the essential data should be in a text file

Body:
When Ever I save the game it works but when loading the contents back it will load game correctly as long as i am on exact same round but if i load the game and i am on a different row/round to what the game was saved on it wont function correctly as i cannot click the squares or it will just not even load the squares or load the squares but extra squares will be generated
Below is the code

        import pygame
        import random
        import sys
        import pickle
        def main():
            # Initialize Pygame
            pygame.init()

            # Set the window size
            window_size = (600, 1000)

            #Create the window
            screen = pygame.display.set_mode(window_size)

            screen_width = 600
            screen_height = 800

            class Savegame:
                def __init__(self):
                    # Initialize Pygame and set up the display
                    pygame.init()
                    self.font = pygame.font.Font(None,32)
                    self.screen = screen

                def show_save_menu(self):

                    self.saveslot1 = self.font.render("savegame{1}",True,(255, 255, 255))
                    self.saveslot1_text_rect = self.saveslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 50))
                    self.saveslot2 = self.font.render("savegame{2}",True,(255, 255, 255))
                    self.saveslot2_text_rect = self.saveslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 80))
                    self.saveslot3 = self.font.render("saveslot{3}",True,(255, 255, 255))
                    self.saveslot3_text_rect = self.saveslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 110))

                    self.screen.blit(self.saveslot1,self.saveslot1_text_rect)
                    self.screen.blit(self.saveslot2,self.saveslot2_text_rect)
                    self.screen.blit(self.saveslot3,self.saveslot3_text_rect)

                    self.just_opened_savemenu = True
                    pygame.display.update()

                def hide_save_menu(self):
                    self.just_opened_savemenu = False
                    screen.fill((0,0,0))
                    Mastermind.show_pause_menu()
                    pygame.display.update()

                def updatesaveslot1(self):
                    Mastermind.save_game()
                def updatesaveslot2(self):
                    print("Saved in slot 2")
                def updatesaveslot3(self):
                    print("Saved in slot 3")

                def saveslotclicked(self,pos):
                    if self.saveslot1_text_rect.collidepoint(pos):
                        self.updatesaveslot1()
                    elif self.saveslot2_text_rect.collidepoint(pos):
                        self.updatesaveslot2()
                    elif self.saveslot3_text_rect.collidepoint(pos):
                        self.updatesaveslot3()

            class Loadgame:
                def __init__(self):
                    # Initialize Pygame and set up the display
                    pygame.init()
                    self.font = pygame.font.Font(None,32)
                    self.screen = screen

                def show_load_menu(self):

                    self.loadslot1 = self.font.render("loadslot{1}",True,(255, 255, 255))
                    self.loadslot1_text_rect = self.loadslot1.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 50))
                    self.loadslot2 = self.font.render("loadslot{2}",True,(255, 255, 255))
                    self.loadslot2_text_rect = self.loadslot2.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 80))
                    self.loadslot3 = self.font.render("loadslot{3}",True,(255, 255, 255))
                    self.loadslot3_text_rect = self.loadslot3.get_rect(topleft=((screen_width - 200) / 2 + 200, (screen_height - 100) / 2 + 110))

                    self.screen.blit(self.loadslot1,self.loadslot1_text_rect)
                    self.screen.blit(self.loadslot2,self.loadslot2_text_rect)
                    self.screen.blit(self.loadslot3,self.loadslot3_text_rect)

                    self.just_opened_loadmenu = True
                    pygame.display.update()

                def hide_load_menu(self):
                    self.just_opened_loadmenu = False
                    self.screen.fill((0, 0 , 0))
                    Mastermind.show_pause_menu()
                    pygame.display.update()

                def updateloadslot1(self):
                    print("loaded slot 1")
                    Mastermind.load_game()
                def updateloadslot2(self):
                    print("loaded slot 2")
                def updateloadslot3(self):
                    print("loaded  slot 3")

                def loadslotclicked(self,pos):
                    if self.loadslot1_text_rect.collidepoint(pos):
                        self.updateloadslot1()
                    elif self.loadslot2_text_rect.collidepoint(pos):
                        self.updateloadslot2()
                    elif self.loadslot3_text_rect.collidepoint(pos):
                        self.updateloadslot3()

            class PauseMenu:
                def __init__(self):
                    self.screen = screen
                    self.game_paused = False
                    self.game_status = f"Game in Progress..."
                    self.icon_visible = True
                def Return_game_paused(self):
                    return self.game_paused
                def hide_pause_menu(self):
                    self.screen.fill((0, 0 , 0))

                def show_pause_menu(self):
                    # Set the font and text for the menu options
                    self.font = pygame.font.Font(None, 32)
                    self.game_status_text = self.font.render(self.game_status, True,(255,255,255))
                    self.game_status_text_rect = self.game_status_text.get_rect(topleft =((screen_width - 200) / 2 + 20, (screen_height - 100) / 2))
                    self.resume_text = self.font.render("Resume", True, (255, 255, 255))
                    self.resume_text_rect = self.resume_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 20))
                    self.restart_text = self.font.render("Restart", True, (255, 255, 255))
                    self.restart_text_rect = self.restart_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 50))
                    self.savegame_text = self.font.render("savegame",True,(255, 255, 255))
                    self.savegame_text_rect = self.savegame_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 80))
                    self.loadgame_text = self.font.render("loadgame",True,(255,255,255))
                    self.loadgame_text_rect = self.loadgame_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 110))
                    self.quit_text = self.font.render("Quit", True, (255, 255, 255))
                    self.quit_text_rect = self.quit_text.get_rect(topleft=((screen_width - 200) / 2 + 20, (screen_height - 100) / 2 + 140))

                    # Set the dimensions and position of the menu background
                    menu_width = 200
                    menu_height = 100
                    menu_x = (screen_width - menu_width) / 2
                    menu_y = (screen_height - menu_height) / 2

                    # Draw the menu background
                    pygame.draw.rect(self.screen, (0, 0, 0), (menu_x, menu_y, menu_width, menu_height))

                    # Display the menu options
                    self.screen.blit(self.game_status_text, self.game_status_text_rect)
                    self.screen.blit(self.resume_text, self.resume_text_rect)
                    self.screen.blit(self.restart_text, self.restart_text_rect)
                    self.screen.blit(self.savegame_text,self.savegame_text_rect)
                    self.screen.blit(self.loadgame_text,self.loadgame_text_rect)
                    self.screen.blit(self.quit_text, self.quit_text_rect)

                    # Update the display
                    pygame.display.update()

                def restart_button_clicked(self, pos):
                    global Mastermind, roundbutton
                    if self.restart_text_rect.collidepoint(pos):
                        main()
                def pause_button_clicked(self,pos):
                    if  self.resume_text_rect.collidepoint(pos):
                        self.game_paused = not self.game_paused
                        return True
                    return False
                def save_button_clicked(self,pos):
                    if self.savegame_text_rect.collidepoint(pos):
                        return True
                def load_button_clicked(self,pos):
                    if self.loadgame_text_rect.collidepoint(pos):
                        return True
                def quit_button_clicked(self,pos):
                    if self.quit_text_rect.collidepoint(pos):
                        return True

            class Square:
                def __init__(self, x, y, sizex,sizey, color,colors =  [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)],text = "", font =  pygame.font.Font('freesansbold.ttf', 32)):
                    self.colors =  colors
                    self.x = x
                    self.y = y
                    self.width= sizex
                    self.height = sizey
                    self.color = color
                    self.rect = pygame.Rect(self.x,self.y,self.width,self.height)
                    self.text = text
                    self.font =font
                    self.tempx = self.x + self.width // 2
                    self.tempy =self.y + self.height // 2
                    self.position = (self.x, self.y,self.width, self.height)
                def draw(self, screen):
                    pygame.draw.rect(screen, self.color,self.position)
                    text_surface = self.font.render(self.text,True,(255,255,255))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (self.tempx, self.tempy)
                    screen.blit(text_surface, text_rect)
                def clicked(self, pos):
                    # Check if the square was clicked by checking if the mouse position is inside the square
                    if int(self.x) <= int(pos[0]) <= int(self.x + self.width) and self.y <= int(pos[1]) <= int(self.y + self.height) and Mastermind.round*100 == self.y:
                        if self.colors.index(self.color) + 1 < len(self.colors):
                            self.color = self.colors[self.colors.index(self.color) + 1]
                        else:
                            self.color = self.colors[0]

            # Create four squares
            class Row:
                def __init__(self,row,colors=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]):
                    self.grey = (128,128,128)
                    self.squares = [Square(100, row*100, 50,50, colors[0]), Square(200, row*100, 50,50, colors[1]), Square(300, row*100, 50,50, colors[2]), Square(400, row*100, 50,50, colors[3])]
                    self.identifiers = [Square(0, row*100+20,20 ,20, self.grey), Square(50, row*100+20,20, 20, self.grey), Square(475, row*100+20,20, 20, self.grey), Square(525, row*100+20, 20,20, self.grey)]

            class Game(PauseMenu,Savegame,Loadgame):
                def __init__(self) -> None:
                    PauseMenu.__init__(self)
                    Savegame.__init__(self)
                    # Define a list of colors to cycle through
                    self.savemenuclicked = False
                    self.loadmenuclicked = False
                    self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]
                    self.randomcolors = [random.sample(self.colors,1)[0] for i in range(4)]
                    print(self.randomcolors)
                    self.round = 1
                    self.currentrow = Row(self.round,self.colors)
                    self.all_rows = [self.currentrow]
                    self.status = 0

                    pass
                def get_round(self):
                    return self.currentrow.squares[-1].y/100
                def get_colors(self):
                    return self.colors
                def get_essential_data(self):
                    return [self.round,self.all_rows]
                def save_game(self):
                    pickledata = [[self.round,self.randomcolors]]
                    squaredata = []
                    pindata = []
                    for row in self.all_rows:
                        for square in row.squares:
                            squaredata.append([square.x,square.y,square.color])
                        for pin in row.identifiers:
                            pindata.append([pin.x,pin.y,pin.color])
                    pickledata.append(squaredata)
                    pickledata.append(pindata)
                    data = pickle.dumps(pickledata)
                    with open("saveslot1","wb") as f:
                        f.write(data)

                def load_game(self):
                    with open("saveslot1", "rb") as file:
                        while True:
                            try:
                                data = pickle.load(file)
                            except EOFError:
                                break
                            self.round = data[0][0]

                            self.randomcolors = data[0][1]
                            colorlist = [0,0,0,0]

                            for square in data[1]:
                                x, y, color = square
                                print(x,y,color)
                                for row in self.all_rows:
                                    for i in range(0,4):
                                        colorlist[i] = color

                                        if row.squares[i].x == x and row.squares[i].y == y:
                                            row.squares[i].color = color

                                            break
                            for pin in data[2]:
                                x, y, identifier = pin
                                for row in self.all_rows:
                                    for i in range(0,4):
                                        if row.identifiers[i].x == x and row.identifiers[i].y == y:
                                            row.identifiers[i].identifiers = identifier
                                            break
                            self.currentrow = Row(self.round,colorlist)
                            self.update_screen()

                def eventhandling(self):
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            sys.exit()

                        elif event.type == pygame.MOUSEBUTTONUP:

                            if not self.game_paused:
                                self.status = roundbutton.clicked(event.pos,self.randomcolors)[1]
                                for row in self.all_rows:
                                    for square in row.squares:
                                            square.clicked(event.pos)
                            if self.game_paused:
                                if self.quit_button_clicked(event.pos):
                                    pygame.quit()
                                    sys.exit()
                                self.restart_button_clicked(event.pos)
                                if self.pause_button_clicked(event.pos):
                                    if self.game_paused:
                                        self.hide_pause_menu()
                                        self.hide_load_menu()
                                        self.hide_save_menu()
                                    else:
                                        self.show_pause_menu()
                                if self.savemenuclicked:
                                    self.saveslotclicked(event.pos)
                                if self.loadmenuclicked:
                                    self.loadslotclicked(event.pos)
                                if self.save_button_clicked(event.pos):
                                    print("savebuttonclick")
                                    self.savemenuclicked = not self.savemenuclicked
                                if self.load_button_clicked(event.pos):
                                    print("loadbuttonclicked")
                                    self.loadmenuclicked = not self.loadmenuclicked
                        elif event.type == pygame.KEYUP:
                            if event.key == pygame.K_ESCAPE:
                                self.game_paused = not self.game_paused
                                if self.game_paused:
                                    self.show_pause_menu()
                                else:
                                    self.hide_pause_menu()

                def update_screen(self):

                    for row in self.all_rows:
                        for square in row.squares:
                                square.draw(screen)
                        for square in row.identifiers:
                            square.draw(screen)
                        roundbutton.draw(screen)

                def Gameloop(self):
                    just_resumed = False
                    self.just_opened_savemenu = False
                    self.just_opened_loadmenu = False
                    self.show_pause_menu()
                    self.hide_pause_menu()
                    mysterycolor = pygame.image.load("questionbox.png").convert()
                    mysterycolor = pygame.transform.scale(mysterycolor,(50,50))
                    while True:
                        self.eventhandling()
                        if self.savemenuclicked:
                            self.show_save_menu()
                        elif self.just_opened_savemenu:
                            print("hiding")
                            self.hide_save_menu()
                        if self.loadmenuclicked:
                            self.show_load_menu()
                        elif self.just_opened_loadmenu:
                            self.hide_load_menu()

                        if not PauseMenu.Return_game_paused(self):
                            if just_resumed:
                                PauseMenu.hide_pause_menu(self)
                                just_resumed = False

                            else:
                                self.update_screen()
                                if self.status == -1:
                                    self.squares = [Square(100, 0, 50,50, self.randomcolors[0]).draw(screen), Square(200, 0, 50,50, self.randomcolors[1]).draw(screen), Square(300, 0, 50,50, self.randomcolors[2]).draw(screen), Square(400, 0, 50,50, self.randomcolors[3]).draw(screen)]
                                    self.game_status = "Game Won!"

                                elif self.get_round() >=9:
                                    self.squares = [Square(100, 0, 50,50, self.randomcolors[0]).draw(screen), Square(200, 0, 50,50, self.randomcolors[1]).draw(screen), Square(300, 0, 50,50, self.randomcolors[2]).draw(screen), Square(400, 0, 50,50, self.randomcolors[3]).draw(screen)]
                                    self.game_status = "Game Over!"

                                else:
                                    screen.blit(mysterycolor,(100,0))
                                    screen.blit(mysterycolor,(200,0))
                                    screen.blit(mysterycolor,(300,0))
                                    screen.blit(mysterycolor,(400,0))

                        else:
                            if not just_resumed:
                                screen.fill((0,0,0))
                                PauseMenu.show_pause_menu(self)
                                just_resumed = True

                        pygame.display.update()

            class Nextround(Game):
                def __init__(self, round):
                    self.font = pygame.font.Font(None, 25)
                    self.x = 500
                    self.round = round
                    self.y = 600
                    self.size = 20
                    self.currentcolors = []
                    self.next_round_text = self.font.render("Reveal", True, (0,0,0))
                    self.next_round_rect = self.next_round_text.get_rect(topleft=(self.x ,self.y))
                def draw(self, screen):
                    pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, 60, self.size))
                    screen.blit(self.next_round_text,self.next_round_rect)
                    pygame.display.update()
                def clicked(self, pos, randcolors):
                    count = 0
                    self.randcolors = randcolors
                    if self.next_round_rect.collidepoint(pos):
                        Mastermind.round +=1
                        self.round += 1
                        for i in range(0,4):
                            # Check if the current square's color matches the corresponding color in the randcolors list
                            if Mastermind.currentrow.squares[i].color == self.randcolors[i]:
                                Mastermind.currentrow.identifiers[i].color = (255,255,255)
                                count += 1

                            # Check if the current square's color is present in the randcolors list, but not in the correct position
                            elif Mastermind.currentrow.squares[i].color in self.randcolors:
                                Mastermind.currentrow.identifiers[i].color = (255,0,0)
                            # If the current square's color is not present in the randcolors list
                            else:
                                Mastermind.currentrow.identifiers[i].color = (128,128,128)
                        # If all the colors match, return -1
                        if count == 4:
                            return [self.round,-1,True]
                        # Create a new row of squares
                        new_row = Row(self.round,Mastermind.colors)
                        # Add the new row to the list of all rows
                        Mastermind.all_rows.append(new_row)
                        # Update the currentrow attribute to point to the new row
                        Mastermind.currentrow = new_row
                        return [self.round,self.round,True]
                    return [self.round,self.round,False]
            Mastermind = Game()
            roundbutton = Nextround(1)
            Mastermind.Gameloop()

        main()

I am expecting when the loadbutton is clicked it will resume the game at the exact point that the save button was clicked no matter if you close the program or click the restart button or play another game as the essential data should be in a text file


来源: stackexchange

问:
Cassandra nodetool status taking too long when running through remote jmx
I have a cassandra cluster running on AWS EC2. It has 4 nodes, all the nodes have remote jmx enabled without any authentication and jmx port 7199 is open.
From my local system, running nodetool -h <node-ip> status take ~9mins to complete.
But all other commands like gossipinfo, tpstats completes in less than 10sec.

Running nodetool -h <any-node-ip> status through ssh on any of the nodes completes in ~3 secs.

Any idea why this is happening in case of remote jmx?
Is it possible that nodetool status command needs to make multiple network calls from my local system to each nodes, causing overall slowdown?

Cassandra Version: 3.11.4

ContentLicense: CC BY-SA 4.0


问:
How do i solve 'invalid token specified' in react app on deployment with netlify?
I built a react app with sanity.io for the backend which works perfectly on my local server but after a successful build and deployment on netlify, it renders a blank page with an error message 'invalid token specified'. I have tried creating new tokens but nothing works. What might be the issue?


问:
Camera with Border Collision
I am trying currently to program a functioning camera that follows the player, and stops whenever the player gets close enough to the border that the outside would appear.

Most of everything works fine except for the collision with the right and bottom parts of the screen.

The code for the collision part is as follows:

for sprite in self.sprites():
    rectPosition = sprite.rect.topleft - self.offset

    if self.offset.x < self.mapRect.x:
        self.offset.x = 0
        rectPosition = sprite.rect.topleft - self.offset
    if self.offset.y < self.mapRect.y:
        self.offset.y = 0
        rectPosition = sprite.rect.topleft - self.offset

    if self.offset.x > self.mapRect.w:
        self.offset.x = 0
        rectPosition = sprite.rect.topleft - self.offset
    if self.offset.y > self.mapRect.h:
        self.offset.y = 0
        rectPosition = sprite.rect.topleft - self.offset

    screen.blit( sprite.image, rectPosition)
```
<p>The collisions for the top and left sides of the screen work fine, but the right and bottom ones don't seem to work correctly. If the player moves enough off screen (seems about half the screen's supposed length) to either of the faulty sides, it does trigger a collision, but it still doesn't work as intended i believe because the camera position seems to be reset to (0,0)</p>
<p>I've tried different attributes for the mapRect (w, h, right, bottom) and conditions (offset.y < mapRect.height instead of >) but the most that will happen, is that it sets the camera position to (0,0) as well, otherwise nothing will change. Also tried manually setting the width and height values in the condition instead of getting them from the map Rect.</p>
<p>The game screen is first blited to a Surface before being blited to the actual game screen, so that the contents in the screen are resizable. I've of course changed it to draw everything in the game screen to see if anything changes but no luck.</p>
<p>What can i do to fix this so that it will work as intended?</p>
<p>If needed, the rest of the game code is below:</p>
<pre class="lang-py prettyprint-override"><code>import pygame

pygame.init()
screen_SIZE = width, height = 768, 648
screen = pygame.display.set_mode(screen_SIZE)

class Background(pygame.sprite.Sprite):
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((1152,972))
        self.rect = pygame.Rect(0,0,1152,972)
        pygame.draw.rect(self.image, 'red', self.rect)
        #big red rectangle
class Background_Center(pygame.sprite.Sprite):
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((200,200))
        self.rect = pygame.Rect(576,486,200,200)
        pygame.draw.rect(self.image, 'black', self.rect)
        #big square in the middle
class Player(pygame.sprite.Sprite):
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((64, 64))
        self.rect = pygame.Rect(400, 800, 64, 64)
        pygame.draw.rect(self.image, 'white', self.rect)
        #movement
        self.direction = pygame.math.Vector2()
        self.speed = 5

    def input(self):
        key = pygame.key.get_pressed()
        #keys
        if key[pygame.K_UP]:
            self.direction.y = -1
        elif key[pygame.K_DOWN]:
            self.direction.y = 1
        else:
            self.direction.y = 0
        if key[pygame.K_RIGHT]:
            self.direction.x = 1
        elif key[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0
    def move(self):
        self.rect.x += self.direction.x * self.speed
        self.rect.y += self.direction.y * self.speed

    def update(self):
        self.input()
        self.move()

class camera_group(pygame.sprite.Group):
    def __init__(self):
        super().__init__()
        self.display = screen

        self.offset = pygame.math.Vector2()
        self.half_w = self.display.get_size()[0] // 2
        self.half_h = self.display.get_size()[0] // 2

    def custom_draw(self, target, map):
        rectPosition = []
        self.mapRect = map.rect
        self.offset.x = target.rect.centerx - self.half_w
        self.offset.y = target.rect.centery - self.half_h

        for sprite in self.sprites():
            rectPosition = sprite.rect.topleft - self.offset

            if self.offset.x < self.mapRect.x:
                self.offset.x = 0
                rectPosition = sprite.rect.topleft - self.offset
            if self.offset.y < self.mapRect.y:
                self.offset.y = 0
                rectPosition = sprite.rect.topleft - self.offset

            if self.offset.x > self.mapRect.w:
                self.offset.x = 0
                rectPosition = sprite.rect.topleft - self.offset
            if self.offset.y > self.mapRect.h:
                self.offset.y = 0
                rectPosition = sprite.rect.topleft - self.offset

            screen.blit( sprite.image, rectPosition)

camera = camera_group()
map = Background(camera)
map_center = Background_Center(camera)
player = Player(camera)

clock = pygame.time.Clock()
while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    screen.fill('white')
    camera.update()
    camera.custom_draw(player, map)

    pygame.display.update()

</code>```

Title: Camera with Border Collision

Body:
I am trying currently to program a functioning camera that follows the player, and stops whenever the player gets close enough to the border that the outside would appear.

Most of everything works fine except for the collision with the right and bottom parts of the screen.

The code for the collision part is as follows:

for sprite in self.sprites():
    rectPosition = sprite.rect.topleft - self.offset

    if self.offset.x < self.mapRect.x:
        self.offset.x = 0
        rectPosition = sprite.rect.topleft - self.offset
    if self.offset.y < self.mapRect.y:
        self.offset.y = 0
        rectPosition = sprite.rect.topleft - self.offset

    if self.offset.x > self.mapRect.w:
        self.offset.x = 0
        rectPosition = sprite.rect.topleft - self.offset
    if self.offset.y > self.mapRect.h:
        self.offset.y = 0
        rectPosition = sprite.rect.topleft - self.offset

    screen.blit( sprite.image, rectPosition)

The collisions for the top and left sides of the screen work fine, but the right and bottom ones don't seem to work correctly. If the player moves enough off screen (seems about half the screen's supposed length) to either of the faulty sides, it does trigger a collision, but it still doesn't work as intended i believe because the camera position seems to be reset to (0,0)

I've tried different attributes for the mapRect (w, h, right, bottom) and conditions (offset.y < mapRect.height instead of >) but the most that will happen, is that it sets the camera position to (0,0) as well, otherwise nothing will change. Also tried manually setting the width and height values in the condition instead of getting them from the map Rect.

The game screen is first blited to a Surface before being blited to the actual game screen, so that the contents in the screen are resizable. I've of course changed it to draw everything in the game screen to see if anything changes but no luck.

What can i do to fix this so that it will work as intended?

If needed, the rest of the game code is below:

import pygame

pygame.init()
screen_SIZE = width, height = 768, 648
screen = pygame.display.set_mode(screen_SIZE)

class Background(pygame.sprite.Sprite):
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((1152,972))
        self.rect = pygame.Rect(0,0,1152,972)
        pygame.draw.rect(self.image, 'red', self.rect)
        #big red rectangle
class Background_Center(pygame.sprite.Sprite):
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((200,200))
        self.rect = pygame.Rect(576,486,200,200)
        pygame.draw.rect(self.image, 'black', self.rect)
        #big square in the middle
class Player(pygame.sprite.Sprite):
    def __init__(self, group):
        super().__init__(group)
        self.image = pygame.Surface((64, 64))
        self.rect = pygame.Rect(400, 800, 64, 64)
        pygame.draw.rect(self.image, 'white', self.rect)
        #movement
        self.direction = pygame.math.Vector2()
        self.speed = 5

    def input(self):
        key = pygame.key.get_pressed()
        #keys
        if key[pygame.K_UP]:
            self.direction.y = -1
        elif key[pygame.K_DOWN]:
            self.direction.y = 1
        else:
            self.direction.y = 0
        if key[pygame.K_RIGHT]:
            self.direction.x = 1
        elif key[pygame.K_LEFT]:
            self.direction.x = -1
        else:
            self.direction.x = 0
    def move(self):
        self.rect.x += self.direction.x * self.speed
        self.rect.y += self.direction.y * self.speed

    def update(self):
        self.input()
        self.move()

class camera_group(pygame.sprite.Group):
    def __init__(self):
        super().__init__()
        self.display = screen

        self.offset = pygame.math.Vector2()
        self.half_w = self.display.get_size()[0] // 2
        self.half_h = self.display.get_size()[0] // 2

    def custom_draw(self, target, map):
        rectPosition = []
        self.mapRect = map.rect
        self.offset.x = target.rect.centerx - self.half_w
        self.offset.y = target.rect.centery - self.half_h

        for sprite in self.sprites():
            rectPosition = sprite.rect.topleft - self.offset

            if self.offset.x < self.mapRect.x:
                self.offset.x = 0
                rectPosition = sprite.rect.topleft - self.offset
            if self.offset.y < self.mapRect.y:
                self.offset.y = 0
                rectPosition = sprite.rect.topleft - self.offset

            if self.offset.x > self.mapRect.w:
                self.offset.x = 0
                rectPosition = sprite.rect.topleft - self.offset
            if self.offset.y > self.mapRect.h:
                self.offset.y = 0
                rectPosition = sprite.rect.topleft - self.offset

            screen.blit( sprite.image, rectPosition)

camera = camera_group()
map = Background(camera)
map_center = Background_Center(camera)
player = Player(camera)

clock = pygame.time.Clock()
while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    screen.fill('white')
    camera.update()
    camera.custom_draw(player, map)

    pygame.display.update()


问:
how to iterate through this array of objects in javascrip
```<code>{"airplane_models":[{"name":"A770","max_passenger":230},{"name":"A342","max_passenger":130},{"name":"A341","max_passenger":234},{"name":"B345","max_passenger":21}]}
</code>```

In the text above i provide what was given in the xhttp response. Output was done via

```<code>window.alert(this.responseText)

</code>```

then this gets passed to the function:

```<code>displayModels(JSON.parse(this.responseText))
</code>```

then i have a function that is supposed to add insights of this array to the table:

```<code>/**
 * Updates the DOM tree in order to display users.
 *
 * @param {Array.<{name: String, max_passengers: Number}>} airplane_models
 */
function displayModels(airplane_models) {
    let tableBody = document.getElementById('tableBody');
    clearElementChildren(tableBody);
    airplane_models.forEach(model => {
        for(let key in model)
        {
            window.alert(key)
            tableBody.appendChild(createTableRow(key));
        }
    })
}
</code>```

But this does not append the table, even the window.alert(key) never outputs anything.

I tried to modify A code in a various way, firstly by changing @param

```<code>* @param {{name: String, max_passengers: Number}[]} airplane_models
</code>```

but it gives me basically the same output. I also tried modyfing the for loop:

```<code>Object.keys(airplane_models).forEach(model => {
    window.alert(model.name)
    tableBody.appendChild(createTableRow(model.name));
})
</code>```

Exactly the same result, no output at window.alert(model.name)

Body:
{"airplane_models":[{"name":"A770","max_passenger":230},{"name":"A342","max_passenger":130},{"name":"A341","max_passenger":234},{"name":"B345","max_passenger":21}]}

In the text above i provide what was given in the xhttp response. Output was done via

window.alert(this.responseText)

then this gets passed to the function:

displayModels(JSON.parse(this.responseText))

then i have a function that is supposed to add insights of this array to the table:

/**
 * Updates the DOM tree in order to display users.
 *
 * @param {Array.<{name: String, max_passengers: Number}>} airplane_models
 */
function displayModels(airplane_models) {
    let tableBody = document.getElementById('tableBody');
    clearElementChildren(tableBody);
    airplane_models.forEach(model => {
        for(let key in model)
        {
            window.alert(key)
            tableBody.appendChild(createTableRow(key));
        }
    })
}

But this does not append the table, even the window.alert(key) never outputs anything.

I tried to modify A code in a various way, firstly by changing @param

* @param {{name: String, max_passengers: Number}[]} airplane_models

but it gives me basically the same output. I also tried modyfing the for loop:

Object.keys(airplane_models).forEach(model => {
    window.alert(model.name)
    tableBody.appendChild(createTableRow(model.name));
})

Exactly the same result, no output at window.alert(model.name)


问:
How i can solve diminssion problemwhen i used seqance to sequance attention model or any model has encoder_decoder for time series forecasting?
why does dimension error always appear when I run sequence to sequence model?

I'm trying to use sequence-to-sequence Attention to predict time series data, but always this error appears
ValueError: Found array with dim 3. Estimator expected <= 2.

I tried a lot to change the dimensions of X,y as well as the number of Features of RepeatVector

But this error always appears whenever I try to use a model that contains an encoder-decoder such as an autoencoder, transformer

```<code>time_steps = 24

# reshape to [samples, time_steps, n_features]

X_train, y_train = create_dataset(train, train.traffic_volume, time_steps)
X_test, y_test = create_dataset(test, test.traffic_volume, time_steps)

print('X_train:', X_train.shape, 'Y_train:', y_train.shape)
print('X_test:', X_test.shape, 'Y_test:', y_test.shape)
------
X_train: (28078, 24, 6) Y_train: (28078,)
X_test: (7002, 24, 6) Y_test: (7002,)

def create_seq2seqAtt():

    input_train = Input(shape=(X_train.shape[1], X_train.shape[2]))
   # output_train = Input(shape=(y_train_sequence.shape[1], y_train_sequence.shape[2]))

    encoder_stack_h, encoder_last_h, encoder_last_c = tf.keras.layers.LSTM(128, activation='relu',
                                                           dropout=0.2,
                                                           recurrent_dropout=0.2,
                                                           return_state=True,
                                                           return_sequences=True)(input_train)

    decoder_input = tf.keras.layers.RepeatVector(time_steps)(encoder_last_h)

    decoder_stack_h = tf.keras.layers.LSTM(128, activation='relu',
                           dropout=0.2,
                           recurrent_dropout=0.2,
                           return_state=False,
                           return_sequences=True)(decoder_input, initial_state=[encoder_last_h, encoder_last_c])

    attention = dot([decoder_stack_h, encoder_stack_h], axes=[2, 2])
    attention = Activation('softmax')(attention)

    context = dot([attention, encoder_stack_h], axes=[2,1])

    decoder_combined_context = concatenate([context, decoder_stack_h])

    out = tf.keras.layers.TimeDistributed(Dense(1))(decoder_combined_context)
    model = Model(inputs=input_train, outputs=out)

    opt = tf.keras.optimizers.Adam(learning_rate=0.0001, beta_1=0.9, beta_2=0.999, amsgrad=True)
    model.compile(optimizer=opt, loss='mse')
    model.summary()

    return model
model = create_seq2seqAtt()

start = dt.now()
lr =0.0001
adam = optimizers.Adam(lr)
model.compile(loss='mse', optimizer=adam)
monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=50,
                        verbose=1, mode='auto', restore_best_weights=True)

history = model.fit(X_train,y_train,validation_data=(X_test,y_test),callbacks=[monitor],verbose=2,epochs=50,batch_size=32)
# process stuff
running_secs = (dt.now() - start).seconds
running_secs

from sklearn import metrics
def timeseries_evaluation_metrics_func(y_true, y_pred):
    def mean_absolute_percentage_error(y_true, y_pred):
        y_true, y_pred = np.array(y_true), np.array(y_pred)
        return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
    print('Evaluation metric results:-')
    print(f'MSE is : {metrics.mean_squared_error(y_true, y_pred)}')
    print(f'MAE is : {metrics.mean_absolute_error(y_true, y_pred)}')
    print(f'RMSE is : {np.sqrt(metrics.mean_squared_error(y_true, y_pred))}')
    print(f'MAPE is : {mean_absolute_percentage_error(y_true, y_pred)}')
    print(f'R2 is : {metrics.r2_score(y_true, y_pred)}',end='\n\n')

y_pred = model.predict(X_test)
timeseries_evaluation_metrics_func(y_test , y_pred)

when i r un this code, this error appear

ValueError: Found array with dim 3. Estimator expected <= 2.
</code>```

Body:
why does dimension error always appear when I run sequence to sequence model?

I'm trying to use sequence-to-sequence Attention to predict time series data, but always this error appears
ValueError: Found array with dim 3. Estimator expected <= 2.

I tried a lot to change the dimensions of X,y as well as the number of Features of RepeatVector

But this error always appears whenever I try to use a model that contains an encoder-decoder such as an autoencoder, transformer

time_steps = 24

# reshape to [samples, time_steps, n_features]

X_train, y_train = create_dataset(train, train.traffic_volume, time_steps)
X_test, y_test = create_dataset(test, test.traffic_volume, time_steps)

print('X_train:', X_train.shape, 'Y_train:', y_train.shape)
print('X_test:', X_test.shape, 'Y_test:', y_test.shape)
------
X_train: (28078, 24, 6) Y_train: (28078,)
X_test: (7002, 24, 6) Y_test: (7002,)

def create_seq2seqAtt():

    input_train = Input(shape=(X_train.shape[1], X_train.shape[2]))
   # output_train = Input(shape=(y_train_sequence.shape[1], y_train_sequence.shape[2]))

    encoder_stack_h, encoder_last_h, encoder_last_c = tf.keras.layers.LSTM(128, activation='relu',
                                                           dropout=0.2,
                                                           recurrent_dropout=0.2,
                                                           return_state=True,
                                                           return_sequences=True)(input_train)

    decoder_input = tf.keras.layers.RepeatVector(time_steps)(encoder_last_h)

    decoder_stack_h = tf.keras.layers.LSTM(128, activation='relu',
                           dropout=0.2,
                           recurrent_dropout=0.2,
                           return_state=False,
                           return_sequences=True)(decoder_input, initial_state=[encoder_last_h, encoder_last_c])

    attention = dot([decoder_stack_h, encoder_stack_h], axes=[2, 2])
    attention = Activation('softmax')(attention)

    context = dot([attention, encoder_stack_h], axes=[2,1])

    decoder_combined_context = concatenate([context, decoder_stack_h])

    out = tf.keras.layers.TimeDistributed(Dense(1))(decoder_combined_context)
    model = Model(inputs=input_train, outputs=out)

    opt = tf.keras.optimizers.Adam(learning_rate=0.0001, beta_1=0.9, beta_2=0.999, amsgrad=True)
    model.compile(optimizer=opt, loss='mse')
    model.summary()

    return model
model = create_seq2seqAtt()

start = dt.now()
lr =0.0001
adam = optimizers.Adam(lr)
model.compile(loss='mse', optimizer=adam)
monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=50,
                        verbose=1, mode='auto', restore_best_weights=True)

history = model.fit(X_train,y_train,validation_data=(X_test,y_test),callbacks=[monitor],verbose=2,epochs=50,batch_size=32)
# process stuff
running_secs = (dt.now() - start).seconds
running_secs

from sklearn import metrics
def timeseries_evaluation_metrics_func(y_true, y_pred):
    def mean_absolute_percentage_error(y_true, y_pred):
        y_true, y_pred = np.array(y_true), np.array(y_pred)
        return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
    print('Evaluation metric results:-')
    print(f'MSE is : {metrics.mean_squared_error(y_true, y_pred)}')
    print(f'MAE is : {metrics.mean_absolute_error(y_true, y_pred)}')
    print(f'RMSE is : {np.sqrt(metrics.mean_squared_error(y_true, y_pred))}')
    print(f'MAPE is : {mean_absolute_percentage_error(y_true, y_pred)}')
    print(f'R2 is : {metrics.r2_score(y_true, y_pred)}',end='\n\n')

y_pred = model.predict(X_test)
timeseries_evaluation_metrics_func(y_test , y_pred)

when i r un this code, this error appear

ValueError: Found array with dim 3. Estimator expected <= 2.


问:
Databricks AutoML Python SDK for Model Serving
I am using Databricks AutoML ( Python SDK) to forecast bed occupancy. (Actually, Databricks used MLflow experiments for AutoML run). After training with different iterations I registered the best model in the Databricks Model registry.
Now I am trying to serve the register model and I have seen that it is always in the "Pending" stage and in the deployment log has an attached error message.

can anyone please help me here?

Note: Model artifacts has been created automatically as its from AutoML run. I think I don't have control to add pip dependency and package version.

```<code>Warning: you have pip-installed dependencies in your environment file, but you do not list pip itself as one of your conda dependencies.  Conda may not use the correct pip to install your packages, and they may end up in the wrong place.  Please add an explicit pip dependency.  I'm adding one for you, but still nagging you.
Collecting package metadata (repodata.json): ...working... done
Solving environment: ...working... done
Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
Pip subprocess error:
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/tmp/pip-install-_4rq4zju/numba_f054bd7eb658421087c86678b088efff/setup.py", line 51, in <module>
          _guard_py_ver()
        File "/tmp/pip-install-_4rq4zju/numba_f054bd7eb658421087c86678b088efff/setup.py", line 48, in _guard_py_ver
          raise RuntimeError(msg.format(cur_py, min_py, max_py))
      RuntimeError: Cannot install on Python version 3.11.0; only versions >=3.7,<3.11 are supported.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

Body:
I am using Databricks AutoML ( Python SDK) to forecast bed occupancy. (Actually, Databricks used MLflow experiments for AutoML run). After training with different iterations I registered the best model in the Databricks Model registry.
Now I am trying to serve the register model and I have seen that it is always in the "Pending" stage and in the deployment log has an attached error message.

can anyone please help me here?

Note: Model artifacts has been created automatically as its from AutoML run. I think I don't have control to add pip dependency and package version.

Warning: you have pip-installed dependencies in your environment file, but you do not list pip itself as one of your conda dependencies.  Conda may not use the correct pip to install your packages, and they may end up in the wrong place.  Please add an explicit pip dependency.  I'm adding one for you, but still nagging you.
Collecting package metadata (repodata.json): ...working... done
Solving environment: ...working... done
Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
Pip subprocess error:
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/tmp/pip-install-_4rq4zju/numba_f054bd7eb658421087c86678b088efff/setup.py", line 51, in <module>
          _guard_py_ver()
        File "/tmp/pip-install-_4rq4zju/numba_f054bd7eb658421087c86678b088efff/setup.py", line 48, in _guard_py_ver
          raise RuntimeError(msg.format(cur_py, min_py, max_py))
      RuntimeError: Cannot install on Python version 3.11.0; only versions >=3.7,<3.11 are supported.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.


问:
Sshd config ignores PasswordAuthentication yes
I have a following part sshd config, after applying it and checking using sshd -T it write that everything is right:

```<code># Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

Match User auditor
  PasswordAuthentication yes
  PubkeyAuthentication no
</code>```

However when I try to ssh into server using auditor user, it just will not accept password:

```<code>debug1: load_hostkeys: fopen /Users/x/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: Host '223.136.90.81' is known and matches the ED25519 host key.
debug1: Found key in /Users/x/.ssh/known_hosts:226
debug1: Will attempt key: /Users/x/.ssh/id_rsa RSA
debug1: Will attempt key: /Users/x/.ssh/id_ecdsa
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: password
auditor@213.136.90.91's password:
debug1: Authentications that can continue: gssapi-keyex,gssapi-with-mic,password
Permission denied, please try again.
</code>```

Body:
I have a following part sshd config, after applying it and checking using sshd -T it write that everything is right:

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

Match User auditor
  PasswordAuthentication yes
  PubkeyAuthentication no

However when I try to ssh into server using auditor user, it just will not accept password:

debug1: load_hostkeys: fopen /Users/x/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: Host '223.136.90.81' is known and matches the ED25519 host key.
debug1: Found key in /Users/x/.ssh/known_hosts:226
debug1: Will attempt key: /Users/x/.ssh/id_rsa RSA
debug1: Will attempt key: /Users/x/.ssh/id_ecdsa
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: password
auditor@213.136.90.91's password:
debug1: Authentications that can continue: gssapi-keyex,gssapi-with-mic,password
Permission denied, please try again.


问:
How to get proper message response from json POST instead of "The remote server returned an error: (422) Unprocessable Entity"
I have tried to get the same response that I get from Postman from my code.

I have tried the two methods below:

```<code>string responsedata = string.Empty;
byte[] dataBytes = Encoding.UTF8.GetBytes(jsonData);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = "application/json";
request.Method = "POST";

using (Stream requestBody = request.GetRequestStream())
{
    requestBody.Write(dataBytes, 0, dataBytes.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    responsedata = reader.ReadToEnd();
}

return responsedata;
</code>```

And also tried this:

```<code>HttpClient clinet = new HttpClient();

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    result = client.UploadString(url, "POST", jsonData);
}

return result;
</code>```

However, both return the error : "The remote server returned an error: (422) Unprocessable Entity" when there is an mistake made in the json. It goes through well if a user does not make a mistake on a wrong form entry.

However, when I run the same "mistake" json on Postman, this is the response I get:

```<code>{
    "Error": {
        "code": "NOT_MATCHING_TAXRATE",
        "message": "Error on transaction line 1: Tax rate for HSCode: 0057.11.00 should be '0' instead of '16'."
    }
}
</code>```

However, the Status in Postman still shows: 422 Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors.

What do I need to change to capture the actual error like the above which is very useful to the end user?

Body:
I have tried to get the same response that I get from Postman from my code.

I have tried the two methods below:

string responsedata = string.Empty;
byte[] dataBytes = Encoding.UTF8.GetBytes(jsonData);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = "application/json";
request.Method = "POST";

using (Stream requestBody = request.GetRequestStream())
{
    requestBody.Write(dataBytes, 0, dataBytes.Length);
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    responsedata = reader.ReadToEnd();
}

return responsedata;

And also tried this:

HttpClient clinet = new HttpClient();

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    result = client.UploadString(url, "POST", jsonData);
}

return result;

However, both return the error : "The remote server returned an error: (422) Unprocessable Entity" when there is an mistake made in the json. It goes through well if a user does not make a mistake on a wrong form entry.

However, when I run the same "mistake" json on Postman, this is the response I get:

{
    "Error": {
        "code": "NOT_MATCHING_TAXRATE",
        "message": "Error on transaction line 1: Tax rate for HSCode: 0057.11.00 should be '0' instead of '16'."
    }
}

However, the Status in Postman still shows: 422 Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors.

What do I need to change to capture the actual error like the above which is very useful to the end user?


问:
CommandInvokationFailure: Gradle build failed - classes2.dex
I have this error on my Unity build:

```<code>CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2021.3.12f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2021.3.12f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-6.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleDebug"
</code>```

In the details I see this error :

```<code>Execution failed for task ':launcher:packageDebug'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > java.lang.IllegalStateException: Entry name 'classes2.dex' collided
</code>```

I find this solution here: Entry name 'classes.dex' collided

I can't find a solution to this issue..

Body:
I have this error on my Unity build:

CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2021.3.12f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2021.3.12f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-6.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleDebug"

In the details I see this error :

Execution failed for task ':launcher:packageDebug'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > java.lang.IllegalStateException: Entry name 'classes2.dex' collided

I find this solution here: Entry name 'classes.dex' collided

I can't find a solution to this issue..


问:
Options Trading Back-testing Strategy Issue
I have been getting the following error message:

```<code>IndexError                                Traceback (most recent call last)
Cell In [29], line 12
      8 for index, row in df.iterrows():
      9     # if the 50-day moving average is above the 200-day moving average
     10     if row['ma50'] > row['ma200']:
     11         # get the call options data for the current date
---> 12         call_options = options[5]['calls']
     13         # find the call option with the highest implied volatility
     14         max_iv_call = call_options[call_options['impliedVolatility'] == call_options['impliedVolatility'].max()]

IndexError: tuple index out of range
</code>```

I have tried multiple things, but to no avail. What could I do to resolve the issue?

Why did my options trading strategy fail in this back-test? I had such high hopes for it, expecting it to bring in a profit based on the data and assumptions I inputted. But instead, it resulted in a loss. Is there a problem with the back-testing tool I'm using, or is there something else at play here? I implore anyone with experience in this field to offer their insights and suggestions on how to troubleshoot this frustrating issue. I have developed an options trading back-testing strategy as follows:

```<code>import yfinance as yf

start_date = "2020-01-01"
end_date = "2022-12-31"

stock = yf.Ticker("SPY")
df = stock.history(start=start_date, end=end_date)

def moving_average(df, window):
    return df['Close'].rolling(window=window).mean()

df['ma50'] = moving_average(df, 50)
df['ma200'] = moving_average(df, 200)

position = 0

long_trades = 0
short_trades = 0

options = stock.option_chain()

for index, row in df.iterrows():
    # if the 50-day moving average is above the 200-day moving average
    if row['ma50'] > row['ma200']:
        # get the call options data for the current date
        call_options = options[5]['calls']
        # find the call option with the highest implied volatility
        max_iv_call = call_options[call_options['impliedVolatility'] == call_options['impliedVolatility'].max()]
        # buy the call option with the highest implied volatility
        long_trades += 1
    # if the 50-day moving average is below the 200-day moving average
    elif row['ma50'] < row['ma200']:
        # get the put options data for the current date
        put_options = options[index.date()]['puts']
        # find the put option with the highest implied volatility
        max_iv_put = put_options[put_options['impliedVolatility'] == put_options['impliedVolatility'].max()]
        # buy the put option with the highest implied volatility
        short_trades += 1

print(f"Number of long trades: {long_trades}")
print(f"Number of short trades: {short_trades}")
</code>```

Body:
I have been getting the following error message:

IndexError                                Traceback (most recent call last)
Cell In [29], line 12
      8 for index, row in df.iterrows():
      9     # if the 50-day moving average is above the 200-day moving average
     10     if row['ma50'] > row['ma200']:
     11         # get the call options data for the current date
---> 12         call_options = options[5]['calls']
     13         # find the call option with the highest implied volatility
     14         max_iv_call = call_options[call_options['impliedVolatility'] == call_options['impliedVolatility'].max()]

IndexError: tuple index out of range

I have tried multiple things, but to no avail. What could I do to resolve the issue?

Why did my options trading strategy fail in this back-test? I had such high hopes for it, expecting it to bring in a profit based on the data and assumptions I inputted. But instead, it resulted in a loss. Is there a problem with the back-testing tool I'm using, or is there something else at play here? I implore anyone with experience in this field to offer their insights and suggestions on how to troubleshoot this frustrating issue. I have developed an options trading back-testing strategy as follows:

import yfinance as yf

start_date = "2020-01-01"
end_date = "2022-12-31"

stock = yf.Ticker("SPY")
df = stock.history(start=start_date, end=end_date)

def moving_average(df, window):
    return df['Close'].rolling(window=window).mean()

df['ma50'] = moving_average(df, 50)
df['ma200'] = moving_average(df, 200)

position = 0

long_trades = 0
short_trades = 0

options = stock.option_chain()

for index, row in df.iterrows():
    # if the 50-day moving average is above the 200-day moving average
    if row['ma50'] > row['ma200']:
        # get the call options data for the current date
        call_options = options[5]['calls']
        # find the call option with the highest implied volatility
        max_iv_call = call_options[call_options['impliedVolatility'] == call_options['impliedVolatility'].max()]
        # buy the call option with the highest implied volatility
        long_trades += 1
    # if the 50-day moving average is below the 200-day moving average
    elif row['ma50'] < row['ma200']:
        # get the put options data for the current date
        put_options = options[index.date()]['puts']
        # find the put option with the highest implied volatility
        max_iv_put = put_options[put_options['impliedVolatility'] == put_options['impliedVolatility'].max()]
        # buy the put option with the highest implied volatility
        short_trades += 1

print(f"Number of long trades: {long_trades}")
print(f"Number of short trades: {short_trades}")


问:
Changing the default behavior of the mobile button "Go Back". React Native
I have a BottomTabsNavigator with two buttons: home and menu, the screen for menu shows a list of items that are clickable, it allows the user to navigate to another screen (say ShowDishes) that is not in the BottomTabsNavigator (because I made it invisible)

This other screen is also a list of clickable elements that allow the user to navigate to another screen (say ShowDish).

The problem is that if the user presses the default mobile phone button “go back”, it will navigate to home, and not to the previous screen that it was on

I’m using navigation.navigate:

```<code>navigation.navigate("Other Screen", {
    someProperty: { someValue},
});
</code>```

With this navigation I can pass arguments (and this is one reason I made some buttons invisible, since these screens need some arguments to operate, from the bottom tab menu button I don't have the values, but from the items themselves I do have the values given by the FlatList (index))

So the user can navigate to the ShowDishes screen, then it can navigate to the ShowDish screen, but if the user presses the default android button of “Go Back”, how can I lead the user to the ShowDishes screen? (if the user was in ShowDish), but it goes to Home instead (there are only two buttons, Menu and Home in the BottomTabsNavigator, I imagine it is the reason why)

Thanks in advance

EDIT

The main idea is: two buttons tabs: home and ShowCategories.

ShowCategories show a list of categories, each category is a list of dishes,  no special navigation yet

But when the user presses a category it navigates to ShowDishes, which is a list of dishes, then pressing one of them, it navigates to ShowDish (navigation ends here)

```<code>           <MainTab.Navigator
                initialRouteName="ShowCategories"
                screenOptions={{
                    tabBarActiveTintColor: "white",
                    tabBarInactiveTintColor: "black",
                    tabBarStyle: {
                        backgroundColor: "gray",
                    },
                }}
            >
                <MainTab.Screen
                    name="Home"
                    options={({ route }) => ({
                        headerShown: false,
                    })}
                    component={Home}
                />
                <MainTab.Screen
                    name="ShowCategories"
                    options={({ route }) => ({
                        headerShown: false,
                    })}
                    component={ShowCategories}
                />
                <MainTab.Screen
                    name="ShowDishes"
                    component={ShowDishes}
                    options={({ route }) => ({
                        headerShown: false,
                        tabBarButton: () => null,
                        tabBarVisible: false, //hide tab bar on this screen
                    })}
                />
                <MainTab.Screen
                    name="ShowDish"
                    component={ShowDish}
                    options={({ route }) => ({
                        headerShown: false,
                        tabBarButton: () => null,
                        tabBarVisible: false, //hide tab bar on this screen
                    })}
                />
            </MainTab.Navigator>
</code>```

And the navigations. In order to go to ShowDishes:

```<code><Pressable
    onPress={() => {
        navigation.navigate("ShowDishes", {
            categoryIndex: { itemIndex },
        });
    }} ...
</code>```

In order to go to ShowDish:

```<code><Pressable
    onPress={() => {
        let propsForShowDish = {
            categoryIndex: { categoryIndex },
            itemIndex: { itemIndex },
        };

        navigation.navigate("ShowDish", {
            propsForShowDish: propsForShowDish,
        });
    }} ...
</code>```

I works good. But, if the app is in ShowDish, going back should mean to go back to ShowDishes, but instead, it gos to home, which is the other button in ButtonTabs

Body:
I have a BottomTabsNavigator with two buttons: home and menu, the screen for menu shows a list of items that are clickable, it allows the user to navigate to another screen (say ShowDishes) that is not in the BottomTabsNavigator (because I made it invisible)

This other screen is also a list of clickable elements that allow the user to navigate to another screen (say ShowDish).

The problem is that if the user presses the default mobile phone button “go back”, it will navigate to home, and not to the previous screen that it was on

I’m using navigation.navigate:

navigation.navigate("Other Screen", {
    someProperty: { someValue},
});

With this navigation I can pass arguments (and this is one reason I made some buttons invisible, since these screens need some arguments to operate, from the bottom tab menu button I don't have the values, but from the items themselves I do have the values given by the FlatList (index))

So the user can navigate to the ShowDishes screen, then it can navigate to the ShowDish screen, but if the user presses the default android button of “Go Back”, how can I lead the user to the ShowDishes screen? (if the user was in ShowDish), but it goes to Home instead (there are only two buttons, Menu and Home in the BottomTabsNavigator, I imagine it is the reason why)

Thanks in advance

EDIT

The main idea is: two buttons tabs: home and ShowCategories.

ShowCategories show a list of categories, each category is a list of dishes,  no special navigation yet

But when the user presses a category it navigates to ShowDishes, which is a list of dishes, then pressing one of them, it navigates to ShowDish (navigation ends here)

           <MainTab.Navigator
                initialRouteName="ShowCategories"
                screenOptions={{
                    tabBarActiveTintColor: "white",
                    tabBarInactiveTintColor: "black",
                    tabBarStyle: {
                        backgroundColor: "gray",
                    },
                }}
            >
                <MainTab.Screen
                    name="Home"
                    options={({ route }) => ({
                        headerShown: false,
                    })}
                    component={Home}
                />
                <MainTab.Screen
                    name="ShowCategories"
                    options={({ route }) => ({
                        headerShown: false,
                    })}
                    component={ShowCategories}
                />
                <MainTab.Screen
                    name="ShowDishes"
                    component={ShowDishes}
                    options={({ route }) => ({
                        headerShown: false,
                        tabBarButton: () => null,
                        tabBarVisible: false, //hide tab bar on this screen
                    })}
                />
                <MainTab.Screen
                    name="ShowDish"
                    component={ShowDish}
                    options={({ route }) => ({
                        headerShown: false,
                        tabBarButton: () => null,
                        tabBarVisible: false, //hide tab bar on this screen
                    })}
                />
            </MainTab.Navigator>

And the navigations. In order to go to ShowDishes:

<Pressable
    onPress={() => {
        navigation.navigate("ShowDishes", {
            categoryIndex: { itemIndex },
        });
    }} ...

In order to go to ShowDish:

<Pressable
    onPress={() => {
        let propsForShowDish = {
            categoryIndex: { categoryIndex },
            itemIndex: { itemIndex },
        };

        navigation.navigate("ShowDish", {
            propsForShowDish: propsForShowDish,
        });
    }} ...

I works good. But, if the app is in ShowDish, going back should mean to go back to ShowDishes, but instead, it gos to home, which is the other button in ButtonTabs


问:
Apache Arrow C++: What's the best fast alternative to parquet::StreamWriter?
I'm writing a program to convert a tabular ("rownar") custom binary file format to Parquet using Arrow C++.

The core of the program works as follows:

ColInfo colinfo = ...; // fixed schema per file, not known at compile time
parquet::StreamWriter w = ...;

on_row(RowData row) {
  for (col : colinfo) {
    w << convertCell(row, col);
  }
}
```

Here, on_row is called by the input file parser for each row parsed.

This works fine but is pretty slow, with StreamWriter::<< being the bottleneck.

Question: What's an alternative to StreamWriter that's similarly easy to use but faster?

Constraints:

Can't change the callback-based interface shown above.

Input data doesn't fit into memory.

I've looked into the reader_writer{,2}.cc examples in the Arrow repository that use the WriteBatch interface. Is that the recommended way to quickly create Parquet files? If so, what's the recommended way to size row groups? Or is there an interface that abstracts away row groups, like with StreamWriter? And what's the recommended size num_values to WriteBatch?

Secondary question: What are some good opportunities to concurrently create the Parquet file? Can batches, chunks, columns, or row groups by written concurrently?

Body:
I'm writing a program to convert a tabular ("rownar") custom binary file format to Parquet using Arrow C++.

The core of the program works as follows:

ColInfo colinfo = ...; // fixed schema per file, not known at compile time
parquet::StreamWriter w = ...;

on_row(RowData row) {
  for (col : colinfo) {
    w << convertCell(row, col);
  }
}

Here, on_row is called by the input file parser for each row parsed.

This works fine but is pretty slow, with StreamWriter::<< being the bottleneck.

Question: What's an alternative to StreamWriter that's similarly easy to use but faster?

Constraints:

Can't change the callback-based interface shown above.

Input data doesn't fit into memory.

I've looked into the reader_writer{,2}.cc examples in the Arrow repository that use the WriteBatch interface. Is that the recommended way to quickly create Parquet files? If so, what's the recommended way to size row groups? Or is there an interface that abstracts away row groups, like with StreamWriter? And what's the recommended size num_values to WriteBatch?

Secondary question: What are some good opportunities to concurrently create the Parquet file? Can batches, chunks, columns, or row groups by written concurrently?