问:
How to make a sprite rotate to face the mouse?
After several hours of complete utter chaos, I still haven't found a solution to rotating a sprite to face the mouse position. I've implemented several examples from other post, the links are below, but none of them seem to be effective. Any help with my problem, would be very appreciated :)

Pygame Making A Sprite Face The Mouse

https://ubuntuforums.org/showthread.php?t=1823825

https://gamedev.stackexchange.com/questions/132163/how-can-i-make-the-player-look-to-the-mouse-direction-pygame-2d

Original Code:

```<code>class Player(pygame.sprite.Sprite):
    def __init__(self, game, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        sprite_sheet = Spritesheet("Sprites/ships_spritesheet.png")
        image = sprite_sheet.get_image(204, 115, 66, 113)
        self.image = pygame.transform.flip(image, False, True)
        self.orig_img = self.image
        self.rect = self.image.get_rect()
        self.pos = vec(x, y)
        self.vel = vec(0, 0)
        self.health = PLAYER_HEALTH

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.x = self.pos.x
        self.collide_with_tiles(self.game.obstacle_list, "x")
        self.rect.y = self.pos.y
        self.collide_with_tiles(self.game.obstacle_list, "y")

    def rotate(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y
        angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
        self.image = pygame.transform.rotate(self.orig_img, int(angle))
        self.rect = self.image.get_rect(center=self.pos)
</code>```

New Code:

```<code>class Player(pygame.sprite.Sprite):
    def __init__(self, game, pos):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        sprite_sheet = Spritesheet("Sprites/ships_spritesheet.png")
        image = sprite_sheet.get_image(204, 115, 66, 113)
        self.image = pygame.transform.flip(image, False, True)
        self.orig_img = self.image
        self.rect = self.image.get_rect(center=pos)
        self.pos = vec(pos)
        self.vel = vec(0, 0)
        self.health = PLAYER_HEALTH

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.centerx = self.pos.x
        #self.rect.x = self.pos.x
        self.collide_with_tiles(self.game.obstacle_list, "x")
        self.rect.centery = self.pos.y
        #self.rect.y = self.pos.y
        self.collide_with_tiles(self.game.obstacle_list, "y")
        self.vel = vec(0, 0)

    def rotate(self):
        mouse_pos = pygame.mouse.get_pos()
        rel_x, rel_y = mouse_pos - self.pos
        angle = -math.degrees(math.atan2(rel_y, rel_x))
        self.image = pygame.transform.rotate(self.orig_img, angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def collide_with_tiles(self, group, dir):
        if dir == "x":
            hits = pygame.sprite.spritecollide(self, group, False)
            if hits:
                if self.vel.x > 0:
                    self.rect.right = hits[0].rect.left
                if self.vel.x < 0:
                    self.rect.left = hits[0].rect.right
                self.pos.x = self.rect.centerx

        if dir == "y":
            hits = pygame.sprite.spritecollide(self, group, False)
            if hits:
                if self.vel.y > 0:
                    self.rect.bottom = hits[0].rect.top
                if self.vel.y < 0:
                    self.rect.top = hits[0].rect.bottom
                self.pos.y = self.rect.centery
</code>```

My Game Class

```<code>import pygame, pytmx, sys, os

from Settings import *
from Obstacle import *
from Player import *
from Camera import *
from TiledMap import *
from MainMenu import *
from PauseMenu import *
from OptionsMenu import *
from HUD import *

class Game:
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.display.set_caption(GAME_TITLE)
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        self.clock = pygame.time.Clock()
        self.click_sound = pygame.mixer.Sound("Sounds/click1.ogg")
        self.main_menu = MainMenu(self, self.window)
        self.obstacle_list = pygame.sprite.Group()
        self.island_boundary_list = pygame.sprite.Group()
        self.pause_menu = PauseMenu(self.window)
        self.options_menu = OptionsMenu(self.window)
        self.hud = HUD()
        self.display_pause_menu = False
        self.display_options_menu = False
        self.display_main_menu = True

    def get_map(self):
        map_dir = TiledMap("Sprites/Maps/map_01.tmx")
        self.map = map_dir.generate_map()
        self.map_rect = self.map.get_rect()

        for tile_obj in map_dir.tmxdata.objects:
            if tile_obj.name == "Obstacle":
                obstacle = Obstacle(self, tile_obj.x, tile_obj.y, 64, 64)
                self.obstacle_list.add(obstacle)
            if tile_obj.name == "PLAYER":
                self.player = Player(self, (tile_obj.x, tile_obj.y))

    def game_loop(self):
        self.get_map()
        self.camera = Camera(5120, 5120)

        while True:
            self.clock.tick(FPS)
            self.game_events()

            if not self.display_pause_menu and not self.display_options_menu and not self.display_main_menu:
            self.update_game()

            self.draw_game()

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

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p and not self.display_options_menu:
                    self.display_pause_menu = not self.display_pause_menu
                if event.key == pygame.K_o and not self.display_pause_menu:
                    self.display_options_menu = not self.display_options_menu

            if event.type == pygame.MOUSEBUTTONDOWN and self.display_main_menu:
                x, y = event.pos
                self.click_sound.play()
                if self.main_menu.play_button.collidepoint(x, y):
                    self.display_main_menu = False
                if self.main_menu.credits_button.collidepoint(x, y):
                    pass
                if self.main_menu.exit_button.collidepoint(x, y):
                    pygame.quit()
                    sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN and self.display_pause_menu:
                x, y = event.pos
                self.click_sound.play()
                if self.pause_menu.pause_resume_button.collidepoint(x, y) or self.pause_menu.pause_x_button.collidepoint(x, y):
                    self.display_pause_menu = False
                if self.pause_menu.pause_options_button.collidepoint(x, y):
                    self.display_pause_menu = False
                    self.display_options_menu = True
                if self.pause_menu.pause_quit_button.collidepoint(x, y):
                    pygame.quit()
                    sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN and self.display_options_menu:
                x, y = event.pos
                self.click_sound.play()
                if self.options_menu.options_x_button.collidepoint(x, y):
                    self.display_options_menu = False
                if self.options_menu.options_reset_button.collidepoint(x, y):
                    #reset options to original options if modified
                    pass
                if self.options_menu.options_home_button.collidepoint(x, y):
                    self.display_options_menu = False
                    self.display_main_menu = True
                if self.options_menu.options_ok_button.collidepoint(x, y):
                    #save settings
                    self.display_options_menu = False

            mouse_x, mouse_y = pygame.mouse.get_pos()
            if mouse_x > self.main_menu.play_button.x and mouse_x < self.main_menu.play_button.x + self.main_menu.play_button.width and mouse_y > self.main_menu.play_button.y and mouse_y < self.main_menu.play_button.y + self.main_menu.play_button.height:
                self.main_menu.img_id = 1

            elif mouse_x > self.main_menu.credits_button.x and mouse_x < self.main_menu.credits_button.x + self.main_menu.credits_button.width and mouse_y > self.main_menu.credits_button.y and mouse_y < self.main_menu.credits_button.y + self.main_menu.credits_button.height:
                self.main_menu.img_id = 2

            elif mouse_x > self.main_menu.exit_button.x and mouse_x < self.main_menu.exit_button.x + self.main_menu.exit_button.width and mouse_y > self.main_menu.exit_button.y and mouse_y < self.main_menu.exit_button.y + self.main_menu.exit_button.height:
                self.main_menu.img_id = 3

            else:
                self.main_menu.img_id = 0

            if mouse_x > self.pause_menu.pause_resume_button.x and mouse_x < self.pause_menu.pause_resume_button.x + self.pause_menu.pause_resume_button.width and mouse_y > self.pause_menu.pause_resume_button.y and mouse_y < self.pause_menu.pause_resume_button.y + self.pause_menu.pause_resume_button.height:
                self.pause_menu.img_id = 1

            elif mouse_x > self.pause_menu.pause_x_button.x and mouse_x < self.pause_menu.pause_x_button.x + self.pause_menu.pause_x_button.width and mouse_y > self.pause_menu.pause_x_button.y and mouse_y < self.pause_menu.pause_x_button.y + self.pause_menu.pause_x_button.height:
                self.pause_menu.img_id = 2

            elif mouse_x > self.pause_menu.pause_options_button.x and mouse_x < self.pause_menu.pause_options_button.x + self.pause_menu.pause_options_button.width and mouse_y > self.pause_menu.pause_options_button.y and mouse_y < self.pause_menu.pause_options_button.y + self.pause_menu.pause_options_button.height:
                self.pause_menu.img_id = 3

            elif mouse_x > self.pause_menu.pause_quit_button.x and mouse_x < self.pause_menu.pause_quit_button.x + self.pause_menu.pause_quit_button.width and mouse_y > self.pause_menu.pause_quit_button.y and mouse_y < self.pause_menu.pause_quit_button.y + self.pause_menu.pause_quit_button.height:
                self.pause_menu.img_id = 4

            else:
                self.pause_menu.img_id = 0

            if mouse_x > self.options_menu.options_x_button.x and mouse_x < self.options_menu.options_x_button.x + self.options_menu.options_x_button.width and mouse_y > self.options_menu.options_x_button.y and mouse_y < self.options_menu.options_x_button.y + self.options_menu.options_x_button.height:
                self.options_menu.img_id = 1

            elif mouse_x > self.options_menu.options_reset_button.x and mouse_x < self.options_menu.options_reset_button.x + self.options_menu.options_reset_button.width and mouse_y > self.options_menu.options_reset_button.y and mouse_y < self.options_menu.options_reset_button.y + self.options_menu.options_reset_button.height:
                self.options_menu.img_id = 2

            elif mouse_x > self.options_menu.options_home_button.x and mouse_x < self.options_menu.options_home_button.x + self.options_menu.options_home_button.width and mouse_y > self.options_menu.options_home_button.y and mouse_y < self.options_menu.options_home_button.y + self.options_menu.options_home_button.height:
                self.options_menu.img_id = 3

            elif mouse_x > self.options_menu.options_ok_button.x and mouse_x < self.options_menu.options_ok_button.x + self.options_menu.options_ok_button.width and mouse_y > self.options_menu.options_ok_button.y and mouse_y < self.options_menu.options_ok_button.y + self.options_menu.options_ok_button.height:
                self.options_menu.img_id = 4

            else:
                self.options_menu.img_id = 0

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.player.vel.x = PLAYER_SPEED
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.player.vel.x = -PLAYER_SPEED
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.player.vel.y = -PLAYER_SPEED
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.player.vel.y = PLAYER_SPEED

    def update_game(self):
        self.player.update()
        self.camera.update(self.player)

        if self.player.rect.x <= 0:
            self.player.rect.x = 0
        if self.player.rect.right >= 5120:
            self.player.rect.right = 5120
        if self.player.rect.y <= 0:
            self.player.rect.y = 0
        if self.player.rect.bottom >= 5120:
            self.player.rect.bottom = 5120

    def draw_game(self):
        self.window.blit(self.map, self.camera.apply_rect(self.map_rect))
        self.window.blit(self.player.image, self.camera.apply(self.player))
        self.hud.draw_health(self.window, 10, 10, self.player.health / PLAYER_HEALTH)

        if self.display_main_menu:
            self.main_menu.draw()

        if self.display_pause_menu:
            self.pause_menu.draw()

        if self.display_options_menu:
            self.options_menu.draw()

        pygame.display.flip()

def main():
    g = Game()
    g.game_loop()

if __name__ == "__main__":
    main()
</code>```

