问:
create snake game add block function
```<code>import pygame
from screeninfo import get_monitors
import numpy as np

pygame.init()

class Snake:
    def __init__(self):
        self.color_body = (140, 13, 17)
        self.color_head = (59, 5, 7)
        self.body_rect = []
        self.head_move_x = 0
        self.head_move_y = 0
        self.head_x = 12 * width//25
        self.head_y = 6 * height//13
        self.body_x = np.array([11 * width//25, 10 * width//25, 9 * width//25])
        self.body_y = np.array(
            [6 * height//13, 6 * height//13, 6 * height//13])
        self.body_move_x = self.body_x
        self.body_move_y = self.body_y
        self.start = False

    def draw(self):
        self.move()
        self.check_fill()
        self.body_rect = []

        for index_x, index_y in zip(self.body_x, self.body_y):
            self.body_rect.append(pygame.Rect(
                index_x, index_y, width//24.8, height//13))

        self.head_pos = np.array([self.head_x, self.head_y])
        head_rect = pygame.Rect(
            self.head_pos[0], self.head_pos[1], width//24.8, height//13)

        pygame.draw.rect(screen, self.color_head, head_rect)

        for index in self.body_rect[:-1]:
            pygame.draw.rect(screen, self.color_body, index)

    def move(self):

        length = len(self.body_rect)
        if self.start:
            for index in range(1, length):
                self.body_move_x[index] = self.body_move_x[index-1]
                self.body_move_y[index] = self.body_move_y[index-1]
            self.body_move_x[0] = self.head_x
            self.body_move_y[0] = self.head_y

        self.head_x += self.head_move_x
        self.head_y += self.head_move_y

        self.body_x = self.body_move_x
        self.body_y = self.body_move_y

    def reset_snake(self):
        self.body_rect = []
        self.head_move_x = 0
        self.head_move_y = 0
        self.head_x = 12 * width//25
        self.head_y = 6 * height//13
        self.body_x = np.array([11 * width//25, 10 * width//25, 9 * width//25])
        self.body_y = np.array(
            [6 * height//13, 6 * height//13, 6 * height//13])
        self.body_move_x = self.body_x
        self.body_move_y = self.body_y
        self.start = False

    def add_block(self):
        self.body_move_x = np.append(self.body_move_x, [self.body_move_x[-1]+1 * width//25])
        self.body_move_y = np.append(self.body_move_y, [self.body_move_y[-1]+1 * height//13])

    def check_fill(self):
        if (
            not 0-6 < self.head_x < (width-width//25)+6
            or not 0-3 < self.head_y < (height-height//13)+3
        ):
            pygame.time.delay(160)
            self.reset_snake()

class grass:
    def __init__(self):
        self.color = (167, 209, 61)

    def draw(self):
        for col in range(width//2):
            if col % 2 == 0:
                for row in range(height//2):
                    if row % 2 == 0:
                        grass = pygame.Rect(
                            col * width//25, row * height//13, width//25, height//13)
                    pygame.draw.rect(screen, self.color, grass)
            else:
                for row in range(height//2):
                    if row % 2 != 0:
                        grass = pygame.Rect(
                            col * width//25, row * height//13, width//25, height//13)
                    pygame.draw.rect(screen, self.color, grass)

class settings_button:

    def __init__(self):

        self.x = (width//56) * 2
        self.y = (width//56) * 2

        self.image = pygame.transform.scale(
            pygame.image.load("settings.png"), (width//24, width//24))

    def draw(self):

        surface = self.image.get_rect(center=(self.x//2, self.y//2))
        screen.blit(self.image, surface)

    def pressed(self):
        if (self.x >= (pygame.mouse.get_pos()[0]) >= 0 and self.y >= (pygame.mouse.get_pos()[1]) >= 0 and pygame.mouse.get_pressed()[0]):
            return True
        else:
            return False

class settings:
    def __init__(self):

        self.font = pygame.font.Font("Hack-Regular.ttf", width//20)

        self.text_q = 'Quit'
        self.text_r = 'Replay'
        self.text_b = 'Resumption'
        self.text_s = 'Sound:'
        self.text_p = 'Play'
        self.text_m = 'Mute'

        self.Quit_surface = self.font.render(self.text_q, True, 'red')
        self.Replay_surface = self.font.render(self.text_r, True, 'cyan')
        self.Resumption_surface = self.font.render(self.text_b, True, 'cyan')
        self.Sound_surface = self.font.render(self.text_s, True, 'pink')
        self.Mute_surface = self.font.render(self.text_m, True, 'pink')
        self.Play_surface = self.font.render(self.text_p, True, 'pink')

        self.Quit_rect = self.Quit_surface.get_rect(
            center=((width//2), (height) - (self.Quit_surface.get_height()//2)))
        self.Replay_rect = self.Replay_surface.get_rect(
            center=((width//2), (height//2.5) - (self.Replay_surface.get_height()//2)))
        self.Resumption_rect = self.Resumption_surface.get_rect(
            center=((width//2), (height//1.5) - (self.Resumption_surface.get_height()//2)))
        self.Sound_rect = self.Sound_surface.get_rect(
            center=((width//2.4), (height//8) - (self.Sound_surface.get_height()//2)))
        self.Mute_rect = self.Mute_surface.get_rect(
            center=((width//1.7), (height//8) - (self.Mute_surface.get_height()//2)))
        self.Play_rect = self.Play_surface.get_rect(
            center=((width//1.7), (height//8) - (self.Play_surface.get_height()//2)))

    def draw(self, sound_mode):

        screen.blit(self.Quit_surface, self.Quit_rect)
        screen.blit(self.Replay_surface, self.Replay_rect)
        screen.blit(self.Resumption_surface, self.Resumption_rect)
        screen.blit(self.Sound_surface, self.Sound_rect)
        if sound_mode == 'Play':
            screen.blit(self.Mute_surface, self.Mute_rect)
        elif sound_mode == 'Mute':
            screen.blit(self.Play_surface, self.Play_rect)

    def pressed(self, sound_mode=None):
        if (self.Quit_rect.x + self.Quit_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Quit_rect.x and self.Quit_rect.y + self.Quit_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Quit_rect.y and pygame.mouse.get_pressed()[0]):
            return 'Quit'
        elif (self.Replay_rect.x + self.Replay_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Replay_rect.x and self.Replay_rect.y + self.Replay_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Replay_rect.y and pygame.mouse.get_pressed()[0]):
            return 'Replay'
        elif (self.Resumption_rect.x + self.Resumption_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Resumption_rect.x and self.Resumption_rect.y + self.Resumption_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Resumption_rect.y and pygame.mouse.get_pressed()[0]):
            return 'Resumption'
        elif (self.Mute_rect.x + self.Mute_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Mute_rect.x and self.Mute_rect.y + self.Mute_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Mute_rect.y and pygame.mouse.get_pressed()[0] and sound_mode == 'Play'):
            return 'Mute'
        elif (self.Play_rect.x + self.Play_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Play_rect.x and self.Play_rect.y + self.Play_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Play_rect.y and pygame.mouse.get_pressed()[0] and sound_mode == 'Mute'):
            return 'Play'

for index in get_monitors():
    width = index.width
    height = index.height

screen = pygame.display.set_mode((width, height))

click_sound = pygame.mixer.Sound('click1.wav')

settings_button_var = settings_button()
settings_var = settings()
grass_block = grass()
snake = Snake()

screen.fill((175, 220, 70))
grass_block.draw()
join_settings = False

sound_mode = 'Play'

deafult_numbers = np.array([height//13, -(height//13)])
w_test = width//24.8
snake.add_block()
colck = pygame.time.Clock()

try:
    while True:
        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()  # Finish Work For pygame
                break

            if settings_button_var.pressed():
                if not join_settings and sound_mode == 'Play':
                    click_sound.play()
                if not join_settings:
                    join_settings = True
                screen.fill((149, 184, 68))
                settings_var.draw(sound_mode)
                pygame.display.update()

            pygame.display.update()

            if not join_settings:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP and snake.head_move_y != deafult_numbers[0]:
                        snake.start = True
                        snake.head_move_y = deafult_numbers[1]
                        snake.head_move_x = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                        if settings_button_var.pressed():
                            if not join_settings and sound_mode == 'Play':
                                click_sound.play()
                            if not join_settings:
                                join_settings = True
                            screen.fill((149, 184, 68))
                            settings_var.draw(sound_mode)
                            pygame.display.update()

                        pygame.display.update()
                    elif event.key == pygame.K_DOWN and snake.head_move_y != deafult_numbers[1]:
                        snake.start = True
                        snake.head_move_y = deafult_numbers[0]
                        snake.head_move_x = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                        if settings_button_var.pressed():
                            if not join_settings and sound_mode == 'Play':
                                click_sound.play()
                            if not join_settings:
                                join_settings = True
                            screen.fill((149, 184, 68))
                            settings_var.draw(sound_mode)
                            pygame.display.update()

                        pygame.display.update()
                    elif event.key == pygame.K_LEFT and snake.head_move_x != w_test and snake.start:
                        snake.start = True
                        snake.head_move_x = -(w_test)
                        snake.head_move_y = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                        if settings_button_var.pressed():
                            if not join_settings and sound_mode == 'Play':
                                click_sound.play()
                            if not join_settings:
                                join_settings = True
                            screen.fill((149, 184, 68))
                            settings_var.draw(sound_mode)
                            pygame.display.update()

                        pygame.display.update()
                    elif event.key == pygame.K_RIGHT and snake.head_move_x != -(w_test):
                        snake.start = True
                        snake.head_move_x = w_test
                        snake.head_move_y = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                            if settings_button_var.pressed():
                                if not join_settings and sound_mode == 'Play':
                                    click_sound.play()
                                if not join_settings:
                                    join_settings = True
                                screen.fill((149, 184, 68))
                                settings_var.draw(sound_mode)
                                pygame.display.update()

                        pygame.display.update()

        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()

        pygame.display.update()

        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()

        if not join_settings:
            screen.fill((175, 220, 70))
            grass_block.draw()
            snake.draw()
            settings_button_var.draw()

        pygame.display.update()

        if join_settings:
            if settings_var.pressed() == 'Quit':
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                pygame.quit()  # Finish Work For pygame
                break

            elif settings_var.pressed() == 'Resumption':
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                screen.fill((175, 220, 70))
                join_settings = False

                pygame.display.update()

            elif settings_var.pressed() == 'Replay':
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                snake.reset_snake()
                join_settings = False

                pygame.display.update()

            elif settings_var.pressed(sound_mode) == 'Mute' and sound_mode == 'Play':
                screen.fill((149, 184, 68))
                sound_mode = 'Mute'
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                settings_var.draw(sound_mode)
                pygame.display.update()
                pygame.time.delay(150)

            elif settings_var.pressed(sound_mode) == 'Play' and sound_mode == 'Mute':
                screen.fill((149, 184, 68))
                sound_mode = 'Play'
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                settings_var.draw(sound_mode)
                pygame.display.update()
                pygame.time.delay(150)

        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()

        pygame.display.update()

        colck.tick(100)

except:
    pass
</code>```