Camera class

```<code>import pygame

from Settings import *

class Camera:
    def __init__(self, width, height):
        self.camera = pygame.Rect(0, 0, width, height)
        self.width = width
        self.height = height

    def apply(self, target):
        return target.rect.move(self.camera.topleft)

    def apply_rect(self, rect):
        return rect.move(self.camera.topleft)

    def update(self, target):
        x = -target.rect.centerx + int(WINDOW_WIDTH/2)
        y = -target.rect.centery + int(WINDOW_HEIGHT/2)
        x = min(0, x)
        y = min(0, y)
        x = max(-(self.width - WINDOW_WIDTH), x)
        y = max(-(self.height - WINDOW_HEIGHT), y)
        self.camera = pygame.Rect(x, y, self.width, self.height)
</code>```

答:
Use the center points self.rect.centerx and self.rect.centery or just self.rect.center and self.pos instead of self.rect.x self.rect.y (the topleft coordinates).

Here's the complete example that I used to test your code:

```<code>import math
import pygame
from pygame.math import Vector2

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 30), pygame.SRCALPHA)
        pygame.draw.polygon(
            self.image,
            pygame.Color('dodgerblue1'),
            ((0, 0), (50, 15), (0, 30)))
        self.rect = self.image.get_rect(center=pos)
        self.orig_img = self.image
        self.pos = Vector2(pos)
        self.vel = Vector2(0, 0)

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.centerx = self.pos.x
        self.rect.centery = self.pos.y

    def rotate(self):
        mouse_pos = pygame.mouse.get_pos()
        # Calculate the vector to the mouse position by subtracting
        # the self.pos vector from the mouse_pos.
        rel_x, rel_y = mouse_pos - self.pos
        # Use math.atan2 to get the angle in radians and convert it to degrees.
        angle = -math.degrees(math.atan2(rel_y, rel_x))
        # Rotate the image.
        self.image = pygame.transform.rotozoom(self.orig_img, angle, 1)
        # Update the rect and keep the center at the old position.
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    sprite_group = pygame.sprite.Group()
    player = Player((300, 200))
    sprite_group.add(player)

    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        sprite_group.update()
        screen.fill((30, 30, 30))
        sprite_group.draw(screen)

        pygame.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit()
</code>```

Edit3: In this example I use another pygame.Rect (called hitbox) to handle the collisions with the walls. The rect of the player can't be used for the collision detection, because it changes its size with each rotation what causes jumps if the player touches a wall. I'm using Rect.colliderect because spritecollide uses the rect not the hitbox, but you could also pass a custom collided callback function to spritecollide. (The red and green rects show the player.rect and player.hitbox.)

```<code>import math
import pygame
from pygame.math import Vector2 as vec

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, walls):
        pygame.sprite.Sprite.__init__(self)
        self.walls = walls
        self.image = pygame.Surface((50, 30), pygame.SRCALPHA)
        pygame.draw.polygon(
            self.image,
            pygame.Color('dodgerblue1'),
            ((0, 0), (50, 15), (0, 30)))
        self.rect = self.image.get_rect(center=(x, y))
        self.hitbox = pygame.Rect(x, y, 50, 50)
        self.orig_img = self.image
        self.pos = vec(x, y)
        self.vel = vec(0, 0)

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.hitbox.centerx = self.pos.x
        self.collide_with_tiles(self.walls, "x")
        self.hitbox.centery = self.pos.y
        self.collide_with_tiles(self.walls, "y")
        self.rect.center = self.pos

    def rotate(self):
        rel_x, rel_y = pygame.mouse.get_pos() - self.pos
        angle = -math.degrees(math.atan2(rel_y, rel_x))
        self.image = pygame.transform.rotate(self.orig_img, int(angle))
        self.rect = self.image.get_rect(center=self.pos)

    def collide_with_tiles(self, group, dir):
        if dir == "x":
             for wall in self.walls:
                 if self.hitbox.colliderect(wall.rect):
                     if self.vel.x > 0:
                         self.hitbox.right = wall.rect.left
                     if self.vel.x < 0:
                         self.hitbox.left = wall.rect.right
                     self.vel.x = 0
                     self.pos.x = self.hitbox.centerx

        if dir == "y":
            for wall in self.walls:
                if self.hitbox.colliderect(wall.rect):
                    if self.vel.y > 0:
                        self.hitbox.bottom = wall.rect.top
                    if self.vel.y < 0:
                        self.hitbox.top = wall.rect.bottom
                    self.vel.y = 0
                    self.pos.y = self.hitbox.centery

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((w, h))
        self.image.fill(pygame.Color('sienna1'))
        self.rect = self.image.get_rect(topleft=(x, y))

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()

    sprite_group = pygame.sprite.Group()
    walls = pygame.sprite.Group()

    wall = Wall(100, 200, 300, 30)
    walls.add(wall)
    sprite_group.add(wall)

    player = Player(300, 400, walls)
    sprite_group.add(player)

    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    player.vel.y = -3
                elif event.key == pygame.K_s:
                    player.vel.y = 3
                elif event.key == pygame.K_a:
                    player.vel.x = -3
                elif event.key == pygame.K_d:
                    player.vel.x = 3
            elif event.type == pygame.KEYUP:
                player.vel = vec(0, 0)

        sprite_group.update()
        screen.fill((30, 30, 30))
        sprite_group.draw(screen)
        pygame.draw.rect(screen, (200, 30, 30), player.rect, 2)
        pygame.draw.rect(screen, (0, 200, 30), player.hitbox, 2)

        pygame.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit()
</code>```

Edit4: To include the camera in the calculation, give the Player the camera as an attribute and in the rotate method just change this line:

```<code>rel_x, rel_y = pg.mouse.get_pos() - vec(self.camera.apply(self).center)
</code>```

Body:
After several hours of complete utter chaos, I still haven't found a solution to rotating a sprite to face the mouse position. I've implemented several examples from other post, the links are below, but none of them seem to be effective. Any help with my problem, would be very appreciated :)

Pygame Making A Sprite Face The Mouse

https://ubuntuforums.org/showthread.php?t=1823825

https://gamedev.stackexchange.com/questions/132163/how-can-i-make-the-player-look-to-the-mouse-direction-pygame-2d

Original Code:

class Player(pygame.sprite.Sprite):
    def __init__(self, game, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        sprite_sheet = Spritesheet("Sprites/ships_spritesheet.png")
        image = sprite_sheet.get_image(204, 115, 66, 113)
        self.image = pygame.transform.flip(image, False, True)
        self.orig_img = self.image
        self.rect = self.image.get_rect()
        self.pos = vec(x, y)
        self.vel = vec(0, 0)
        self.health = PLAYER_HEALTH

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.x = self.pos.x
        self.collide_with_tiles(self.game.obstacle_list, "x")
        self.rect.y = self.pos.y
        self.collide_with_tiles(self.game.obstacle_list, "y")

    def rotate(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y
        angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
        self.image = pygame.transform.rotate(self.orig_img, int(angle))
        self.rect = self.image.get_rect(center=self.pos)

New Code:

class Player(pygame.sprite.Sprite):
    def __init__(self, game, pos):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        sprite_sheet = Spritesheet("Sprites/ships_spritesheet.png")
        image = sprite_sheet.get_image(204, 115, 66, 113)
        self.image = pygame.transform.flip(image, False, True)
        self.orig_img = self.image
        self.rect = self.image.get_rect(center=pos)
        self.pos = vec(pos)
        self.vel = vec(0, 0)
        self.health = PLAYER_HEALTH

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.centerx = self.pos.x
        #self.rect.x = self.pos.x
        self.collide_with_tiles(self.game.obstacle_list, "x")
        self.rect.centery = self.pos.y
        #self.rect.y = self.pos.y
        self.collide_with_tiles(self.game.obstacle_list, "y")
        self.vel = vec(0, 0)

    def rotate(self):
        mouse_pos = pygame.mouse.get_pos()
        rel_x, rel_y = mouse_pos - self.pos
        angle = -math.degrees(math.atan2(rel_y, rel_x))
        self.image = pygame.transform.rotate(self.orig_img, angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def collide_with_tiles(self, group, dir):
        if dir == "x":
            hits = pygame.sprite.spritecollide(self, group, False)
            if hits:
                if self.vel.x > 0:
                    self.rect.right = hits[0].rect.left
                if self.vel.x < 0:
                    self.rect.left = hits[0].rect.right
                self.pos.x = self.rect.centerx

        if dir == "y":
            hits = pygame.sprite.spritecollide(self, group, False)
            if hits:
                if self.vel.y > 0:
                    self.rect.bottom = hits[0].rect.top
                if self.vel.y < 0:
                    self.rect.top = hits[0].rect.bottom
                self.pos.y = self.rect.centery

My Game Class

import pygame, pytmx, sys, os

from Settings import *
from Obstacle import *
from Player import *
from Camera import *
from TiledMap import *
from MainMenu import *
from PauseMenu import *
from OptionsMenu import *
from HUD import *

class Game:
    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.display.set_caption(GAME_TITLE)
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        self.clock = pygame.time.Clock()
        self.click_sound = pygame.mixer.Sound("Sounds/click1.ogg")
        self.main_menu = MainMenu(self, self.window)
        self.obstacle_list = pygame.sprite.Group()
        self.island_boundary_list = pygame.sprite.Group()
        self.pause_menu = PauseMenu(self.window)
        self.options_menu = OptionsMenu(self.window)
        self.hud = HUD()
        self.display_pause_menu = False
        self.display_options_menu = False
        self.display_main_menu = True

    def get_map(self):
        map_dir = TiledMap("Sprites/Maps/map_01.tmx")
        self.map = map_dir.generate_map()
        self.map_rect = self.map.get_rect()

        for tile_obj in map_dir.tmxdata.objects:
            if tile_obj.name == "Obstacle":
                obstacle = Obstacle(self, tile_obj.x, tile_obj.y, 64, 64)
                self.obstacle_list.add(obstacle)
            if tile_obj.name == "PLAYER":
                self.player = Player(self, (tile_obj.x, tile_obj.y))

    def game_loop(self):
        self.get_map()
        self.camera = Camera(5120, 5120)

        while True:
            self.clock.tick(FPS)
            self.game_events()

            if not self.display_pause_menu and not self.display_options_menu and not self.display_main_menu:
            self.update_game()

            self.draw_game()

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

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p and not self.display_options_menu:
                    self.display_pause_menu = not self.display_pause_menu
                if event.key == pygame.K_o and not self.display_pause_menu:
                    self.display_options_menu = not self.display_options_menu

            if event.type == pygame.MOUSEBUTTONDOWN and self.display_main_menu:
                x, y = event.pos
                self.click_sound.play()
                if self.main_menu.play_button.collidepoint(x, y):
                    self.display_main_menu = False
                if self.main_menu.credits_button.collidepoint(x, y):
                    pass
                if self.main_menu.exit_button.collidepoint(x, y):
                    pygame.quit()
                    sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN and self.display_pause_menu:
                x, y = event.pos
                self.click_sound.play()
                if self.pause_menu.pause_resume_button.collidepoint(x, y) or self.pause_menu.pause_x_button.collidepoint(x, y):
                    self.display_pause_menu = False
                if self.pause_menu.pause_options_button.collidepoint(x, y):
                    self.display_pause_menu = False
                    self.display_options_menu = True
                if self.pause_menu.pause_quit_button.collidepoint(x, y):
                    pygame.quit()
                    sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN and self.display_options_menu:
                x, y = event.pos
                self.click_sound.play()
                if self.options_menu.options_x_button.collidepoint(x, y):
                    self.display_options_menu = False
                if self.options_menu.options_reset_button.collidepoint(x, y):
                    #reset options to original options if modified
                    pass
                if self.options_menu.options_home_button.collidepoint(x, y):
                    self.display_options_menu = False
                    self.display_main_menu = True
                if self.options_menu.options_ok_button.collidepoint(x, y):
                    #save settings
                    self.display_options_menu = False

            mouse_x, mouse_y = pygame.mouse.get_pos()
            if mouse_x > self.main_menu.play_button.x and mouse_x < self.main_menu.play_button.x + self.main_menu.play_button.width and mouse_y > self.main_menu.play_button.y and mouse_y < self.main_menu.play_button.y + self.main_menu.play_button.height:
                self.main_menu.img_id = 1

            elif mouse_x > self.main_menu.credits_button.x and mouse_x < self.main_menu.credits_button.x + self.main_menu.credits_button.width and mouse_y > self.main_menu.credits_button.y and mouse_y < self.main_menu.credits_button.y + self.main_menu.credits_button.height:
                self.main_menu.img_id = 2

            elif mouse_x > self.main_menu.exit_button.x and mouse_x < self.main_menu.exit_button.x + self.main_menu.exit_button.width and mouse_y > self.main_menu.exit_button.y and mouse_y < self.main_menu.exit_button.y + self.main_menu.exit_button.height:
                self.main_menu.img_id = 3

            else:
                self.main_menu.img_id = 0

            if mouse_x > self.pause_menu.pause_resume_button.x and mouse_x < self.pause_menu.pause_resume_button.x + self.pause_menu.pause_resume_button.width and mouse_y > self.pause_menu.pause_resume_button.y and mouse_y < self.pause_menu.pause_resume_button.y + self.pause_menu.pause_resume_button.height:
                self.pause_menu.img_id = 1

            elif mouse_x > self.pause_menu.pause_x_button.x and mouse_x < self.pause_menu.pause_x_button.x + self.pause_menu.pause_x_button.width and mouse_y > self.pause_menu.pause_x_button.y and mouse_y < self.pause_menu.pause_x_button.y + self.pause_menu.pause_x_button.height:
                self.pause_menu.img_id = 2

            elif mouse_x > self.pause_menu.pause_options_button.x and mouse_x < self.pause_menu.pause_options_button.x + self.pause_menu.pause_options_button.width and mouse_y > self.pause_menu.pause_options_button.y and mouse_y < self.pause_menu.pause_options_button.y + self.pause_menu.pause_options_button.height:
                self.pause_menu.img_id = 3

            elif mouse_x > self.pause_menu.pause_quit_button.x and mouse_x < self.pause_menu.pause_quit_button.x + self.pause_menu.pause_quit_button.width and mouse_y > self.pause_menu.pause_quit_button.y and mouse_y < self.pause_menu.pause_quit_button.y + self.pause_menu.pause_quit_button.height:
                self.pause_menu.img_id = 4

            else:
                self.pause_menu.img_id = 0

            if mouse_x > self.options_menu.options_x_button.x and mouse_x < self.options_menu.options_x_button.x + self.options_menu.options_x_button.width and mouse_y > self.options_menu.options_x_button.y and mouse_y < self.options_menu.options_x_button.y + self.options_menu.options_x_button.height:
                self.options_menu.img_id = 1

            elif mouse_x > self.options_menu.options_reset_button.x and mouse_x < self.options_menu.options_reset_button.x + self.options_menu.options_reset_button.width and mouse_y > self.options_menu.options_reset_button.y and mouse_y < self.options_menu.options_reset_button.y + self.options_menu.options_reset_button.height:
                self.options_menu.img_id = 2

            elif mouse_x > self.options_menu.options_home_button.x and mouse_x < self.options_menu.options_home_button.x + self.options_menu.options_home_button.width and mouse_y > self.options_menu.options_home_button.y and mouse_y < self.options_menu.options_home_button.y + self.options_menu.options_home_button.height:
                self.options_menu.img_id = 3

            elif mouse_x > self.options_menu.options_ok_button.x and mouse_x < self.options_menu.options_ok_button.x + self.options_menu.options_ok_button.width and mouse_y > self.options_menu.options_ok_button.y and mouse_y < self.options_menu.options_ok_button.y + self.options_menu.options_ok_button.height:
                self.options_menu.img_id = 4

            else:
                self.options_menu.img_id = 0

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.player.vel.x = PLAYER_SPEED
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.player.vel.x = -PLAYER_SPEED
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.player.vel.y = -PLAYER_SPEED
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.player.vel.y = PLAYER_SPEED

    def update_game(self):
        self.player.update()
        self.camera.update(self.player)

        if self.player.rect.x <= 0:
            self.player.rect.x = 0
        if self.player.rect.right >= 5120:
            self.player.rect.right = 5120
        if self.player.rect.y <= 0:
            self.player.rect.y = 0
        if self.player.rect.bottom >= 5120:
            self.player.rect.bottom = 5120

    def draw_game(self):
        self.window.blit(self.map, self.camera.apply_rect(self.map_rect))
        self.window.blit(self.player.image, self.camera.apply(self.player))
        self.hud.draw_health(self.window, 10, 10, self.player.health / PLAYER_HEALTH)

        if self.display_main_menu:
            self.main_menu.draw()

        if self.display_pause_menu:
            self.pause_menu.draw()

        if self.display_options_menu:
            self.options_menu.draw()

        pygame.display.flip()

def main():
    g = Game()
    g.game_loop()

if __name__ == "__main__":
    main()

Camera class

import pygame

from Settings import *

class Camera:
    def __init__(self, width, height):
        self.camera = pygame.Rect(0, 0, width, height)
        self.width = width
        self.height = height

    def apply(self, target):
        return target.rect.move(self.camera.topleft)

    def apply_rect(self, rect):
        return rect.move(self.camera.topleft)

    def update(self, target):
        x = -target.rect.centerx + int(WINDOW_WIDTH/2)
        y = -target.rect.centery + int(WINDOW_HEIGHT/2)
        x = min(0, x)
        y = min(0, y)
        x = max(-(self.width - WINDOW_WIDTH), x)
        y = max(-(self.height - WINDOW_HEIGHT), y)
        self.camera = pygame.Rect(x, y, self.width, self.height)

Body:
Use the center points self.rect.centerx and self.rect.centery or just self.rect.center and self.pos instead of self.rect.x self.rect.y (the topleft coordinates).

Here's the complete example that I used to test your code:

import math
import pygame
from pygame.math import Vector2

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 30), pygame.SRCALPHA)
        pygame.draw.polygon(
            self.image,
            pygame.Color('dodgerblue1'),
            ((0, 0), (50, 15), (0, 30)))
        self.rect = self.image.get_rect(center=pos)
        self.orig_img = self.image
        self.pos = Vector2(pos)
        self.vel = Vector2(0, 0)

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.rect.centerx = self.pos.x
        self.rect.centery = self.pos.y

    def rotate(self):
        mouse_pos = pygame.mouse.get_pos()
        # Calculate the vector to the mouse position by subtracting
        # the self.pos vector from the mouse_pos.
        rel_x, rel_y = mouse_pos - self.pos
        # Use math.atan2 to get the angle in radians and convert it to degrees.
        angle = -math.degrees(math.atan2(rel_y, rel_x))
        # Rotate the image.
        self.image = pygame.transform.rotozoom(self.orig_img, angle, 1)
        # Update the rect and keep the center at the old position.
        self.rect = self.image.get_rect(center=self.rect.center)

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    sprite_group = pygame.sprite.Group()
    player = Player((300, 200))
    sprite_group.add(player)

    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

        sprite_group.update()
        screen.fill((30, 30, 30))
        sprite_group.draw(screen)

        pygame.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit()

Edit3: In this example I use another pygame.Rect (called hitbox) to handle the collisions with the walls. The rect of the player can't be used for the collision detection, because it changes its size with each rotation what causes jumps if the player touches a wall. I'm using Rect.colliderect because spritecollide uses the rect not the hitbox, but you could also pass a custom collided callback function to spritecollide. (The red and green rects show the player.rect and player.hitbox.)

import math
import pygame
from pygame.math import Vector2 as vec

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, walls):
        pygame.sprite.Sprite.__init__(self)
        self.walls = walls
        self.image = pygame.Surface((50, 30), pygame.SRCALPHA)
        pygame.draw.polygon(
            self.image,
            pygame.Color('dodgerblue1'),
            ((0, 0), (50, 15), (0, 30)))
        self.rect = self.image.get_rect(center=(x, y))
        self.hitbox = pygame.Rect(x, y, 50, 50)
        self.orig_img = self.image
        self.pos = vec(x, y)
        self.vel = vec(0, 0)

    def update(self):
        self.rotate()
        self.pos += self.vel
        self.hitbox.centerx = self.pos.x
        self.collide_with_tiles(self.walls, "x")
        self.hitbox.centery = self.pos.y
        self.collide_with_tiles(self.walls, "y")
        self.rect.center = self.pos

    def rotate(self):
        rel_x, rel_y = pygame.mouse.get_pos() - self.pos
        angle = -math.degrees(math.atan2(rel_y, rel_x))
        self.image = pygame.transform.rotate(self.orig_img, int(angle))
        self.rect = self.image.get_rect(center=self.pos)

    def collide_with_tiles(self, group, dir):
        if dir == "x":
             for wall in self.walls:
                 if self.hitbox.colliderect(wall.rect):
                     if self.vel.x > 0:
                         self.hitbox.right = wall.rect.left
                     if self.vel.x < 0:
                         self.hitbox.left = wall.rect.right
                     self.vel.x = 0
                     self.pos.x = self.hitbox.centerx

        if dir == "y":
            for wall in self.walls:
                if self.hitbox.colliderect(wall.rect):
                    if self.vel.y > 0:
                        self.hitbox.bottom = wall.rect.top
                    if self.vel.y < 0:
                        self.hitbox.top = wall.rect.bottom
                    self.vel.y = 0
                    self.pos.y = self.hitbox.centery

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((w, h))
        self.image.fill(pygame.Color('sienna1'))
        self.rect = self.image.get_rect(topleft=(x, y))

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()

    sprite_group = pygame.sprite.Group()
    walls = pygame.sprite.Group()

    wall = Wall(100, 200, 300, 30)
    walls.add(wall)
    sprite_group.add(wall)

    player = Player(300, 400, walls)
    sprite_group.add(player)

    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    player.vel.y = -3
                elif event.key == pygame.K_s:
                    player.vel.y = 3
                elif event.key == pygame.K_a:
                    player.vel.x = -3
                elif event.key == pygame.K_d:
                    player.vel.x = 3
            elif event.type == pygame.KEYUP:
                player.vel = vec(0, 0)

        sprite_group.update()
        screen.fill((30, 30, 30))
        sprite_group.draw(screen)
        pygame.draw.rect(screen, (200, 30, 30), player.rect, 2)
        pygame.draw.rect(screen, (0, 200, 30), player.hitbox, 2)

        pygame.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit()