i want add a function to add new block for a snake

======================================

======================================

if you see any problem in my code insert me

i don't why the block delete after start a moving

Title: create snake game add block function

Body:
import pygame
from screeninfo import get_monitors
import numpy as np

pygame.init()

class Snake:
    def __init__(self):
        self.color_body = (140, 13, 17)
        self.color_head = (59, 5, 7)
        self.body_rect = []
        self.head_move_x = 0
        self.head_move_y = 0
        self.head_x = 12 * width//25
        self.head_y = 6 * height//13
        self.body_x = np.array([11 * width//25, 10 * width//25, 9 * width//25])
        self.body_y = np.array(
            [6 * height//13, 6 * height//13, 6 * height//13])
        self.body_move_x = self.body_x
        self.body_move_y = self.body_y
        self.start = False

    def draw(self):
        self.move()
        self.check_fill()
        self.body_rect = []

        for index_x, index_y in zip(self.body_x, self.body_y):
            self.body_rect.append(pygame.Rect(
                index_x, index_y, width//24.8, height//13))

        self.head_pos = np.array([self.head_x, self.head_y])
        head_rect = pygame.Rect(
            self.head_pos[0], self.head_pos[1], width//24.8, height//13)

        pygame.draw.rect(screen, self.color_head, head_rect)

        for index in self.body_rect[:-1]:
            pygame.draw.rect(screen, self.color_body, index)

    def move(self):

        length = len(self.body_rect)
        if self.start:
            for index in range(1, length):
                self.body_move_x[index] = self.body_move_x[index-1]
                self.body_move_y[index] = self.body_move_y[index-1]
            self.body_move_x[0] = self.head_x
            self.body_move_y[0] = self.head_y

        self.head_x += self.head_move_x
        self.head_y += self.head_move_y

        self.body_x = self.body_move_x
        self.body_y = self.body_move_y

    def reset_snake(self):
        self.body_rect = []
        self.head_move_x = 0
        self.head_move_y = 0
        self.head_x = 12 * width//25
        self.head_y = 6 * height//13
        self.body_x = np.array([11 * width//25, 10 * width//25, 9 * width//25])
        self.body_y = np.array(
            [6 * height//13, 6 * height//13, 6 * height//13])
        self.body_move_x = self.body_x
        self.body_move_y = self.body_y
        self.start = False

    def add_block(self):
        self.body_move_x = np.append(self.body_move_x, [self.body_move_x[-1]+1 * width//25])
        self.body_move_y = np.append(self.body_move_y, [self.body_move_y[-1]+1 * height//13])

    def check_fill(self):
        if (
            not 0-6 < self.head_x < (width-width//25)+6
            or not 0-3 < self.head_y < (height-height//13)+3
        ):
            pygame.time.delay(160)
            self.reset_snake()

class grass:
    def __init__(self):
        self.color = (167, 209, 61)

    def draw(self):
        for col in range(width//2):
            if col % 2 == 0:
                for row in range(height//2):
                    if row % 2 == 0:
                        grass = pygame.Rect(
                            col * width//25, row * height//13, width//25, height//13)
                    pygame.draw.rect(screen, self.color, grass)
            else:
                for row in range(height//2):
                    if row % 2 != 0:
                        grass = pygame.Rect(
                            col * width//25, row * height//13, width//25, height//13)
                    pygame.draw.rect(screen, self.color, grass)

class settings_button:

    def __init__(self):

        self.x = (width//56) * 2
        self.y = (width//56) * 2

        self.image = pygame.transform.scale(
            pygame.image.load("settings.png"), (width//24, width//24))

    def draw(self):

        surface = self.image.get_rect(center=(self.x//2, self.y//2))
        screen.blit(self.image, surface)

    def pressed(self):
        if (self.x >= (pygame.mouse.get_pos()[0]) >= 0 and self.y >= (pygame.mouse.get_pos()[1]) >= 0 and pygame.mouse.get_pressed()[0]):
            return True
        else:
            return False

class settings:
    def __init__(self):

        self.font = pygame.font.Font("Hack-Regular.ttf", width//20)

        self.text_q = 'Quit'
        self.text_r = 'Replay'
        self.text_b = 'Resumption'
        self.text_s = 'Sound:'
        self.text_p = 'Play'
        self.text_m = 'Mute'

        self.Quit_surface = self.font.render(self.text_q, True, 'red')
        self.Replay_surface = self.font.render(self.text_r, True, 'cyan')
        self.Resumption_surface = self.font.render(self.text_b, True, 'cyan')
        self.Sound_surface = self.font.render(self.text_s, True, 'pink')
        self.Mute_surface = self.font.render(self.text_m, True, 'pink')
        self.Play_surface = self.font.render(self.text_p, True, 'pink')

        self.Quit_rect = self.Quit_surface.get_rect(
            center=((width//2), (height) - (self.Quit_surface.get_height()//2)))
        self.Replay_rect = self.Replay_surface.get_rect(
            center=((width//2), (height//2.5) - (self.Replay_surface.get_height()//2)))
        self.Resumption_rect = self.Resumption_surface.get_rect(
            center=((width//2), (height//1.5) - (self.Resumption_surface.get_height()//2)))
        self.Sound_rect = self.Sound_surface.get_rect(
            center=((width//2.4), (height//8) - (self.Sound_surface.get_height()//2)))
        self.Mute_rect = self.Mute_surface.get_rect(
            center=((width//1.7), (height//8) - (self.Mute_surface.get_height()//2)))
        self.Play_rect = self.Play_surface.get_rect(
            center=((width//1.7), (height//8) - (self.Play_surface.get_height()//2)))

    def draw(self, sound_mode):

        screen.blit(self.Quit_surface, self.Quit_rect)
        screen.blit(self.Replay_surface, self.Replay_rect)
        screen.blit(self.Resumption_surface, self.Resumption_rect)
        screen.blit(self.Sound_surface, self.Sound_rect)
        if sound_mode == 'Play':
            screen.blit(self.Mute_surface, self.Mute_rect)
        elif sound_mode == 'Mute':
            screen.blit(self.Play_surface, self.Play_rect)

    def pressed(self, sound_mode=None):
        if (self.Quit_rect.x + self.Quit_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Quit_rect.x and self.Quit_rect.y + self.Quit_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Quit_rect.y and pygame.mouse.get_pressed()[0]):
            return 'Quit'
        elif (self.Replay_rect.x + self.Replay_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Replay_rect.x and self.Replay_rect.y + self.Replay_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Replay_rect.y and pygame.mouse.get_pressed()[0]):
            return 'Replay'
        elif (self.Resumption_rect.x + self.Resumption_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Resumption_rect.x and self.Resumption_rect.y + self.Resumption_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Resumption_rect.y and pygame.mouse.get_pressed()[0]):
            return 'Resumption'
        elif (self.Mute_rect.x + self.Mute_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Mute_rect.x and self.Mute_rect.y + self.Mute_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Mute_rect.y and pygame.mouse.get_pressed()[0] and sound_mode == 'Play'):
            return 'Mute'
        elif (self.Play_rect.x + self.Play_surface.get_width() >= (pygame.mouse.get_pos()[0]) >= self.Play_rect.x and self.Play_rect.y + self.Play_surface.get_height() >= (pygame.mouse.get_pos()[1]) >= self.Play_rect.y and pygame.mouse.get_pressed()[0] and sound_mode == 'Mute'):
            return 'Play'

for index in get_monitors():
    width = index.width
    height = index.height

screen = pygame.display.set_mode((width, height))

click_sound = pygame.mixer.Sound('click1.wav')

settings_button_var = settings_button()
settings_var = settings()
grass_block = grass()
snake = Snake()

screen.fill((175, 220, 70))
grass_block.draw()
join_settings = False

sound_mode = 'Play'

deafult_numbers = np.array([height//13, -(height//13)])
w_test = width//24.8
snake.add_block()
colck = pygame.time.Clock()

try:
    while True:
        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()  # Finish Work For pygame
                break

            if settings_button_var.pressed():
                if not join_settings and sound_mode == 'Play':
                    click_sound.play()
                if not join_settings:
                    join_settings = True
                screen.fill((149, 184, 68))
                settings_var.draw(sound_mode)
                pygame.display.update()

            pygame.display.update()

            if not join_settings:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP and snake.head_move_y != deafult_numbers[0]:
                        snake.start = True
                        snake.head_move_y = deafult_numbers[1]
                        snake.head_move_x = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                        if settings_button_var.pressed():
                            if not join_settings and sound_mode == 'Play':
                                click_sound.play()
                            if not join_settings:
                                join_settings = True
                            screen.fill((149, 184, 68))
                            settings_var.draw(sound_mode)
                            pygame.display.update()

                        pygame.display.update()
                    elif event.key == pygame.K_DOWN and snake.head_move_y != deafult_numbers[1]:
                        snake.start = True
                        snake.head_move_y = deafult_numbers[0]
                        snake.head_move_x = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                        if settings_button_var.pressed():
                            if not join_settings and sound_mode == 'Play':
                                click_sound.play()
                            if not join_settings:
                                join_settings = True
                            screen.fill((149, 184, 68))
                            settings_var.draw(sound_mode)
                            pygame.display.update()

                        pygame.display.update()
                    elif event.key == pygame.K_LEFT and snake.head_move_x != w_test and snake.start:
                        snake.start = True
                        snake.head_move_x = -(w_test)
                        snake.head_move_y = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                        if settings_button_var.pressed():
                            if not join_settings and sound_mode == 'Play':
                                click_sound.play()
                            if not join_settings:
                                join_settings = True
                            screen.fill((149, 184, 68))
                            settings_var.draw(sound_mode)
                            pygame.display.update()

                        pygame.display.update()
                    elif event.key == pygame.K_RIGHT and snake.head_move_x != -(w_test):
                        snake.start = True
                        snake.head_move_x = w_test
                        snake.head_move_y = 0
                        if not join_settings:
                            screen.fill((175, 220, 70))
                            grass_block.draw()
                            snake.draw()
                            settings_button_var.draw()
                            if settings_button_var.pressed():
                                if not join_settings and sound_mode == 'Play':
                                    click_sound.play()
                                if not join_settings:
                                    join_settings = True
                                screen.fill((149, 184, 68))
                                settings_var.draw(sound_mode)
                                pygame.display.update()

                        pygame.display.update()

        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()

        pygame.display.update()

        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()

        if not join_settings:
            screen.fill((175, 220, 70))
            grass_block.draw()
            snake.draw()
            settings_button_var.draw()

        pygame.display.update()

        if join_settings:
            if settings_var.pressed() == 'Quit':
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                pygame.quit()  # Finish Work For pygame
                break

            elif settings_var.pressed() == 'Resumption':
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                screen.fill((175, 220, 70))
                join_settings = False

                pygame.display.update()

            elif settings_var.pressed() == 'Replay':
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                snake.reset_snake()
                join_settings = False

                pygame.display.update()

            elif settings_var.pressed(sound_mode) == 'Mute' and sound_mode == 'Play':
                screen.fill((149, 184, 68))
                sound_mode = 'Mute'
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                settings_var.draw(sound_mode)
                pygame.display.update()
                pygame.time.delay(150)

            elif settings_var.pressed(sound_mode) == 'Play' and sound_mode == 'Mute':
                screen.fill((149, 184, 68))
                sound_mode = 'Play'
                if join_settings and sound_mode == 'Play':
                    click_sound.play()
                settings_var.draw(sound_mode)
                pygame.display.update()
                pygame.time.delay(150)

        if settings_button_var.pressed():
            if not join_settings and sound_mode == 'Play':
                click_sound.play()
            if not join_settings:
                join_settings = True
            screen.fill((149, 184, 68))
            settings_var.draw(sound_mode)
            pygame.display.update()

        pygame.display.update()

        colck.tick(100)

except:
    pass

i want add a function to add new block for a snake

======================================

======================================

if you see any problem in my code insert me

i don't why the block delete after start a moving


来源: stackexchange

问:
Running cmd.exe from Powershell and passing another exe application as a Parameter
Ok so I have been looking for an example on how to do the following but can't seems to find the correct answer. I have found a lot of things that are close but won't work. This code is being run from within a PowerShell script if matters or makes a difference.

Here is the code snip:

Start-Process -FilePath cmd.exe -ArgumentList /k "msdgen170.exe" -Wait -WindowStyle Maximized -Verb RunAs -WorkingDirectory "C:\Program Files (x86)\3E\msdgen"

It works as far starting the cmd window but I can't seem to get the msdgen170.exe application to be passed to the window. It opens and stops at a prompt. I have tried the & but that doesn't work either.

What am I missing?

Thanks for helping to point me in the correct direction.

ContentLicense: CC BY-SA 4.0


问:
Setting different font URL in CSS file for development and production (Webpack)
This is how I'm embedding the Nunito font in my Chrome Extension:

manifest.json:

```<code>// more code
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "css": ["style.css"],
        "js": ["content.js"]
    }
],
// more code
"web_accessible_resources": [
    {
        "resources": ["*.ttf"],
        "matches": ["<all_urls>"]
    }
]
</code>```

style.css:

```<code>@font-face {
    font-family: 'Nunito';
    font-style: normal;
    font-weight: 500;
    src: url('chrome-extension://__MSG_@@extension_id__/fonts/Nunito-Medium.ttf');
}
</code>```

The font is successfully embedded when I compile my extension and load it in Chrome. However, when I'm developing the extension in localhost, I get this error:

Failed to load resource: net::ERR_FAILED

I think this happens because localhost can't interpret chrome-extension://__MSG_@@extension_id__, so I have to change that path when I'm developing in localhost.

But as you can see up there, the path to the font is hard-coded in an CSS file (style.css). So I can't change the path. Is there any way around this?

Note: I'm using Webpack:

package.json:

```<code>"scripts": {
  "dev": "webpack --watch --config webpack.dev.js",
  "build": "webpack --config webpack.prod.js"
},
</code>```

Body:
This is how I'm embedding the Nunito font in my Chrome Extension:

manifest.json:

// more code
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "css": ["style.css"],
        "js": ["content.js"]
    }
],
// more code
"web_accessible_resources": [
    {
        "resources": ["*.ttf"],
        "matches": ["<all_urls>"]
    }
]

style.css:

@font-face {
    font-family: 'Nunito';
    font-style: normal;
    font-weight: 500;
    src: url('chrome-extension://__MSG_@@extension_id__/fonts/Nunito-Medium.ttf');
}

The font is successfully embedded when I compile my extension and load it in Chrome. However, when I'm developing the extension in localhost, I get this error:

Failed to load resource: net::ERR_FAILED

I think this happens because localhost can't interpret chrome-extension://__MSG_@@extension_id__, so I have to change that path when I'm developing in localhost.

But as you can see up there, the path to the font is hard-coded in an CSS file (style.css). So I can't change the path. Is there any way around this?

Note: I'm using Webpack:

package.json:

"scripts": {
  "dev": "webpack --watch --config webpack.dev.js",
  "build": "webpack --config webpack.prod.js"
},


问:
I have created Must use plugins which is not showing in wordpress dashboard
I am trying to display custom post types called Events and I have created mu-plugins folder and written code below.

```<code><?php

function post_types_events() {
    register_post_type('event', array(
        'public'     => true,
        'menu_icon'  => 'dashicons-calender',
        'labels'     => array(
            'name'   => 'Events',
            'add_new_item' => 'Add New Event',
            'edit_item'    => 'Edit Event',
            'all_items'    => 'All Events',
            'singular_name' => 'Event'
        )
    ));
}
add_action('init', 'post_types_events');

?>
</code>```

I can see in plugins section that I have must use plugins -1 but I am not able to see on left hand side of dashboard.

I have my code file inside mu-plugins folder. I can see there is must use plugins -1 but custom post type should be displaying on left hand side of admin dashboard but I cannot see.

Body:
I am trying to display custom post types called Events and I have created mu-plugins folder and written code below.

<?php

function post_types_events() {
    register_post_type('event', array(
        'public'     => true,
        'menu_icon'  => 'dashicons-calender',
        'labels'     => array(
            'name'   => 'Events',
            'add_new_item' => 'Add New Event',
            'edit_item'    => 'Edit Event',
            'all_items'    => 'All Events',
            'singular_name' => 'Event'
        )
    ));
}
add_action('init', 'post_types_events');

?>

I can see in plugins section that I have must use plugins -1 but I am not able to see on left hand side of dashboard.

I have my code file inside mu-plugins folder. I can see there is must use plugins -1 but custom post type should be displaying on left hand side of admin dashboard but I cannot see.


问:
Android Test Fails caused by a Resources$NotFoundException when trying to resolve String from within a Submodule Component
I created an android project with a submodule, which i would like to share between other android projects as well. this works quite well and i consume services, components etc. from this submodule in my rootproject. The App works well and as intended.

I am really concerned to write some ui-tests and stumbled over that problem. that is, if i setup a component-test for testing a view, composeable etc. which uses one composable from this submodule holding the R.string.id to a stringresource within this module, the test fails caused by, which was thrown in the submodule

Handling an uncaught exception thrown on the thread main. 01-11 14:56:45.357  3145  3145 D MonitoringInstr: android.content.res.Resources$NotFoundException: String resource ID #0x7f0f001c 01-11 14:56:45.357  3145  3145 D MonitoringInstr:  at android.content.res.Resources.getText(Resources.java:367) 01-11 14:56:45.357  3145  3145 D MonitoringInstr:  at android.content.res.Resources.getString(Resources.java:460) 01-11 14:56:45.357  3145  3145 D MonitoringInstr:    at androidx.compose.ui.res.StringResources_androidKt.stringResource(StringResources.android.kt:36)

here is the test

```<code>class StringResourceTest {

    @get:Rule val ctr: ComposeContentTestRule = createComposeRule()

    ...

    @Test
    fun composeableTest() {
        val context: Context = InstrumentationRegistry.getInstrumentation().targetContext

        val hello_world = context.resources.getString(com.root.project.R.string.hello_world)
        assertEquals("hello world", hello_world)

        var hello_world_again = ""

        ctr.setContent {
            hello_world_again = stringResource(id = com.submodule.string.hello_world)

            Text(text = hello_world_again)

            HelloWorldComposable()
        }

        assertEquals("hello world", hello_world_again)
        ctr.onNodeWithText(hello_world).assertExists()
    }
}
</code>```

the composeable under test:

```<code>package com.submodule.ui

import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.submodule.R

@Composable
fun HelloWorldComposable() {

    Text(stringResource(R.string.hello_world)) // here the exception gets thrown

}
</code>```

tried to copy strings.xml resources-file from the submodule to the rootmodule
etc.

Body:
I created an android project with a submodule, which i would like to share between other android projects as well. this works quite well and i consume services, components etc. from this submodule in my rootproject. The App works well and as intended.

I am really concerned to write some ui-tests and stumbled over that problem. that is, if i setup a component-test for testing a view, composeable etc. which uses one composable from this submodule holding the R.string.id to a stringresource within this module, the test fails caused by, which was thrown in the submodule

Handling an uncaught exception thrown on the thread main. 01-11 14:56:45.357  3145  3145 D MonitoringInstr: android.content.res.Resources$NotFoundException: String resource ID #0x7f0f001c 01-11 14:56:45.357  3145  3145 D MonitoringInstr:  at android.content.res.Resources.getText(Resources.java:367) 01-11 14:56:45.357  3145  3145 D MonitoringInstr:  at android.content.res.Resources.getString(Resources.java:460) 01-11 14:56:45.357  3145  3145 D MonitoringInstr:    at androidx.compose.ui.res.StringResources_androidKt.stringResource(StringResources.android.kt:36)

here is the test

class StringResourceTest {

    @get:Rule val ctr: ComposeContentTestRule = createComposeRule()

    ...

    @Test
    fun composeableTest() {
        val context: Context = InstrumentationRegistry.getInstrumentation().targetContext

        val hello_world = context.resources.getString(com.root.project.R.string.hello_world)
        assertEquals("hello world", hello_world)

        var hello_world_again = ""

        ctr.setContent {
            hello_world_again = stringResource(id = com.submodule.string.hello_world)

            Text(text = hello_world_again)

            HelloWorldComposable()
        }

        assertEquals("hello world", hello_world_again)
        ctr.onNodeWithText(hello_world).assertExists()
    }
}

the composeable under test:

package com.submodule.ui

import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.submodule.R

@Composable
fun HelloWorldComposable() {

    Text(stringResource(R.string.hello_world)) // here the exception gets thrown

}

tried to copy strings.xml resources-file from the submodule to the rootmodule
etc.


问:
Paste properly in contenteditable html table
I am having html table with conteneditable. Now when I am pasting data into HTML table then table creates rows instead of columns. Please take a look at my code. I am not able to get what javascript I should use to complete the task.

    11
    22
    33

    44
    55
    66

```

The table is looking something like this when I am pasting 3 column and 4 rows data from excel sheet into HTML table.

Body:
I am having html table with conteneditable. Now when I am pasting data into HTML table then table creates rows instead of columns. Please take a look at my code. I am not able to get what javascript I should use to complete the task.

    11
    22
    33

    44
    55
    66

The table is looking something like this when I am pasting 3 column and 4 rows data from excel sheet into HTML table.


问:
Getting NOT IN subset with SQL
I have a SQL/Postgres database where I keep the application data, including references to user-generated content persisted in object storage - image files. Every now and then, these user-generated files get overwritten or deleted. I would like to add garbage collection to clean up the unused storage.

My plan is:

get a list of files from the object store.

randomly select a subset of maybe 100 files at a time.

use FaaS to run something like the below query every few minutes:

```<code>    SELECT
      *
    FROM
      events e, categories c
    WHERE
      e.image <> ANY($1) AND
      e.cropped_image <> ANY($1) AND
      e.cropped_image_thumb <> ANY($1) AND
      e.promoted_img <> ANY($1) AND
      c.header_image <> ANY($1) AND
      c.list_image <> ANY($1)
</code>```

Only, the query is working "backwards" - incorrectly. My version will return a list database records not containing the images. I want a list of images no longer referenced in the database.

Can I somehow join on the array $1 and get elements not matching anything?

Title: Getting NOT IN subset with SQL

Body:
I have a SQL/Postgres database where I keep the application data, including references to user-generated content persisted in object storage - image files. Every now and then, these user-generated files get overwritten or deleted. I would like to add garbage collection to clean up the unused storage.

My plan is:

get a list of files from the object store.

randomly select a subset of maybe 100 files at a time.

use FaaS to run something like the below query every few minutes:

    SELECT
      *
    FROM
      events e, categories c
    WHERE
      e.image <> ANY($1) AND
      e.cropped_image <> ANY($1) AND
      e.cropped_image_thumb <> ANY($1) AND
      e.promoted_img <> ANY($1) AND
      c.header_image <> ANY($1) AND
      c.list_image <> ANY($1)

Only, the query is working "backwards" - incorrectly. My version will return a list database records not containing the images. I want a list of images no longer referenced in the database.

Can I somehow join on the array $1 and get elements not matching anything?


问:
Instantiate Template via OC cli - Openshift 4
Instantiate Template from openshift UI seems very straight forward but while creating custom templates & Instantiate Template from OC cli with below steps is not working:-

oc login

oc create -f testtemplate.json

oc get templates

oc process --parameters -n 23002 builder27 --> This command is not showing successfully created template & openshift UI showed this template was created

Below is the error while doing last command -

Need some clue if approach is right & this is permission issue with the user.


问:
change the order of labels in sklearn logistic regression
I'm training a multinomial logistic regression model with scikit learn. This model is used to classify sentences by sentiment.
The labels for the outputs are: "NEG", "NEU", "POS". The problem is that when the model assigns the default value to a sentence (either because it doesn't know the words or because the sentence is empty), I get "NEG" instead of "NEU". I assume that's because the LogisticRegression() class sorts the labels in alphabetical order).

```<code>{'': ['NEG', array([[0.333, 0.333, 0.333]])]}
</code>```

Of course I could change the label names and do some post-processing, but it should be a better way to make "NEU" the first label.

Body:
I'm training a multinomial logistic regression model with scikit learn. This model is used to classify sentences by sentiment.
The labels for the outputs are: "NEG", "NEU", "POS". The problem is that when the model assigns the default value to a sentence (either because it doesn't know the words or because the sentence is empty), I get "NEG" instead of "NEU". I assume that's because the LogisticRegression() class sorts the labels in alphabetical order).

{'': ['NEG', array([[0.333, 0.333, 0.333]])]}

Of course I could change the label names and do some post-processing, but it should be a better way to make "NEU" the first label.


问:
How to get logs from a lambda trigger in AWS Lambda?
Some time ago, I developed a lambda function, this function has s3 bucket as trigger. The event type is s3:ObjectCreated:* and the suffix is .csv. Everything was working fine.

For a few days I see that when I upload a csv the trigger no longer works. Nothing was changed, which is why I want to see the logs for a lambda trigger.

It's possible?
I need to see why the lambda trigger is not working, I don't know if there are any logs or error messages from the lambda triggers.

I was reading a lot of literature and I can't find something like what I need. Cloudwatch only shows logs for lambdas and obviously if a lambda doesn't start then no logs are logged and I can't see why the trigger didn't start.


问:
InternalOAuthError: Failed to obtain access token? - NodeJS Passport
I've been trying all day but I couldn't solve it.
The problem is as follows;
I made an oauth2 system for my own website. But it gives me the error in the title.

I guess it doesn't detect the callback coming from the server side?

```<code>res.redirect('http://localhost:2000/callback?code=' + response.data.accessToken);
//Example => http://localhost:2000/callback?code=97a1438b602c76a680297426306785ec9ef49f43
</code>```

The piece of code where I got the error;

```<code>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let token = 'http://localhost:3000/oauth/token';
let authorization = 'http://localhost:3000/login';
let temproraydata = {};

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var passport = require('passport');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

passport.use(new OAuth2Strategy({
    authorizationURL: authorization,
    tokenURL: token,
    clientID: 'application',
    clientSecret: 'secret',
    callbackURL: "http://localhost:2000/callback",
    passReqToCallback: true
},
    function (accessToken, refreshToken, profile, done) {
        console.log(accessToken);
        console.log(refreshToken);
        temproraydata = profile;
        return done(null, profile);
    }
));

app.get('/provider', passport.authenticate('oauth2', { session: false }));
app.get('/callback',
    passport.authenticate('oauth2', {
        successRedirect: '/',
        failureRedirect: '/login'
    }));

app.listen(2000, function () {
    console.log("Listening on port 2000");
});
</code>```

this is error;
images

I've been working on it all day. I have done oauth server side but I am having problems on user side. I can't figure it out, I'm waiting for your help.

Body:
I've been trying all day but I couldn't solve it.
The problem is as follows;
I made an oauth2 system for my own website. But it gives me the error in the title.

I guess it doesn't detect the callback coming from the server side?

res.redirect('http://localhost:2000/callback?code=' + response.data.accessToken);
//Example => http://localhost:2000/callback?code=97a1438b602c76a680297426306785ec9ef49f43

The piece of code where I got the error;

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let token = 'http://localhost:3000/oauth/token';
let authorization = 'http://localhost:3000/login';
let temproraydata = {};

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var passport = require('passport');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

passport.use(new OAuth2Strategy({
    authorizationURL: authorization,
    tokenURL: token,
    clientID: 'application',
    clientSecret: 'secret',
    callbackURL: "http://localhost:2000/callback",
    passReqToCallback: true
},
    function (accessToken, refreshToken, profile, done) {
        console.log(accessToken);
        console.log(refreshToken);
        temproraydata = profile;
        return done(null, profile);
    }
));

app.get('/provider', passport.authenticate('oauth2', { session: false }));
app.get('/callback',
    passport.authenticate('oauth2', {
        successRedirect: '/',
        failureRedirect: '/login'
    }));

app.listen(2000, function () {
    console.log("Listening on port 2000");
});

this is error;
images

I've been working on it all day. I have done oauth server side but I am having problems on user side. I can't figure it out, I'm waiting for your help.


问:
IronPython 2.7 Errors when installing pyyaml
I have IronPython 2.7.11 and am trying to install pyyaml to it and am getting errors. Here is a snippet of the errors I get from the command prompt.  The program I have uses IronPython to build a TwinCAT package and has worked in the past.  The original programmer is no longer available so I am taking this over.

```<code>C:\>ipy -X:Frames -m pip install pyyaml
DEPRECATION: A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting pyyaml
ERROR: Exception:
Traceback (most recent call last):
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
    status = self.run(options, args)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\commands\install.py", line 345, in run
    resolver.resolve(requirement_set)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\legacy_resolve.py", line 195, in resolve
    discovered_reqs.extend(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\legacy_resolve.py", line 359, in _resolve_one
    abstract_dist = self._get_abstract_dist_for(req_to_install)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\legacy_resolve.py", line 305, in _get_abstract_dist_for
    abstract_dist = self.preparer.prepare_linked_requirement(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\operations\prepare.py", line 134, in prepare_linked_requirement
    req.populate_link(finder, upgrade_allowed, require_hashes)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\req\req_install.py", line 211, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1200, in find_requirement
    candidates = self.find_candidates(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1183, in find_candidates
    candidates = self.find_all_candidates(project_name)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1131, in find_all_candidates
    page_versions.extend(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1339, in _package_versions
    for link in self._sort_links(links):
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1296, in _sort_links
    for link in links:
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1494, in iter_links
    document = html5lib.parse(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 47, in parse
    return p.parse(doc, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 289, in parse
    self._parse(stream, False, None, *args, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 130, in _parse
    self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_tokenizer.py", line 36, in __init__
    self.stream = HTMLInputStream(stream, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 151, in HTMLInputStream
    return HTMLBinaryInputStream(source, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 428, in __init__
    self.charEncoding = self.determineEncoding(useChardet)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 475, in determineEncoding
    charEncoding = self.detectEncodingMeta(), "tentative"
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 576, in detectEncodingMeta
    encoding = parser.getEncoding()
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 707, in getEncoding
    if self.data.matchBytes(key):
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 668, in matchBytes
    data = self[p:p + len(bytes)]
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
</code>```

Install IronPython 2.7.11 and in Command Prompt, run

```<code>ipy -X:Frames -m pip install pyyaml
</code>```

Body:
I have IronPython 2.7.11 and am trying to install pyyaml to it and am getting errors. Here is a snippet of the errors I get from the command prompt.  The program I have uses IronPython to build a TwinCAT package and has worked in the past.  The original programmer is no longer available so I am taking this over.

C:\>ipy -X:Frames -m pip install pyyaml
DEPRECATION: A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting pyyaml
ERROR: Exception:
Traceback (most recent call last):
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
    status = self.run(options, args)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\commands\install.py", line 345, in run
    resolver.resolve(requirement_set)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\legacy_resolve.py", line 195, in resolve
    discovered_reqs.extend(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\legacy_resolve.py", line 359, in _resolve_one
    abstract_dist = self._get_abstract_dist_for(req_to_install)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\legacy_resolve.py", line 305, in _get_abstract_dist_for
    abstract_dist = self.preparer.prepare_linked_requirement(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\operations\prepare.py", line 134, in prepare_linked_requirement
    req.populate_link(finder, upgrade_allowed, require_hashes)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\req\req_install.py", line 211, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1200, in find_requirement
    candidates = self.find_candidates(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1183, in find_candidates
    candidates = self.find_all_candidates(project_name)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1131, in find_all_candidates
    page_versions.extend(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1339, in _package_versions
    for link in self._sort_links(links):
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1296, in _sort_links
    for link in links:
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_internal\index.py", line 1494, in iter_links
    document = html5lib.parse(
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 47, in parse
    return p.parse(doc, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 289, in parse
    self._parse(stream, False, None, *args, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 130, in _parse
    self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_tokenizer.py", line 36, in __init__
    self.stream = HTMLInputStream(stream, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 151, in HTMLInputStream
    return HTMLBinaryInputStream(source, **kwargs)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 428, in __init__
    self.charEncoding = self.determineEncoding(useChardet)
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 475, in determineEncoding
    charEncoding = self.detectEncodingMeta(), "tentative"
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 576, in detectEncodingMeta
    encoding = parser.getEncoding()
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 707, in getEncoding
    if self.data.matchBytes(key):
  File "C:\Program Files\IronPython 2.7\Lib\site-packages\pip\_vendor\html5lib\_inputstream.py", line 668, in matchBytes
    data = self[p:p + len(bytes)]
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Install IronPython 2.7.11 and in Command Prompt, run

ipy -X:Frames -m pip install pyyaml


问:
Graceful fail with cmake
I have a cmake that compiles various things: some C libraries, some C programs and some higher level SWIG bindings in C for JNI.

How do I do the equivalement of the following pseudocode in my CMakeLists.txt ?

```<code>Compile the C targets
if JDK and SWIG are present find_package(SWIG REQUIRED COMPONENTS java), and cmake_minimum_required(VERSION 3.11)
  -> compile the Swig targets
else
  -> message("Missing JDK")
endif
</code>```

Title: Graceful fail with cmake

Body:
I have a cmake that compiles various things: some C libraries, some C programs and some higher level SWIG bindings in C for JNI.

How do I do the equivalement of the following pseudocode in my CMakeLists.txt ?

Compile the C targets
if JDK and SWIG are present find_package(SWIG REQUIRED COMPONENTS java), and cmake_minimum_required(VERSION 3.11)
  -> compile the Swig targets
else
  -> message("Missing JDK")
endif


问:
Is using SSIS in Visual Studio (Community Version) not leading to any data breach?
I am beginner in SQL, have downloaded Visual Studio(Community Version) to use SSIS. I work in an enterprise having more than 200 HCs, and planning to use Visual Studio(Community Version) for data analytics in office.

I have a question - is it okay to use VS community version of visual studio for official purpose? If not, what is the consequence?

Another question I have - Does VS community version have robust control, and not risk of data breach?

Thank you
Shubham

I have looked at some of answers available, but it is for individual developer.

I think it is a open source application, and I would be using it for ETL only, not for any development work, so it should be fine.


问:
How to specify n tiles that span min to max values using ggplot2::stat_sumary2d() when values cross zero
Is there a way to specify the number of bins, as well as start and end values when using ggplot2::stat_summary_2d() tiles? You'd think you could just set the number of bins or set the binwidth values to (max-min)/n for both x and y, but this doesn't work when values cross zero. I must be missing something but it seems tiles must start/end at zero when values cross zero.

```<code>library(tidyverse)

set.seed(100)
dat<-data.frame(y=sample(c(-200:4000),1000, replace=TRUE),x=sample(c(0:100),1000, replace=TRUE),z=rnorm(1000))

#get bin widths
dat%>%gather(Variable,Value,everything())%>%
  group_by(Variable)%>%
  summarise(min=min(Value),max=max(Value), int=(max-min)/10)%>%{.->>check}%>%
  filter(Variable %in% c("x","y"))%>%
  pull(int)%>%{.->>bw}
print(check)
print(bw)

p1<-dat%>%
  ggplot(.,aes(x=x,y=y,z=z))+
  stat_summary_2d(binwidth=bw,geom = "tile",fun="mean",na.rm = TRUE)
win.graph()
p1#11x10 bins

p2<-dat%>%
  ggplot(.,aes(x=x,y=y,z=z))+
  stat_summary_2d(bins=10,geom = "tile",fun="mean",na.rm = TRUE)
win.graph()
p2#11x10 bins
</code>```

Body:
Is there a way to specify the number of bins, as well as start and end values when using ggplot2::stat_summary_2d() tiles? You'd think you could just set the number of bins or set the binwidth values to (max-min)/n for both x and y, but this doesn't work when values cross zero. I must be missing something but it seems tiles must start/end at zero when values cross zero.

library(tidyverse)

set.seed(100)
dat<-data.frame(y=sample(c(-200:4000),1000, replace=TRUE),x=sample(c(0:100),1000, replace=TRUE),z=rnorm(1000))

#get bin widths
dat%>%gather(Variable,Value,everything())%>%
  group_by(Variable)%>%
  summarise(min=min(Value),max=max(Value), int=(max-min)/10)%>%{.->>check}%>%
  filter(Variable %in% c("x","y"))%>%
  pull(int)%>%{.->>bw}
print(check)
print(bw)

p1<-dat%>%
  ggplot(.,aes(x=x,y=y,z=z))+
  stat_summary_2d(binwidth=bw,geom = "tile",fun="mean",na.rm = TRUE)
win.graph()
p1#11x10 bins

p2<-dat%>%
  ggplot(.,aes(x=x,y=y,z=z))+
  stat_summary_2d(bins=10,geom = "tile",fun="mean",na.rm = TRUE)
win.graph()
p2#11x10 bins


问:
How can I pass a reference to an array field to a child component, so I can connect it with an input field through two-way binding?
I'm currently implementing a form with an undo-function in Angular and I can't figure out how to connect the @Input values of the child component to fields of an array in a seperate 'dataService'. Initially I just implemented the whole form in one component with Angular's FormGroup class which worked fine. Whenever I pressed the undo button the array would be set to a previous state and the changes would be reflected in the input fields. I then decided it would be cleaner and more future proof to move the inputs to a seperate child component, so I could customize them better. The problem is now, that the array field that I pass as an Input to the child component is always passed as a primitive string and looses its connection to the actual array. How can I pass it in a way that I can connect it to the inputs value via two-way data binding so the changes in the input get reflected in the array and vice versa?

The code looks like the following:

Parent template:

```<code>...
<input-field id="name" name="name" [(value)]="dataService.projectData.info.projectDetails.name"></input-field>
...
</code>```

Child component:

```<code>...
export class InputFieldComponent implements OnInit {

  @Input() value: any;
  @Output() valueChange: EventEmitter<any> = new EventEmitter<any>();
  @Input() id: string;
  @Input() name: string;
  @Input() class: string;
...
  onBlur() {
    this.valueChange.emit(this.value);
  }
</code>```

Child template:

```<code>...
<input [(ngModel)]="value" (blur)="onBlur()" type="text" id="{{id}}" class="{{class}}">
...
</code>```

The way it behaves right now is that the default string value from the array is passed to the child component and displayed in the input field. When I type something in the input only the 'value' attribute inside the child component is being changed (probably because it's not bound to the actual array). The content in the array stays the same and the undo function doesn't work.

The way I would want it is that once the input field looses focus (onBlur) the value in the array is updated and once I click on 'undo' the changes in the array get reflected in the input field.

Thanks in advance for any suggestions!

Angular version: 14.0.7

Body:
I'm currently implementing a form with an undo-function in Angular and I can't figure out how to connect the @Input values of the child component to fields of an array in a seperate 'dataService'. Initially I just implemented the whole form in one component with Angular's FormGroup class which worked fine. Whenever I pressed the undo button the array would be set to a previous state and the changes would be reflected in the input fields. I then decided it would be cleaner and more future proof to move the inputs to a seperate child component, so I could customize them better. The problem is now, that the array field that I pass as an Input to the child component is always passed as a primitive string and looses its connection to the actual array. How can I pass it in a way that I can connect it to the inputs value via two-way data binding so the changes in the input get reflected in the array and vice versa?

The code looks like the following:

Parent template:

...
<input-field id="name" name="name" [(value)]="dataService.projectData.info.projectDetails.name"></input-field>
...

Child component:

...
export class InputFieldComponent implements OnInit {

  @Input() value: any;
  @Output() valueChange: EventEmitter<any> = new EventEmitter<any>();
  @Input() id: string;
  @Input() name: string;
  @Input() class: string;
...
  onBlur() {
    this.valueChange.emit(this.value);
  }

Child template:

...
<input [(ngModel)]="value" (blur)="onBlur()" type="text" id="{{id}}" class="{{class}}">
...

The way it behaves right now is that the default string value from the array is passed to the child component and displayed in the input field. When I type something in the input only the 'value' attribute inside the child component is being changed (probably because it's not bound to the actual array). The content in the array stays the same and the undo function doesn't work.

The way I would want it is that once the input field looses focus (onBlur) the value in the array is updated and once I click on 'undo' the changes in the array get reflected in the input field.

Thanks in advance for any suggestions!

Angular version: 14.0.7


问:
Django - how to remove INFO logs of "channels" package
I recently started using the channels package in Django (versions: channels==3.0.4 and channels-redis==3.3.1)

The application is sending massive amount of unwanted logs for each request i make to Django. log for example:

```<code>{"time": "2023-01-11 16:12:09 UTC", "msg": "HTTP %(method)s %(path)s %(status)s [%(time_taken).2f, %(client)s]", "logger": "edison", "level": "INFO", "log_trace": "/Volumes/dev/venv3.8/lib/python3.8/site-packages/channels/management/commands/runserver.py"}
</code>```

the log seems exactly the same no matter what request i send.

I tried to set the channels logging level to ERROR using logging.getLogger('channels').setLevel(logging.ERROR) just like i do with other packages but it doesn't help

any ideas what I need to do to remove those logs?

Body:
I recently started using the channels package in Django (versions: channels==3.0.4 and channels-redis==3.3.1)

The application is sending massive amount of unwanted logs for each request i make to Django. log for example:

{"time": "2023-01-11 16:12:09 UTC", "msg": "HTTP %(method)s %(path)s %(status)s [%(time_taken).2f, %(client)s]", "logger": "edison", "level": "INFO", "log_trace": "/Volumes/dev/venv3.8/lib/python3.8/site-packages/channels/management/commands/runserver.py"}

the log seems exactly the same no matter what request i send.

I tried to set the channels logging level to ERROR using logging.getLogger('channels').setLevel(logging.ERROR) just like i do with other packages but it doesn't help

any ideas what I need to do to remove those logs?


问:
Problem with gunicorn and nginx while deploying django project to digitalocean
I am trying to host a django project using digitalocean on a domain. While the project is visible in the ip address, it does not work with the domain. These are the exact steps I tried. Can you please help sort this issue. Thank you.

sudo apt update

sudo apt install python3-pip python3-dev nginx

sudo pip3 install virtualenv

mkdir ~/projectdir and cd~/projectdir

source env/bin/activate

pip install django gunicorn

django-admin startproject test_project ~/projectdir

~/projectdir/manage.py makemigrations

~/projectdir/manage.py migrate

sudo ufw allow 8000

sudo fuser -k 8000/tcp

gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/MY_USER_NAME/projectdir/test_project test_project.wsgi

deactivate

sudo vim /etc/systemcd/system/gunicorn.socket

Pasted the following content by using vim:

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

sudo vim /etc/systemd/system/gunicorn.service

Pasted the following content through vim:

```<code>[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=MY_USER_NAME
Group=www-data
WorkingDirectory=/home/MY_USER_NAME/projectdir
ExecStart=/home/MY_USER_NAME/projectdir/env/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          test_project.wsgi:application

[Install]
WantedBy=multi-user.target
</code>```

sudo systemctl start gunicorn.socket

sudo systemctl enable gunicorn.socket

sudo vim /etc/nginx/sites-available/test_project/

Pasted the following content using vim:

```<code>server {
     listen 80;
     server_name IP_ADDRESS www.MY_DOMAIN  MY_DOMAIN;
     location = /favicon.ico { access_log off; log_not_found off; }
     location /static/ {
         root /home/MY_USER_NAME/projectdir;
     }
     location / {
         include proxy_params;
         proxy_pass http://unix:/run/gunicorn.sock;
     }
}
</code>```

sudo ln -s /etc/nginx/sites-available/test_project /etc/nginx/sites-enabled/

sudo systemctl restart nginx

I tried debugging the issue by running sudo systemctl status gunicorn. I get the following message:

```<code>× gunicorn.service - gunicorn daemon
     Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset:>
     Active: failed (Result: exit-code) since Wed 2023-01-11 15:57:45 UTC; 10min ago
TriggeredBy: × gunicorn.socket
    Process: 22861 ExecStart=/home/odin/projectdir/env/bin/gunicorn --access-logfil>
   Main PID: 22861 (code=exited, status=1/FAILURE)
        CPU: 272ms

gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
gunicorn.service: Main process exited, code=exited, status=1/FAILURE
Failed to start gunicorn daemon.
</code>```

Here is the project structure:

```<code>home/
  USER_NAME/
    projectdir/
      env/
      test_project/
        test_project/
          wsgi.py/
</code>```

Body:
I am trying to host a django project using digitalocean on a domain. While the project is visible in the ip address, it does not work with the domain. These are the exact steps I tried. Can you please help sort this issue. Thank you.

sudo apt update

sudo apt install python3-pip python3-dev nginx

sudo pip3 install virtualenv

mkdir ~/projectdir and cd~/projectdir

source env/bin/activate

pip install django gunicorn

django-admin startproject test_project ~/projectdir

~/projectdir/manage.py makemigrations

~/projectdir/manage.py migrate

sudo ufw allow 8000

sudo fuser -k 8000/tcp

gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/MY_USER_NAME/projectdir/test_project test_project.wsgi

deactivate

sudo vim /etc/systemcd/system/gunicorn.socket

Pasted the following content by using vim:

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

sudo vim /etc/systemd/system/gunicorn.service

Pasted the following content through vim:

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=MY_USER_NAME
Group=www-data
WorkingDirectory=/home/MY_USER_NAME/projectdir
ExecStart=/home/MY_USER_NAME/projectdir/env/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          test_project.wsgi:application

[Install]
WantedBy=multi-user.target

sudo systemctl start gunicorn.socket

sudo systemctl enable gunicorn.socket

sudo vim /etc/nginx/sites-available/test_project/

Pasted the following content using vim:

server {
     listen 80;
     server_name IP_ADDRESS www.MY_DOMAIN  MY_DOMAIN;
     location = /favicon.ico { access_log off; log_not_found off; }
     location /static/ {
         root /home/MY_USER_NAME/projectdir;
     }
     location / {
         include proxy_params;
         proxy_pass http://unix:/run/gunicorn.sock;
     }
}

sudo ln -s /etc/nginx/sites-available/test_project /etc/nginx/sites-enabled/

sudo systemctl restart nginx

I tried debugging the issue by running sudo systemctl status gunicorn. I get the following message:

× gunicorn.service - gunicorn daemon
     Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset:>
     Active: failed (Result: exit-code) since Wed 2023-01-11 15:57:45 UTC; 10min ago
TriggeredBy: × gunicorn.socket
    Process: 22861 ExecStart=/home/odin/projectdir/env/bin/gunicorn --access-logfil>
   Main PID: 22861 (code=exited, status=1/FAILURE)
        CPU: 272ms

gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
gunicorn.service: Main process exited, code=exited, status=1/FAILURE
Failed to start gunicorn daemon.

Here is the project structure:

home/
  USER_NAME/
    projectdir/
      env/
      test_project/
        test_project/
          wsgi.py/


问:
Failing to read data from firebase firestore using next.js getStaticProps
I am trying to read data from firebase using nextjs but I get back an empty page. Even when I console log, nothing gets returned. This is how my code looks like

```<code>import React, {useState} from 'react'
import { db } from '../firebase'
import { collection, getDocs } from "firebase/firestore";

const reference = collection(db, "students");

function Card(props) {
    const { studentsData } = props

    return (
    <div>
        <p>This is just a test</p>
        {studentsData && studentsData.map(students => (
            <p>{students.name}</p>
        ))}
    </div>
  )
}
export const getStaticProps = async () => {
    const students = await getDocs(reference);
    const studentsData = students.docs.map(doc => ({id: doc.id, ...doc.data() }))
    console.log(studentsData);

    return {
        props: { studentsData }
    }
}
export default Card
</code>```

All I get back from this is just an empty page. Where could I be going wrong?.

Body:
I am trying to read data from firebase using nextjs but I get back an empty page. Even when I console log, nothing gets returned. This is how my code looks like

import React, {useState} from 'react'
import { db } from '../firebase'
import { collection, getDocs } from "firebase/firestore";

const reference = collection(db, "students");

function Card(props) {
    const { studentsData } = props

    return (

This is just a test

        {studentsData && studentsData.map(students => (

{students.name}

        ))}

  )
}
export const getStaticProps = async () => {
    const students = await getDocs(reference);
    const studentsData = students.docs.map(doc => ({id: doc.id, ...doc.data() }))
    console.log(studentsData);

    return {
        props: { studentsData }
    }
}
export default Card

All I get back from this is just an empty page. Where could I be going wrong?.


问:
How can I use Graphics.Dispose / Using Statements
I'm trying to improve the performance of my Winform application, and I found that I wasn't disposing graphics objects and instead relying on garbage collection, how can I implement the Graphics.Dispose method into my paint event?

```<code>public void Form1_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.DrawImage(bigImage, scrollX, scrollY);
   e.Graphics.DrawImage(smallImage, peanutHitboxX, peanutHitboxY);
}
</code>```

The image bigImage is an image bigger than the screen, and constantly moving. I want to dispose the graphics from it but when I change the code to this:

```<code>public void Form1_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.DrawImage(bigImage, scrollX, scrollY);
   e.Graphics.Dispose();
   e.Graphics.DrawImage(smallImage, peanutHitboxX, peanutHitboxY);
}
</code>```

It says that smallImage isn't valid, and moving e.Graphics.Dispose(); to the bottom returns an error in an entirely different file used by winforms

How do I just dispose bigImage without messing up things with smallImage?

Body:
I'm trying to improve the performance of my Winform application, and I found that I wasn't disposing graphics objects and instead relying on garbage collection, how can I implement the Graphics.Dispose method into my paint event?

public void Form1_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.DrawImage(bigImage, scrollX, scrollY);
   e.Graphics.DrawImage(smallImage, peanutHitboxX, peanutHitboxY);
}

The image bigImage is an image bigger than the screen, and constantly moving. I want to dispose the graphics from it but when I change the code to this:

public void Form1_Paint(object sender, PaintEventArgs e)
{
   e.Graphics.DrawImage(bigImage, scrollX, scrollY);
   e.Graphics.Dispose();
   e.Graphics.DrawImage(smallImage, peanutHitboxX, peanutHitboxY);
}

It says that smallImage isn't valid, and moving e.Graphics.Dispose(); to the bottom returns an error in an entirely different file used by winforms

How do I just dispose bigImage without messing up things with smallImage?


问:
Why is requests-html not returning the element for kahoot.it?
I'm trying to create a kahoot bot with requests-html. When I search for the game-pin element via identifier ('#game-pin'), it returns as "[]". From what I can tell, the page is loaded dynamically via Javascript. Supposedly, r.html.render should allow me to grab the elements but it responds the same with "[]"

I expected it to return an element but it still returned blank.

This is my code:

```<code>import requests-html

session = requests-html.HTMLSession()

r = session.get('https://kahoot.it/')

#this might take awhile the first time ran
r.html.render()

elem = r.html.find('#game-input')

print(elem)
</code>```

Body:
I'm trying to create a kahoot bot with requests-html. When I search for the game-pin element via identifier ('#game-pin'), it returns as "[]". From what I can tell, the page is loaded dynamically via Javascript. Supposedly, r.html.render should allow me to grab the elements but it responds the same with "[]"

I expected it to return an element but it still returned blank.

This is my code:

import requests-html

session = requests-html.HTMLSession()

r = session.get('https://kahoot.it/')

#this might take awhile the first time ran
r.html.render()

elem = r.html.find('#game-input')

print(elem)


问:
Is it better to have plugins loaded at runtime or direct code integration?
I'm in the process of making an app which I was hoping could have optional modules/plugins depending on what the user needs. Concretely, the host application would be lightweight (mostly a text/markdown editor) and I'd add the ability to use plugins. However, some plugins could be fairly heavy (for example a 3D viewer).

Would it be better to have plugins loaded at runtime at the cost of performance or to directly integrate those with the main code with an ability to turn them off at the cost of space? Ideally I'd want both high performance and low volume, but if I had to pick one I'd choose performance.

Feel free to suggest alternatives! I'm not too familiar with modular programming :)


问:
Kendo UI scheduler popUp customize
AngularJs

I want to remove some fields and add my custom fields in the kendo scheduler pop.

In the above snippet, I want to customize all the fields that appear after a repeat

Title: Kendo UI scheduler popUp customize


问:
Jest testing - challenges rending component which is using styled-components
Very new to JEST, REACT, ES6, etc.

I have been tasked with creating Jest tests for an existing code base before the team starts modifying and enhancing the application.

```<code>import styled from "styled-components/macro";
import { ViewHeader, ViewText } from "../../components/ViewStyle/ViewStyle";

export const Content = styled.div`
  align-self: center;
  justify-content: center;
  font-family: Fjalla One;
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 3rem;
`;

export const TextDiv = styled.div`
  p {
    margin-top: 0.5rem;
    max-width: 600px;
  }
`;

export default function SimplePage(
  props: Record<string, any>
): JSX.Element {
  const config = props.viewData?.config;
  return (

        <Content>
          <TextDiv>
            <ViewHeader titleColor={config?.textColor}>
              {props?.viewData.title}
            </ViewHeader>
            <ViewText textColor={config?.textColor}>
              {config?.description}
            </ViewText>
          </TextDiv>
          </Content>
  );
}
</code>```

<ViewHeader> is a simple component which is handling the text color.

```<code>import styled from "styled-components/macro";

interface HeaderProp {
  titleColor: string;
}

export const ViewHeader = styled.h2<HeaderProp>`
  color: ${({ titleColor }) => titleColor};
`;
</code>```

Instead of testing SimplePage.tsx I am singling out the ViewHeader component. Once I have a GREEN test, I will create testing for the ViewText component.

Here I render the ViewHeader with textColor = red, and I expect it to have a style rule if color = red but instead I am getting a TS error.

```<code>import renderer from "react-test-renderer";
import "jest-styled-components";
import { ViewHeader } from "../ViewStyle";

test("it works", () => {
  const textColor = "red";
  const tree = renderer.create(<ViewHeader textColor={textColor} />).toJSON();
  expect(tree).toHaveStyleRule("color", "red");
});
</code>```

Jest (features-web)

Test run started at 1/11/2023, 10:04:59 AM <

FAIL   Features-Web  src/components/ViewStyle/test/ViewStyle.test.tsx
Test suite failed to run

src/components/ViewStyle/test/ViewStyle.test.tsx:7:44 - error TS2769: No overload matches this call.
Overload 1 of 2, '(props: { color?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ref?: ((instance: HTMLHeadingElement | null) => void) | RefObject<...> | null | undefined; ... 251 more ...; titleColor: string; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Type '{ textColor: string; }' is not assignable to type 'IntrinsicAttributes & { color?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ... 252 more ...; titleColor: string; } & { ...; } & { ...; }'.
Property 'textColor' does not exist on type 'IntrinsicAttributes & { color?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ... 252 more ...; titleColor: string; } & { ...; } & { ...; }'.
Overload 2 of 2, '(props: StyledComponentPropsWithAs<"h2", any, HeaderProp, never, "h2", "h2">): ReactElement

Body:
Very new to JEST, REACT, ES6, etc.

I have been tasked with creating Jest tests for an existing code base before the team starts modifying and enhancing the application.

import styled from "styled-components/macro";
import { ViewHeader, ViewText } from "../../components/ViewStyle/ViewStyle";

export const Content = styled.div`
  align-self: center;
  justify-content: center;
  font-family: Fjalla One;
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 3rem;
`;

export const TextDiv = styled.div`
  p {
    margin-top: 0.5rem;
    max-width: 600px;
  }
`;

export default function SimplePage(
  props: Record<string, any>
): JSX.Element {
  const config = props.viewData?.config;
  return (

        <Content>
          <TextDiv>
            <ViewHeader titleColor={config?.textColor}>
              {props?.viewData.title}
            </ViewHeader>
            <ViewText textColor={config?.textColor}>
              {config?.description}
            </ViewText>
          </TextDiv>
          </Content>
  );
}

<ViewHeader> is a simple component which is handling the text color.

import styled from "styled-components/macro";

interface HeaderProp {
  titleColor: string;
}

export const ViewHeader = styled.h2<HeaderProp>`
  color: ${({ titleColor }) => titleColor};
`;

Instead of testing SimplePage.tsx I am singling out the ViewHeader component. Once I have a GREEN test, I will create testing for the ViewText component.

Here I render the ViewHeader with textColor = red, and I expect it to have a style rule if color = red but instead I am getting a TS error.

import renderer from "react-test-renderer";
import "jest-styled-components";
import { ViewHeader } from "../ViewStyle";

test("it works", () => {
  const textColor = "red";
  const tree = renderer.create(<ViewHeader textColor={textColor} />).toJSON();
  expect(tree).toHaveStyleRule("color", "red");
});

Jest (features-web)

Test run started at 1/11/2023, 10:04:59 AM <

FAIL   Features-Web  src/components/ViewStyle/test/ViewStyle.test.tsx
Test suite failed to run

src/components/ViewStyle/test/ViewStyle.test.tsx:7:44 - error TS2769: No overload matches this call.
Overload 1 of 2, '(props: { color?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ref?: ((instance: HTMLHeadingElement | null) => void) | RefObject<...> | null | undefined; ... 251 more ...; titleColor: string; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Type '{ textColor: string; }' is not assignable to type 'IntrinsicAttributes & { color?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ... 252 more ...; titleColor: string; } & { ...; } & { ...; }'.
Property 'textColor' does not exist on type 'IntrinsicAttributes & { color?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; title?: string | undefined; ... 252 more ...; titleColor: string; } & { ...; } & { ...; }'.
Overload 2 of 2, '(props: StyledComponentPropsWithAs<"h2", any, HeaderProp, never, "h2", "h2">): ReactElement


问:
PHP for inner loop
I have 2 arrays, the first array was working as expected (looping through the array updating the db with all elements inserted) But I added a second array that has a value I basically wanted this value to merge to the output of array 1 (I use this to add to the db, it's a string value). This is driven by a form so only rows that are selected should be added.

so array 1 is item, description... and array 2 is hashtag added

I would like for only rows that are selected (item1, description1, hashtag1.. item4, description4, hashtag4 ... item5, description5, hashtag5 if we selected rows 1,4 and 5... it could be rows 7,8,9,10 or 1,2,3... all depends)

My code outputs like (hashtag1, item1, description1 and hashtag1, item4, description4 and hashtag1, item5, description5... hashtag2, item1, description1 and hashtag2, item4, description4 and hashtag2, item5, description5 so on... repeating hashtag for each loop 3 times this case)

So instead of 3 times it is 9 times repeating the same hashtag 3 times

```<code>$checked = $_POST['check'];
$changed = $_POST['hashtag'];

$finalArray;
$changedVal;

$count = count($changed);
$count2 = count($checked);

for ($i = 0; $i < $count; $i++) {

    if (!empty($changed[$i])
        && isset($changed[$i])
        && !is_null($changed[$i]))
    {

        echo "<br>" . "it happens" . "<br>";

        for ($jj =0; $jj < $count2; $jj++) {
            $resultVal = $changed[$i] . "&&&" . $checked[$jj];
            $unbinditem = array_pad(explode("&&&",$resultVal), 5, null);
</code>```

Title: PHP for inner loop

Body:
I have 2 arrays, the first array was working as expected (looping through the array updating the db with all elements inserted) But I added a second array that has a value I basically wanted this value to merge to the output of array 1 (I use this to add to the db, it's a string value). This is driven by a form so only rows that are selected should be added.

so array 1 is item, description... and array 2 is hashtag added

I would like for only rows that are selected (item1, description1, hashtag1.. item4, description4, hashtag4 ... item5, description5, hashtag5 if we selected rows 1,4 and 5... it could be rows 7,8,9,10 or 1,2,3... all depends)

My code outputs like (hashtag1, item1, description1 and hashtag1, item4, description4 and hashtag1, item5, description5... hashtag2, item1, description1 and hashtag2, item4, description4 and hashtag2, item5, description5 so on... repeating hashtag for each loop 3 times this case)

So instead of 3 times it is 9 times repeating the same hashtag 3 times

$checked = $_POST['check'];
$changed = $_POST['hashtag'];

$finalArray;
$changedVal;

$count = count($changed);
$count2 = count($checked);

for ($i = 0; $i < $count; $i++) {

    if (!empty($changed[$i])
        && isset($changed[$i])
        && !is_null($changed[$i]))
    {

        echo "
" . "it happens" . "
";

        for ($jj =0; $jj < $count2; $jj++) {
            $resultVal = $changed[$i] . "&&&" . $checked[$jj];
            $unbinditem = array_pad(explode("&&&",$resultVal), 5, null);


问:
How to web app isntace of Zxing QR generator locally?
I am hoping someone can provide some guidance on how to host a local html / web app instance of https://zxing.appspot.com/generator. I have read the documentation, and have searched in the web but I have come away empty-handed.

Also related, Does anyone know how safe it is to use zxing.appspot.com/generator when entering personal info (like wifi passwords)?--> this is one motivation to run the app locally but I am not sure if this concern is well-founded.

I tried downloading the web app source code from: https://github.com/zxing/zxing/tree/master/zxing.appspot.com
and installed it using maven. It seems like the installation went without issues  (in wsl2), but I dont find a way to run the app locally as a web server.


问:
How to schedule Sqoop import from Mysql and load in HDFS using Airflow 2.5.0
I want to learn Airflow and thus am performing following task.

I want to read data from MySQL DB and load it to HDFS. I am doing this task using sqoop manually.

Now I want to schedule this activity using Airflow.

I have written the following DAG which will perform this task. But I am stuck in creating the Conn_ID for MySQL, Sqoop, HDFS.
I am here to seek some inputs can you kindly help me out here.

```<code>from airflow.models import DAG
from airflow.contrib.operators.sqoop_operator import SqoopOperator
from airflow.utils.dates import days_ago

Dag_Sqoop_Import = DAG(dag_id="SqoopImport",
                      schedule_interval="* * * * *",
                      start_date=days_ago(2))

sqoop_mysql_import = SqoopOperator(conn_id="sqoop_local",
                                  table="shipmethod",
                                  cmd_type="import",
                                  target_dir="/airflow_sqoopImport",
                                  num_mappers=1,
                                  task_id="SQOOP_Import",
                                  dag=Dag_Sqoop_Import)

sqoop_mysql_import
</code>```

Replies Appreciated, Thanks.

Body:
I want to learn Airflow and thus am performing following task.

I want to read data from MySQL DB and load it to HDFS. I am doing this task using sqoop manually.

Now I want to schedule this activity using Airflow.

I have written the following DAG which will perform this task. But I am stuck in creating the Conn_ID for MySQL, Sqoop, HDFS.
I am here to seek some inputs can you kindly help me out here.

from airflow.models import DAG
from airflow.contrib.operators.sqoop_operator import SqoopOperator
from airflow.utils.dates import days_ago

Dag_Sqoop_Import = DAG(dag_id="SqoopImport",
                      schedule_interval="* * * * *",
                      start_date=days_ago(2))

sqoop_mysql_import = SqoopOperator(conn_id="sqoop_local",
                                  table="shipmethod",
                                  cmd_type="import",
                                  target_dir="/airflow_sqoopImport",
                                  num_mappers=1,
                                  task_id="SQOOP_Import",
                                  dag=Dag_Sqoop_Import)

sqoop_mysql_import

Replies Appreciated, Thanks.