Edit4: To include the camera in the calculation, give the Player the camera as an attribute and in the rotate method just change this line:

rel_x, rel_y = pg.mouse.get_pos() - vec(self.camera.apply(self).center)


来源: stackexchange

问:
Scraping multiple tables along with their headers on a Wikipedia page using python requests and BeatifulSoup?
Using python libraries, request and BeautifulSoup, I am trying to scrape the tables on this wikipedia page: https://en.wikipedia.org/wiki/Mobile_country_code. I can get all the data in the tables; however, I want to add another column called Country, from table names, populate it with table names.Here is an example,
Wikipedia table(above) and the desired table(below).

The code below allows me to get all the data without the Country column:

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

wiki = requests.get('https://en.wikipedia.org/wiki/Mobile_country_code')
soup = BeautifulSoup(wiki.content, 'html.parser')

# Get all the tables
tables = soup.find_all('table',class_="wikitable")

# extract the column names
column_names = [item.get_text() for item in tables[0].find_all('th')]

# extract the content
contents = [item.get_text() for item in tables[0].find_all('td')]

# put all the content into a list
values=[]
for table in tables:
    for item in table.select('td'):
        temp = item.get_text()
        values.append(temp)

# Since there are 7 columns, obtain the number of rows and reshape the table
len(values)/7   # 2452 rows

# change the shape of the table
data = np.reshape(values,(2452,7))

# put all the data into a dataframe
df = pd.DataFrame(data = data, columns=header_list)
</code>```

答:
Try with:

```<code>#This is the table which I want to extract
# Get all the tables
tables = soup.find_all('table',class_="wikitable")

# extract the column names
column_names = [item.get_text() for item in tables[0].find_all('th')]

# extract the content
contents = [item.get_text() for item in tables[0].find_all('td')]

# put all the content into a list

values_list = []
#find all countries
countries = soup.find_all('h3')
international = [soup.find('span',{"id":"International_operators"}).parent]
countries = countries+international
for c in countries:
    table = c.find_next_sibling("table")
    if table is not None: #check the coutries has table
        for item in table.select('tr')[1:]:
            values = [e.get_text() for e in item.select('td')]
            values = [c.text]+values
            values_list.append(values)

header_list = ["COUNTRY"]+ column_names

# put all the data into a dataframe
df = pd.DataFrame(values_list, columns=header_list)
</code>```

df will be:

```<code>    COUNTRY             MCC MNC Brand    Operator       Status       Bands (MHz)                                        References and notes
0   Abkhazia - GE-AB    289 67  Aquafon  Aquafon JSC    Operational GSM 900 / GSM 1800 / UMTS 2100 / LTE 800            MCC is not listed by ITU;[85] LTE band 20[95]
1   Abkhazia - GE-AB    289 88  A-Mobile A-Mobile LLSC  Operational GSM 900 / GSM 1800 / UMTS 2100 / LTE 800 / LTE...   MCC is not listed by ITU[85]
...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using python libraries, request and BeautifulSoup, I am trying to scrape the tables on this wikipedia page: https://en.wikipedia.org/wiki/Mobile_country_code. I can get all the data in the tables; however, I want to add another column called Country, from table names, populate it with table names.Here is an example,
Wikipedia table(above) and the desired table(below).

The code below allows me to get all the data without the Country column:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np

wiki = requests.get('https://en.wikipedia.org/wiki/Mobile_country_code')
soup = BeautifulSoup(wiki.content, 'html.parser')

# Get all the tables
tables = soup.find_all('table',class_="wikitable")

# extract the column names
column_names = [item.get_text() for item in tables[0].find_all('th')]

# extract the content
contents = [item.get_text() for item in tables[0].find_all('td')]

# put all the content into a list
values=[]
for table in tables:
    for item in table.select('td'):
        temp = item.get_text()
        values.append(temp)

# Since there are 7 columns, obtain the number of rows and reshape the table
len(values)/7   # 2452 rows

# change the shape of the table
data = np.reshape(values,(2452,7))

# put all the data into a dataframe
df = pd.DataFrame(data = data, columns=header_list)

Body:
Try with:

#This is the table which I want to extract
# Get all the tables
tables = soup.find_all('table',class_="wikitable")

# extract the column names
column_names = [item.get_text() for item in tables[0].find_all('th')]

# extract the content
contents = [item.get_text() for item in tables[0].find_all('td')]

# put all the content into a list

values_list = []
#find all countries
countries = soup.find_all('h3')
international = [soup.find('span',{"id":"International_operators"}).parent]
countries = countries+international
for c in countries:
    table = c.find_next_sibling("table")
    if table is not None: #check the coutries has table
        for item in table.select('tr')[1:]:
            values = [e.get_text() for e in item.select('td')]
            values = [c.text]+values
            values_list.append(values)

header_list = ["COUNTRY"]+ column_names

# put all the data into a dataframe
df = pd.DataFrame(values_list, columns=header_list)

df will be:

    COUNTRY             MCC MNC Brand    Operator       Status       Bands (MHz)                                        References and notes
0   Abkhazia - GE-AB    289 67  Aquafon  Aquafon JSC    Operational GSM 900 / GSM 1800 / UMTS 2100 / LTE 800            MCC is not listed by ITU;[85] LTE band 20[95]
1   Abkhazia - GE-AB    289 88  A-Mobile A-Mobile LLSC  Operational GSM 900 / GSM 1800 / UMTS 2100 / LTE 800 / LTE...   MCC is not listed by ITU[85]
...


问:
Set focus to different column in DataGridView
Column 0 in a DataGridView control is Read Only.  I want the focus to move to column 1 if the user selects column 0 with the mouse or presses the tab key from the last column in the previous row.  I tried the following code in the CellEnter event but it causes an exception "Operation is not valid because it results in a reentrant call to the CurrentCellAddressCore function". Column 1 is named "patternsTerminator".

```<code>private void dataGridView_patterns_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    int currentRow = e.RowIndex;

    try
    {
        if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
            this.dataGridView_patterns.CurrentCell = this.dataGridView_patterns.Rows[currentRow].Cells["patternsTerminator"];
    }
    catch (Exception ex)
    {
        MessageBox.Show(this, ex.Message, errCaption, button, icon);
    }
}
</code>```

I understand why the exception occurs.  When the focus moves to column 1, the CellEnter event is called again, and the exception prevents recursive calls to the CellEnter event.

I tried the following as a workaround but it ignores the tab key.  When I click in column 0, SendKeys is called but the cursor stays in column 0.

```<code>if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
    SendKeys.Send("{TAB}");
</code>```

I have read many of the threads on this and other websites but can't get it to work.  Any suggestions would be greatly appreciated.

Thank you!

答:
I got around the exception but the focus doesn't work right - for me it wants to skip the 2nd column with the following code.  I ran out of time.  Play around with that and if you can't get it I will follow up soon.

```<code>private void DgNew_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        this.BeginInvoke(new MethodInvoker(() =>
        {
            moveCellTo(dgNew, e.RowIndex, 1);
        }));
    }
}

private void moveCellTo(DataGridView dgCurrent, int rowIndex, int columnIndex)
{
    dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnIndex];
}
</code>```

I got the idea from this post: How to evade reentrant call to setCurrentCellAddressCore?

Body:
Column 0 in a DataGridView control is Read Only.  I want the focus to move to column 1 if the user selects column 0 with the mouse or presses the tab key from the last column in the previous row.  I tried the following code in the CellEnter event but it causes an exception "Operation is not valid because it results in a reentrant call to the CurrentCellAddressCore function". Column 1 is named "patternsTerminator".

private void dataGridView_patterns_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    int currentRow = e.RowIndex;

    try
    {
        if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
            this.dataGridView_patterns.CurrentCell = this.dataGridView_patterns.Rows[currentRow].Cells["patternsTerminator"];
    }
    catch (Exception ex)
    {
        MessageBox.Show(this, ex.Message, errCaption, button, icon);
    }
}

I understand why the exception occurs.  When the focus moves to column 1, the CellEnter event is called again, and the exception prevents recursive calls to the CellEnter event.

I tried the following as a workaround but it ignores the tab key.  When I click in column 0, SendKeys is called but the cursor stays in column 0.

if (this.dataGridView_patterns.CurrentCell.ColumnIndex == 0)
    SendKeys.Send("{TAB}");

I have read many of the threads on this and other websites but can't get it to work.  Any suggestions would be greatly appreciated.

Thank you!

Body:
I got around the exception but the focus doesn't work right - for me it wants to skip the 2nd column with the following code.  I ran out of time.  Play around with that and if you can't get it I will follow up soon.

private void DgNew_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        this.BeginInvoke(new MethodInvoker(() =>
        {
            moveCellTo(dgNew, e.RowIndex, 1);
        }));
    }
}

private void moveCellTo(DataGridView dgCurrent, int rowIndex, int columnIndex)
{
    dgCurrent.CurrentCell = dgCurrent.Rows[rowIndex].Cells[columnIndex];
}

I got the idea from this post: How to evade reentrant call to setCurrentCellAddressCore?


问:
Tensorflow: Where is tf.nn.conv2d Actually Executed?
I am curious about the Tensorflow implementation of tf.nn.conv2d(...). To call it, one simply runs tf.nn.conv2d(...). However, I'm going down the rabbit hole trying to see where it is executed. The code is as follows (where the arrow indicates the function it ultimately calls):

```<code>tf.nn.conv2d(...) -> tf.nn_ops.conv2d(...) -> tf.gen_nn_ops.conv2d(...) -> _op_def_lib.apply_op("Conv2D", ...) -> ?
</code>```

I am familiar with Tensorflow's implementation of LSTMs and the ability to easily manipulate them as one deems fit. Is the function that performs the conv2d() calculation written in Python, and if so, where is it? Can I see where and how the strides are executed?

答:
TensorFlow programs as consisting of two discrete sections:

Building the computational graph.

tf.nn.conv2d(...) -> tf.nn_ops.conv2d(...) -> tf.gen_nn_ops.conv2d(...) -> _op_def_lib.apply_op("Conv2D", ...) -> graph.create_op -> register op into graph

Running the computational graph.

sess = tf.Session(target) -> sess.run(conv2d) -> master prune full graph to client graph -> master split client graph by task to graph partition -> register graph partition to worker -> worker split subgraph by device to graph partition -> then master notify all workers to run graph partitions -> worker notify all devices to run graph partitions -> executor will run ops by topological sort on device.

For one of op, the executor will invoke kernel implement to compute for the op.

The kernel implement of tf.nn.conv2d() is written in C++, which invokes optimized code using either Eigen (on CPU) or the cuDNN library (on GPU).

Body:
I am curious about the Tensorflow implementation of tf.nn.conv2d(...). To call it, one simply runs tf.nn.conv2d(...). However, I'm going down the rabbit hole trying to see where it is executed. The code is as follows (where the arrow indicates the function it ultimately calls):

tf.nn.conv2d(...) -> tf.nn_ops.conv2d(...) -> tf.gen_nn_ops.conv2d(...) -> _op_def_lib.apply_op("Conv2D", ...) -> ?

I am familiar with Tensorflow's implementation of LSTMs and the ability to easily manipulate them as one deems fit. Is the function that performs the conv2d() calculation written in Python, and if so, where is it? Can I see where and how the strides are executed?


问:
Android - Receive calendar reminder notification using NotificationListener service
I have two issues using NotificationListener service

I have using NotificationListenerService class in my app. This listener #onNotificationPosted method receive all notification.

My code like below

```<code>public class MyListener extends NotificationListenerService
{
     public void onNotificationPosted(StatusBarNotification statusBarNotification)
     {
       //Receive all notification.
       // I need to receive reminder notification only
     }
 //.....
 ......
}
//My Manifiest like below
 <service
        android:name=".MyListener"
        android:enabled="true"
        android:label="@string/app_name"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService"/>
        </intent-filter>
    </service>
</code>```

But I need to receive calendar reminder notification only.

How to add filter to receive calendar reminder notification only ?

When i turn on notification access , it shows below message

Allow notification access for MyApp?

MyAPP will be able to read all notifications, including personal
information such as contact names and the text of messages that you
receive. It will also be able to dismiss notifications or tigger action
buttons that they contain

How to change the above message in notification access dialog ?

答:
How to add filter to receive calendar reminder notification only ?

To filter for Google's Calendar we can listen for notifications
posted with the com.google.android.calendar package name by using
StatusBarNotification.getPackageName.

To filter for reminder notifications we can listen for notifications
posted with the reminder category using
Notification.CATEGORY_REMINDER. (API 23+)

```<code>public class ReminderListenerService extends NotificationListenerService {

    private static final String CALENDAR_PKG = "com.google.android.calendar";

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        final Notification noti = sbn.getNotification();
        // Filter for the Calendar application
        final boolean isCalendar = CALENDAR_PKG.equals(sbn.getPackageName());
        // Filter for Notification.CATEGORY_REMINDER (API 23+)
        final boolean isReminder = Notification.CATEGORY_REMINDER.equals(noti.category);
        // Retrieve the reminder
        final String reminder = noti.extras.getString(Notification.EXTRA_TITLE);
    }

}
</code>```

Lollipop

I'm not sure how to filter for reminders in Lollipop, as far as the Google Calendar app goes. Notification.CATEGORY_EVENT is used instead of something like NotificationCompat.CATEGORY_REMINDER.

How to change the above message in notification access dialog ?

You can't. But you could show your own dialog explaining why you need access and then direct the user to the notification listener settings using:

```<code>startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
</code>```

Body:
I have two issues using NotificationListener service

I have using NotificationListenerService class in my app. This listener #onNotificationPosted method receive all notification.

My code like below

public class MyListener extends NotificationListenerService
{
     public void onNotificationPosted(StatusBarNotification statusBarNotification)
     {
       //Receive all notification.
       // I need to receive reminder notification only
     }
 //.....
 ......
}
//My Manifiest like below
 <service
        android:name=".MyListener"
        android:enabled="true"
        android:label="@string/app_name"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService"/>
        </intent-filter>
    </service>

But I need to receive calendar reminder notification only.

How to add filter to receive calendar reminder notification only ?

When i turn on notification access , it shows below message

Allow notification access for MyApp?

MyAPP will be able to read all notifications, including personal
information such as contact names and the text of messages that you
receive. It will also be able to dismiss notifications or tigger action
buttons that they contain

How to change the above message in notification access dialog ?

Body:
How to add filter to receive calendar reminder notification only ?

To filter for Google's Calendar we can listen for notifications
posted with the com.google.android.calendar package name by using
StatusBarNotification.getPackageName.

To filter for reminder notifications we can listen for notifications
posted with the reminder category using
Notification.CATEGORY_REMINDER. (API 23+)

public class ReminderListenerService extends NotificationListenerService {

    private static final String CALENDAR_PKG = "com.google.android.calendar";

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        final Notification noti = sbn.getNotification();
        // Filter for the Calendar application
        final boolean isCalendar = CALENDAR_PKG.equals(sbn.getPackageName());
        // Filter for Notification.CATEGORY_REMINDER (API 23+)
        final boolean isReminder = Notification.CATEGORY_REMINDER.equals(noti.category);
        // Retrieve the reminder
        final String reminder = noti.extras.getString(Notification.EXTRA_TITLE);
    }

}

Lollipop

I'm not sure how to filter for reminders in Lollipop, as far as the Google Calendar app goes. Notification.CATEGORY_EVENT is used instead of something like NotificationCompat.CATEGORY_REMINDER.

How to change the above message in notification access dialog ?

You can't. But you could show your own dialog explaining why you need access and then direct the user to the notification listener settings using:

startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)


问:
Selenium Disable “Disable Developer Mode Extensions” Popup While adding extension
I want to disable the "Disable Developer Mode Extensions" popup while keeping an extension as mentioned in this post keep "Disable developer mode" closed while adding extension

There was no answer and I'm trying to do the same thing. Is there a chrome option like this available for Selenium?

答:
Here is the Answer to your Question:

While working with Selenium 3.4.0, chromedriver v2.30, Google Chrome 59.0 through Java bindings, you can use the ChromeOption class to disable the "Disable Developer Mode Extensions" popup as follows:

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class Q44959944_dev_extn {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        options.addArguments("--disable-extensions");
        WebDriver driver = new ChromeDriver(options);
        driver.navigate().to("https://google.com");
    }
}
</code>```

Let me know if this Answers your Question.

Body:
Here is the Answer to your Question:

While working with Selenium 3.4.0, chromedriver v2.30, Google Chrome 59.0 through Java bindings, you can use the ChromeOption class to disable the "Disable Developer Mode Extensions" popup as follows:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class Q44959944_dev_extn {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        options.addArguments("--disable-extensions");
        WebDriver driver = new ChromeDriver(options);
        driver.navigate().to("https://google.com");
    }
}

Let me know if this Answers your Question.


问:
spring cache - Null key returned for cache operation
I have been working with Spring Cache Abstraction and Ehcache. I'm using the @Cacheable annotation on a target method like so:

```<code>@Component
public class DataService {
    @Cacheable(value="movieFindCache", key="#name")
    public String findByDirector(String name) {
        return "hello";
    }
}
</code>```

This is my jUnit test:

```<code>public class ServiceTest extends AbstractJUnit4SpringContextTests{

    @Resource
    private DataService dataService;

    @Test
    public void test_service() {
        System.err.println(dataService.findByDirector("Hello"));
    }
}
</code>```

This is not working fine when I debug with jUnit test. It throws an IllegalArgumentException as follows:

```<code>java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) CacheableOperation[public java.lang.String com.eliteams.quick4j.web.service.ExcelDataService.getCarData()] caches=[movieFindCache] | key='#name' | condition='' | unless=''
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.cache.interceptor.CacheAspectSupport.generateKey(CacheAspectSupport.java:315)
at org.springframework.cache.interceptor.CacheAspectSupport.collectPutRequests(CacheAspectSupport.java:265)
</code>```

I have the following config:

applicationContext.xml:

```<code><cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
      p:configLocation="classpath:ehcache.xml" p:shared="true"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
      p:cacheManager-ref="ehCacheManagerFactory"/>
</code>```

ehcache.xml:

```<code><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
     updateCheck="true"
     monitoring="autodetect"
     dynamicConfig="true">

<diskStore path="java.io.tmpdir" />

<cache name="movieFindCache"
       maxEntriesLocalHeap="10000"
       maxEntriesLocalDisk="1000"
       eternal="false"
       diskSpoolBufferSizeMB="20"
       timeToIdleSeconds="300" timeToLiveSeconds="600"
       memoryStoreEvictionPolicy="LFU"
       transactionalMode="off">
    <persistence strategy="localTempSwap" />
</cache>
</code>```

note: If I don't specify the "key" in the @Cacheable annotations, it works.

Is there anything I forgot to specify? config? annotations?

答:
you could try to replace key with #p0

```<code>@Component
public class DataService {
    @Cacheable(value="movieFindCache", key="#p0")
    public String findByDirector(String name) {
        return "hello";
    }
}
</code>```

reference from
Spring Cache Abstraction VS interfaces VS key param ("Null key returned for cache operation" error)

ContentLicense: CC BY-SA 4.0

Body:
I have been working with Spring Cache Abstraction and Ehcache. I'm using the @Cacheable annotation on a target method like so:

@Component
public class DataService {
    @Cacheable(value="movieFindCache", key="#name")
    public String findByDirector(String name) {
        return "hello";
    }
}

This is my jUnit test:

public class ServiceTest extends AbstractJUnit4SpringContextTests{

    @Resource
    private DataService dataService;

    @Test
    public void test_service() {
        System.err.println(dataService.findByDirector("Hello"));
    }
}

This is not working fine when I debug with jUnit test. It throws an IllegalArgumentException as follows:

java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) CacheableOperation[public java.lang.String com.eliteams.quick4j.web.service.ExcelDataService.getCarData()] caches=[movieFindCache] | key='#name' | condition='' | unless=''
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.cache.interceptor.CacheAspectSupport.generateKey(CacheAspectSupport.java:315)
at org.springframework.cache.interceptor.CacheAspectSupport.collectPutRequests(CacheAspectSupport.java:265)

I have the following config:

applicationContext.xml:

<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
      p:configLocation="classpath:ehcache.xml" p:shared="true"/>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
      p:cacheManager-ref="ehCacheManagerFactory"/>

ehcache.xml:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
     updateCheck="true"
     monitoring="autodetect"
     dynamicConfig="true">

<diskStore path="java.io.tmpdir" />

<cache name="movieFindCache"
       maxEntriesLocalHeap="10000"
       maxEntriesLocalDisk="1000"
       eternal="false"
       diskSpoolBufferSizeMB="20"
       timeToIdleSeconds="300" timeToLiveSeconds="600"
       memoryStoreEvictionPolicy="LFU"
       transactionalMode="off">
    <persistence strategy="localTempSwap" />
</cache>

note: If I don't specify the "key" in the @Cacheable annotations, it works.

Is there anything I forgot to specify? config? annotations?

Body:
you could try to replace key with #p0

@Component
public class DataService {
    @Cacheable(value="movieFindCache", key="#p0")
    public String findByDirector(String name) {
        return "hello";
    }
}

reference from
Spring Cache Abstraction VS interfaces VS key param ("Null key returned for cache operation" error)


问:
Check End Date input is 10 months after Start Date input. [PHP]
Just a student here, limited knowledge and understanding, please bear with me thank you in advance.

I have two inputs, a Start and End datetime input.
I need to see if the End input is after 10 months of Start input.
Ex. if I entered July 7, 2017 the only acceptable input for End is May of 2018 (10 Months after July).

Here is the date format that I used.

```<code>$start = date("Y-m-d",strtotime($_POST['start']));
$end = date("Y-m-d",strtotime($_POST['end']));
</code>```

Thank you again, for taking notice.

答: see http://php.net/manual/zh/datetime.diff.php, you will find the answer.</p>

Body:
Just a student here, limited knowledge and understanding, please bear with me thank you in advance.

I have two inputs, a Start and End datetime input.
I need to see if the End input is after 10 months of Start input.
Ex. if I entered July 7, 2017 the only acceptable input for End is May of 2018 (10 Months after July).

Here is the date format that I used.

$start = date("Y-m-d",strtotime($_POST['start']));
$end = date("Y-m-d",strtotime($_POST['end']));

Thank you again, for taking notice.


答:
This will be useful if you are allowed to accomplish the task with only PHP code. The definition of month is not straightforward. Any professor who asks you to undertake such a problem should be asked to define a month if the definition wasn't given.

If a PHP-only solution is acceptable, the I recommend you remove the mysql tag.

Title: Check End Date input is 10 months after Start Date input. [PHP]


答:
Here is the solution using strtotime() function:

```<code>$today = time();
$tenMonthsLater = strtotime("+10 months", $today);
</code>```

and then convert the resulting timestamp to Date and time like this:

```<code>$dateToday = date('m-d-Y', $today);
$dateAfterTenMonths = date('m-d-Y', $tenMonthsLater);
</code>```

Hope this will help.

Body:
Here is the solution using strtotime() function:

$today = time();
$tenMonthsLater = strtotime("+10 months", $today);

and then convert the resulting timestamp to Date and time like this:

$dateToday = date('m-d-Y', $today);
$dateAfterTenMonths = date('m-d-Y', $tenMonthsLater);

Hope this will help.


问:
Node.js for loop
I'm developing a bot which asks series of questions. In my code here, the first question is printed 5 times (since 5 names are in the array) before going to the next question. What I would like to do is print the first question with first name in the array then go to the next question. What should I do?</p>

```<code> var members = list.members;

  for (var i = 0; i < members.length; i++) {
      console.log('actual person - ' + members[i].name);
      yesterday = function(res, convo) {
        convo.ask("You're up " + members[i].name + '. What did you do yesterday?', function(res, convo){
          today(res, convo);
          convo.next();
        });
      }
      today = function(res, convo){
        convo.ask('What do you plan on doing today?', function(res, convo){
          block(res, convo);
          convo.next();
        });
      }
      block = function(res, convo){
        convo.ask('Is there anything standing your way?', function(res, convo) {
          convo.next();
        });
      }
      bot.startConversation(message, yesterday);
    }
</code>```

答:
A for loop will not work in this case, since you have asynchronous callbacks. So you are in fact starting 5 conversations, and only then the callbacks are invoked.

It should also not be necessary to define your functions multiple times.

I don't know the API, but I would suggest to add another argument to your functions (i, the current member number), and chain back to the next conversation (providing i+1 when the third function executes. Something like this:

```<code>var members = list.members;

function yesterday(i, res, convo) {
    if (i >= members.length) return; // end
    console.log('actual person - ' + members[i].name);
    convo.ask("You're up " + members[i].name + '. What did you do yesterday?', function(res, convo){
        today(i, res, convo);
        convo.next();
    });
}

function today(i, res, convo){
    convo.ask('What do you plan on doing today?', function(res, convo){
        block(i, res, convo);
        convo.next();
    });
}

function block(i, res, convo){
    convo.ask('Is there anything standing your way?', function(res, convo) {
        // Start next conversation...
        yesterday(i+1, res, convo);
        convo.next();
        // Or, alternatively:
        // bot.startConversation(message, yesterday.bind(null, i+1));
    });
}

bot.startConversation(message, yesterday.bind(null, 0));
</code>```

Title: Node.js for loop

Body:
I'm developing a bot which asks series of questions. In my code here, the first question is printed 5 times (since 5 names are in the array) before going to the next question. What I would like to do is print the first question with first name in the array then go to the next question. What should I do?

 var members = list.members;

  for (var i = 0; i < members.length; i++) {
      console.log('actual person - ' + members[i].name);
      yesterday = function(res, convo) {
        convo.ask("You're up " + members[i].name + '. What did you do yesterday?', function(res, convo){
          today(res, convo);
          convo.next();
        });
      }
      today = function(res, convo){
        convo.ask('What do you plan on doing today?', function(res, convo){
          block(res, convo);
          convo.next();
        });
      }
      block = function(res, convo){
        convo.ask('Is there anything standing your way?', function(res, convo) {
          convo.next();
        });
      }
      bot.startConversation(message, yesterday);
    }

Body:
A for loop will not work in this case, since you have asynchronous callbacks. So you are in fact starting 5 conversations, and only then the callbacks are invoked.

It should also not be necessary to define your functions multiple times.

I don't know the API, but I would suggest to add another argument to your functions (i, the current member number), and chain back to the next conversation (providing i+1 when the third function executes. Something like this:

var members = list.members;

function yesterday(i, res, convo) {
    if (i >= members.length) return; // end
    console.log('actual person - ' + members[i].name);
    convo.ask("You're up " + members[i].name + '. What did you do yesterday?', function(res, convo){
        today(i, res, convo);
        convo.next();
    });
}

function today(i, res, convo){
    convo.ask('What do you plan on doing today?', function(res, convo){
        block(i, res, convo);
        convo.next();
    });
}

function block(i, res, convo){
    convo.ask('Is there anything standing your way?', function(res, convo) {
        // Start next conversation...
        yesterday(i+1, res, convo);
        convo.next();
        // Or, alternatively:
        // bot.startConversation(message, yesterday.bind(null, i+1));
    });
}

bot.startConversation(message, yesterday.bind(null, 0));


问:
UserControl with templates, change server-control rendered ID
TL;DR...

When creating a [UserControl] with single use templates, is it possible to get make server-side controls placed within those templates to render their id without the UserControl or container IDs?

In my ASP.NET web application I've create a UserControl with multiple single-use template (I've only given the code here for one of those templates)...

```<code>Public Class MyUserCtrl
    Inherits System.Web.UI.UserControl

    Private Class MyUserCtrlLiteralContainer
        Inherits Control
        Implements INamingContainer
    End Class

    <TemplateContainer(GetType(MyUserCtrlLiteralContainer)),
     TemplateInstance(TemplateInstance.Single),
     PersistenceMode(PersistenceMode.InnerProperty)>
    Public Property FirstTemplate As ITemplate

    Private Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Init
        If FirstTemplate IsNot Nothing Then
            Dim container As New MyUserCtrlLiteralContainer()
            FirstTemplate.InstantiateIn(container)
            plhFirst.Controls.Add(container)
        End If
    End Sub
End Class
</code>```

(Note, plhFirst is a <asp:PlaceHolder> in the mark-up)

This is an example of the control being used in a page (controlled by a Master page)...

```<code><asp:Content runat="server" ID="content" ContentPlaceHolderID="mainContent">
  <uc1:MyUserCtrl runat="server" id="muc1">
    <FirstTemplate>
      <asp:Button runat="server" id="btnMyButton" />
    </FirstTemplate>
  </uc1:MyUserCtrl>
</asp:Content>
</code>```

When the <asp:Button> is rendered to the HTML, the id of the element results in...

```<code>id="ctl00_content_muc1_ctl00_btnMyButton"
</code>```

... where the second ctl00 is the ID of the MyUserCtrlLiteralContainer instance.

Is there any way to make the id of the control render as follows?  (So the ID of the container is not used)

```<code>ctl00_content_muc1_btnMyButton
</code>```

Or even better, is there any way to make the id of the control render as follows? (So neither the ID of the usercontrol or container is used)

```<code>ctl00_content_btnMyButton
</code>```

Alternatively, is there a different way to instantiate the controls in the UserControl that would result in either of the above?

答:
The button id includes muc1 and ctl00 because UserControl and MyUserCtrlLiteralContainer implement INamingContainer. If you don’t want the id to include those parts, but you do want the id to include other ancestor IDs, then you can’t use those control types.

Removing ctl00: Unless you specifically need a custom container control, you can delete MyUserCtrlLiteralContainer and just instantiate the template directly in the PlaceHolder.

Removing muc1: You must rewrite your UserControl as a server control that doesn't implement INamingContainer.

Here’s a sample implementation:

<ParseChildren(True)>
Public Class MyUserCtrl
    Inherits Control

    Private plhFirst As PlaceHolder

    <TemplateInstance(TemplateInstance.Single),
     PersistenceMode(PersistenceMode.InnerProperty)>
    Public Property FirstTemplate As ITemplate

    Private Sub Page_Init(sender As Object, e As EventArgs) Handles MyBase.Init
        plhFirst = New PlaceHolder()
        Controls.Add(plhFirst)

        If FirstTemplate IsNot Nothing Then
            FirstTemplate.InstantiateIn(plhFirst)
        End If
    End Sub

    Protected Overrides Sub Render(writer As HtmlTextWriter)
        '

        writer.AddAttribute(HtmlTextWriterAttribute.Class, "myUserCtrl")
        writer.RenderBeginTag(HtmlTextWriterTag.Div)

        '

        writer.AddAttribute(HtmlTextWriterAttribute.Class, "firstControls")
        writer.RenderBeginTag(HtmlTextWriterTag.Div)

        plhFirst.RenderControl(writer)

        '

        writer.RenderEndTag()

        '

        writer.RenderEndTag()
    End Sub
End Class
```

Note: To avoid possible ID conflicts, I intentionally leave plhFirst.ID unset.

Body:
TL;DR...

When creating a [UserControl] with single use templates, is it possible to get make server-side controls placed within those templates to render their id without the UserControl or container IDs?

In my ASP.NET web application I've create a UserControl with multiple single-use template (I've only given the code here for one of those templates)...

Public Class MyUserCtrl
    Inherits System.Web.UI.UserControl

    Private Class MyUserCtrlLiteralContainer
        Inherits Control
        Implements INamingContainer
    End Class

    <TemplateContainer(GetType(MyUserCtrlLiteralContainer)),
     TemplateInstance(TemplateInstance.Single),
     PersistenceMode(PersistenceMode.InnerProperty)>
    Public Property FirstTemplate As ITemplate

    Private Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Init
        If FirstTemplate IsNot Nothing Then
            Dim container As New MyUserCtrlLiteralContainer()
            FirstTemplate.InstantiateIn(container)
            plhFirst.Controls.Add(container)
        End If
    End Sub
End Class

(Note, plhFirst is a <asp:PlaceHolder> in the mark-up)

This is an example of the control being used in a page (controlled by a Master page)...

<asp:Content runat="server" ID="content" ContentPlaceHolderID="mainContent">
  <uc1:MyUserCtrl runat="server" id="muc1">
    <FirstTemplate>
      <asp:Button runat="server" id="btnMyButton" />
    </FirstTemplate>
  </uc1:MyUserCtrl>
</asp:Content>

When the <asp:Button> is rendered to the HTML, the id of the element results in...

id="ctl00_content_muc1_ctl00_btnMyButton"

... where the second ctl00 is the ID of the MyUserCtrlLiteralContainer instance.

Is there any way to make the id of the control render as follows?  (So the ID of the container is not used)

ctl00_content_muc1_btnMyButton

Or even better, is there any way to make the id of the control render as follows? (So neither the ID of the usercontrol or container is used)

ctl00_content_btnMyButton

Alternatively, is there a different way to instantiate the controls in the UserControl that would result in either of the above?

Body:
The button id includes muc1 and ctl00 because UserControl and MyUserCtrlLiteralContainer implement INamingContainer. If you don’t want the id to include those parts, but you do want the id to include other ancestor IDs, then you can’t use those control types.

Removing ctl00: Unless you specifically need a custom container control, you can delete MyUserCtrlLiteralContainer and just instantiate the template directly in the PlaceHolder.

Removing muc1: You must rewrite your UserControl as a server control that doesn't implement INamingContainer.

Here’s a sample implementation:

<ParseChildren(True)>
Public Class MyUserCtrl
    Inherits Control

    Private plhFirst As PlaceHolder

    <TemplateInstance(TemplateInstance.Single),
     PersistenceMode(PersistenceMode.InnerProperty)>
    Public Property FirstTemplate As ITemplate

    Private Sub Page_Init(sender As Object, e As EventArgs) Handles MyBase.Init
        plhFirst = New PlaceHolder()
        Controls.Add(plhFirst)

        If FirstTemplate IsNot Nothing Then
            FirstTemplate.InstantiateIn(plhFirst)
        End If
    End Sub

    Protected Overrides Sub Render(writer As HtmlTextWriter)
        ' <div class="myUserCtrl">
        writer.AddAttribute(HtmlTextWriterAttribute.Class, "myUserCtrl")
        writer.RenderBeginTag(HtmlTextWriterTag.Div)

        ' <div class="firstControls">
        writer.AddAttribute(HtmlTextWriterAttribute.Class, "firstControls")
        writer.RenderBeginTag(HtmlTextWriterTag.Div)

        plhFirst.RenderControl(writer)

        ' </div>
        writer.RenderEndTag()

        ' </div>
        writer.RenderEndTag()
    End Sub
End Class

Note: To avoid possible ID conflicts, I intentionally leave plhFirst.ID unset.


问:
Javascript toFixed function
The expected result of:

```<code>(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18
</code>```

But in JS showing:

```<code>(1.175).toFixed(2) = 1.18 but
*(5.175).toFixed(2) = 5.17*
</code>```

How to rectify the problem?

答:
```<code>obj = {
    round(val) {
      const delta = 0.00001
      let num = val
      if (num - Math.floor(num) === 0.5) {
        num += delta
      }
      return Math.round(num + delta)
    },
  fixed(val, count = 0) {
      const power = Math.pow(10, count)
      let res = this.round(val * power) / power
      let arr = `${res}`.split('.')
      let addZero = ''
      for (let i = 0; i < count; i++) {
        addZero += '0'
      }
      if (count > 0) {
        arr[1] = ((arr[1] || '') + addZero).substr(0, count)
      }
      return arr.join('.')
  }
}
obj.fixed(5.175, 2)
</code>```

<p>// "5.18"</p>

Title: Javascript toFixed function

Body:
The expected result of:

(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18

But in JS showing:

(1.175).toFixed(2) = 1.18 but
*(5.175).toFixed(2) = 5.17*

How to rectify the problem?

Body:
obj = {
    round(val) {
      const delta = 0.00001
      let num = val
      if (num - Math.floor(num) === 0.5) {
        num += delta
      }
      return Math.round(num + delta)
    },
  fixed(val, count = 0) {
      const power = Math.pow(10, count)
      let res = this.round(val * power) / power
      let arr = `${res}`.split('.')
      let addZero = ''
      for (let i = 0; i < count; i++) {
        addZero += '0'
      }
      if (count > 0) {
        arr[1] = ((arr[1] || '') + addZero).substr(0, count)
      }
      return arr.join('.')
  }
}
obj.fixed(5.175, 2)

// "5.18"


问:
Restrict access to S3 hosted website without whitelisting ips
We have a website hosted on AWS S3 that we intend to be accessed only by a limited group of people. Right now, we are white listing the allowed IPs, as described in Restrict access to website hosted on S3.

However, some of the people that must have access to this website don't have static ips, which forces us to constantly update the whitelisted ips on the AWS policy.

I'm pretty sure something like client side certificates should work, but I have no idea how to implement that in terms of AIM policy. Any other (simpler) alternative that does not rely on the IPs being static? I'm guessing adding ssh keys to AWS wouldn't do any good in this case, right?

答:
One alternative approach is to setup user based access control. You can do this by using the following AWS services.

AWS Cognito UserPools

AWS API Gateway

AWS S3

The steps are as follows

Create a AWS Cognito UserPool

Create your users there with authenticated IAM role to allow API Gateway Execute.

Create a public login page in S3 with Cognito Login SDK

Setup API gateway and pass through to S3 AWS Service and also add Cognito UserPool authorizer creating requred IAM roles (Check this example)

After the setup, users should be able to login and access S3 through API Gateway.


问:
Doctrine Searchable Behavior vs Zend Lucene in symfony
I need to  search for keywords in 2 table, simple thing

I am undecided about using one or the other?
any suggestion performance wise?

Thanks!

答:
Lucene has been developed for fulltext search. Do you need this functionality?

If you need only keywords functionality use Searchable
Searchable is easer to use than Lucene.

Also consider to use sfDoctrineActAsTaggablePlugin

ContentLicense: CC BY-SA 2.5


问:
Subset data frame to include only levels of one factor that have values in both levels of another factor
I am working with a data frame that deals with numeric measurements. Some individuals have been measured several times, both as juveniles and adults.
A reproducible example:

```<code>ID <- c("a1", "a2", "a3", "a4", "a1", "a2", "a5", "a6", "a1", "a3")
age <- rep(c("juvenile", "adult"), each=5)
size <- rnorm(10)

# e.g. a1 is measured 3 times, twice as a juvenile, once as an adult.
d <- data.frame(ID, age, size)
</code>```

My goal is to subset that data frame by selecting the IDs that appear at least once as a juvenile and at least once as an adult. Not sure how to do that..?

The resulting dataframe would contain all measurements for individuals a1, a2 and a3, but would exclude a4, a5 and a6, as they were not measured at both stages.

A similar question was asked 7 months ago but never had an answer (Subset data frame to include only levels one factor that have values in both levels of another factor)

Thanks!

答:
split by age, intersect and subset:

```<code>d[d$ID %in% Reduce(intersect, split(d$ID, d$age)),]
#   ID      age        size
#1  a1 juvenile  1.44761836
#2  a2 juvenile  1.70098645
#3  a3 juvenile  0.08231986
#5  a1 juvenile  0.91240568
#6  a2    adult -1.77318962
#9  a1    adult  0.13597986
#10 a3    adult -1.18575294
</code>```

Body:
I am working with a data frame that deals with numeric measurements. Some individuals have been measured several times, both as juveniles and adults.
A reproducible example:

ID <- c("a1", "a2", "a3", "a4", "a1", "a2", "a5", "a6", "a1", "a3")
age <- rep(c("juvenile", "adult"), each=5)
size <- rnorm(10)

# e.g. a1 is measured 3 times, twice as a juvenile, once as an adult.
d <- data.frame(ID, age, size)

My goal is to subset that data frame by selecting the IDs that appear at least once as a juvenile and at least once as an adult. Not sure how to do that..?

The resulting dataframe would contain all measurements for individuals a1, a2 and a3, but would exclude a4, a5 and a6, as they were not measured at both stages.

A similar question was asked 7 months ago but never had an answer (Subset data frame to include only levels one factor that have values in both levels of another factor)

Thanks!

Body:
split by age, intersect and subset:

d[d$ID %in% Reduce(intersect, split(d$ID, d$age)),]
#   ID      age        size
#1  a1 juvenile  1.44761836
#2  a2 juvenile  1.70098645
#3  a3 juvenile  0.08231986
#5  a1 juvenile  0.91240568
#6  a2    adult -1.77318962
#9  a1    adult  0.13597986
#10 a3    adult -1.18575294


问:
SyntaxError: Unexpected token react-native init
Hello I am getting an issue when trying to run react-native init.

SyntaxError: Unexpected token ...

/Users/jordan/Projects/React/LiveInstagram/node_modules/metro-bundler/build/lib/TerminalClass.js:141
    this._nextStatusStr = util.format(format, ...args);

Does anyone know how I can remedy this issue? Thanks!

答: So I completely uninstalled Node then reinstalled it and react-native-cli and it worked correctly.


问:
How can cached value be invalidated in single thread?
I use the Http.Current.Cache to store various values retrieved from my database because my app is to data-intensive.  When running my website on my new laptop with VS2017 install (on another laptop with VS2015 I never see this problem), I'm seeing a very strange issue where cached values seem to be randomly cleared- almost in a way to defies logic.

For instance, I have an if clause whose condition is that the cache item in question is not null.  My code is definitely following the path through this if statement, but a couple of statements later the debugger shows that the cache item is in fact null- causing my app to fail.

```<code>public static SportSeason GetCurrentSportSeason(string sportCode)
{
  SportSeason sportSeason = null;
  string key = "Sheets_SportSeason_" + sportCode;

  int i = 0;
  if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
  {
    i = 1;
    sportSeason = (SportSeason)BizObject.Cache[key];
  }
  else
  {
    i = 2;
    sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
    BaseSheet.CacheData(key, sportSeason);
  }
  if(sportSeason == null)
  {
    int j = i;
  }
  return sportSeason;
}
</code>```

I can set a breakpoint in the final if and the variable i is set to 1, but the sportSeason object is NULL (as is the cache entry).  How can this be when the only way the code could have entered the first if clause is if the cache item was not null?

Here is a screenshot showing some watch variables with a breakpoint in the final if.

This is tough to track down because it happens randomly throughout my business objects.  Sometimes I have to refresh the page 3 or 4 times before I see this issues.

How can the cache be invalidated so quickly, and by what?  The screenshot shows that there aren't many cached items, so I don't think I'm running out of memory.  And no other processes are running which could be clobbering the cache.

EDIT:  Through more debugging I've determined that only the cache key that is checked on Line 91 is cleared (set to null) when it is checked again at the breakpoint.  All of the other cache records are still there.

EDIT2:  I've isolated the problem down to this, although it still seems to defy logic:

```<code>    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
    int i = 0;
</code>```

I clear all my cache.  When I step over the Cache.Insert statement, my cache count goes to 1.  However, the cached item according to that key remains null (see watch window).

Also, if I execute one more statement (the int i = 0), the cache count goes back to zero.

Edit3:  It's the AbsoluteExpiration parameter of the Insert() that is killing me.  Somehow a clock is off.

If I set the AbsoluteExpiration to 5 hours into the future (300 minutes), it doesn't work. If I set it to 5 hours and one minute (301 minutes) into the future, everything works.

```<code>    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);
</code>```

The clock on my laptop is 100% accurate and you can see the Intellisense shows the correct time as well.  Can the cache be based off of some other clock that is 5 hours off?

Edit4: Looks like someone else is off by 5 hours.

答:
The fix is to always use DateTime.UtcNow instead of DateTime.Now when specifying the AbsoluteExporation parameter.

Do this:

```<code>HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.UtcNow.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
</code>```

Not this:

```<code>HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);
</code>```

When I do this, it correctly recognizes that the cache is valid and I can retrieve the value. As to why this is required on my Windows 10 Pro laptop but not on my Windows 10 Home, I have no idea.

Body:
I use the Http.Current.Cache to store various values retrieved from my database because my app is to data-intensive.  When running my website on my new laptop with VS2017 install (on another laptop with VS2015 I never see this problem), I'm seeing a very strange issue where cached values seem to be randomly cleared- almost in a way to defies logic.

For instance, I have an if clause whose condition is that the cache item in question is not null.  My code is definitely following the path through this if statement, but a couple of statements later the debugger shows that the cache item is in fact null- causing my app to fail.

public static SportSeason GetCurrentSportSeason(string sportCode)
{
  SportSeason sportSeason = null;
  string key = "Sheets_SportSeason_" + sportCode;

  int i = 0;
  if (BaseSheet.Settings.EnableCaching && BizObject.Cache[key] != null)
  {
    i = 1;
    sportSeason = (SportSeason)BizObject.Cache[key];
  }
  else
  {
    i = 2;
    sportSeason = GetSportSeasonFromSportSeasonDetails(SiteProvider.Sheets.GetCurrentSportSeason(sportCode));
    BaseSheet.CacheData(key, sportSeason);
  }
  if(sportSeason == null)
  {
    int j = i;
  }
  return sportSeason;
}

I can set a breakpoint in the final if and the variable i is set to 1, but the sportSeason object is NULL (as is the cache entry).  How can this be when the only way the code could have entered the first if clause is if the cache item was not null?

Here is a screenshot showing some watch variables with a breakpoint in the final if.

This is tough to track down because it happens randomly throughout my business objects.  Sometimes I have to refresh the page 3 or 4 times before I see this issues.

How can the cache be invalidated so quickly, and by what?  The screenshot shows that there aren't many cached items, so I don't think I'm running out of memory.  And no other processes are running which could be clobbering the cache.

EDIT:  Through more debugging I've determined that only the cache key that is checked on Line 91 is cleared (set to null) when it is checked again at the breakpoint.  All of the other cache records are still there.

EDIT2:  I've isolated the problem down to this, although it still seems to defy logic:

    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddSeconds(600), TimeSpan.Zero);
    int i = 0;

I clear all my cache.  When I step over the Cache.Insert statement, my cache count goes to 1.  However, the cached item according to that key remains null (see watch window).

Also, if I execute one more statement (the int i = 0), the cache count goes back to zero.

Edit3:  It's the AbsoluteExpiration parameter of the Insert() that is killing me.  Somehow a clock is off.

If I set the AbsoluteExpiration to 5 hours into the future (300 minutes), it doesn't work. If I set it to 5 hours and one minute (301 minutes) into the future, everything works.

    HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(301), TimeSpan.Zero);

The clock on my laptop is 100% accurate and you can see the Intellisense shows the correct time as well.  Can the cache be based off of some other clock that is 5 hours off?

Edit4: Looks like someone else is off by 5 hours.

Body:
The fix is to always use DateTime.UtcNow instead of DateTime.Now when specifying the AbsoluteExporation parameter.

Do this:

HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.UtcNow.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);

Not this:

HttpContext.Current.Cache.Insert("ABC", "123", null, DateTime.Now.AddMinutes(1), System.Web.Caching.Cache.NoSlidingExpiration);

When I do this, it correctly recognizes that the cache is valid and I can retrieve the value. As to why this is required on my Windows 10 Pro laptop but not on my Windows 10 Home, I have no idea.