问:
Pygame Movement of Flag and Character With Walls
I am making a capture the flag type game. From the code below, I have the fundamentals set up. However, I don't know how I stop the flag from moving when the character hits a wall. Can anyone help me with this? As you can see if you run the code, the flag is effectively picked up by the character and carried but the flag will not stop if the character hits a wall. I want the flag to stay on the right side of the character as well. Thanks for any help. (CODE HAS BEEN UPDATED SINCE ORIGINAL POST)

```<code>import pygame
def start():
    pygame.init()
    BLUE = (0, 0, 128)
    RED = (204, 0, 0)
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    screen = pygame.display.set_mode((1920,1080), flags=pygame.FULLSCREEN)
    pygame.display.set_caption("Recovery")
    clock = pygame.time.Clock()
    bigJoe = pygame.image.load("bigJoe.png")
    characterSelected = bigJoe
    game(BLACK, WHITE, BLUE, RED, screen, clock, characterSelected, bigJoe)
def game(BLACK, WHITE, BLUE, RED, screen, clock, characterSelected, bigJoe):
    if characterSelected == bigJoe:
        gameCharacter = "gameJoe.png"
    all_sprite_list = pygame.sprite.Group()
    playerList = pygame.sprite.Group()
    wall_list = pygame.sprite.Group()
    flagList = pygame.sprite.Group()
    playerFlag = pygame.sprite.Group()
    flag = Flag(1810,540)
    flagList.add(flag)
'''Design of Map Below'''
    topWall = Wall(0, 0, 1920, 5, BLUE)
    bottomWall = Wall(0, 1075, 1920, 5, BLUE)
    leftWall = Wall(0, 0, 5, 1080, BLUE)
    rightWall = Wall(1915, 0, 5, 1080, BLUE)
    baseWall1 = Wall(5, 300, 150, 75, WHITE)
    baseWall2 = Wall(5, 375, 100, 330, WHITE)
    baseWall3 = Wall(5, 705, 150, 75, WHITE)
    baseSquare = Wall(30, 530, 40, 40, RED)
    wall1 = Wall(400, 400, 200, 300, RED)
    wall_list.add(topWall, bottomWall, leftWall, rightWall, baseWall1, wall1, baseWall2, baseWall3)
    all_sprite_list.add(topWall, bottomWall, leftWall, rightWall, baseWall1, wall1, baseWall2, baseWall3, baseSquare, flag)
'''Adding Character to Game'''
    player = Player(110, 550, gameCharacter)
    flag.player = playerFlag
    player.wall = wall_list
    all_sprite_list.add(player)
    playerFlag.add(player, flag)
    playerList.add(player)
    flag.player = player
    flag.carried = playerFlag
    flag.walls = wall_list
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            keys = pygame.key.get_pressed()
            if keys[pygame.K_ESCAPE]:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.changespeed(-3, 0)
                    flag.moveFlag(-3, 0)
                elif event.key == pygame.K_RIGHT:
                    player.changespeed(3, 0)
                    flag.moveFlag(3, 0)
                elif event.key == pygame.K_UP:
                    player.changespeed(0, -3)
                    flag.moveFlag(0, -3,)
                elif event.key == pygame.K_DOWN:
                    player.changespeed(0, 3)
                    flag.moveFlag(0, 3)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player.changespeed(3, 0)
                    flag.moveFlag(3, 0)
                elif event.key == pygame.K_RIGHT:
                    player.changespeed(-3, 0)
                    flag.moveFlag(-3, 0)
                elif event.key == pygame.K_UP:
                    player.changespeed(0, 3)
                    flag.moveFlag(0, 3)
                elif event.key == pygame.K_DOWN:
                    player.changespeed(0, -3)
                    flag.moveFlag(0, -3)
        all_sprite_list.update()
        screen.fill(BLACK)
        all_sprite_list.draw(screen)
        pygame.display.flip()
        clock.tick(75)

start()
</code>```

On a separate file

```<code>import pygame
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, gameCharacter):
        super().__init__()
        self.image = pygame.image.load(gameCharacter)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0
        self.wall = None

    def changespeed(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        self.rect.x += self.change_x
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_x > 0:
                self.rect.right = wall.rect.left
            else:
                self.rect.left = wall.rect.right
        self.rect.y += self.change_y
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_y > 0:
                self.rect.bottom = wall.rect.top
            else:
                self.rect.top = wall.rect.bottom

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height,color):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x

class Flag(pygame.sprite.Sprite):
    def __init__(self, x, y,):
        super().__init__()
        self.image = pygame.image.load("flag.png")
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0

    def moveFlag(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        hit = False
        allowMove = True
        flagCharacterList = pygame.sprite.spritecollide(self, self.carried, False)
        for i in flagCharacterList:
            if len(flagCharacterList) == 2:
                hit = True
            else:
                hit = False
        block_hit_list = pygame.sprite.groupcollide(self.walls, self.carried, False, False)
        for block in block_hit_list:
            if len(block_hit_list) == 1:
                allowMove = False
            else:
                allowMove = True
        if hit and allowMove:
            self.rect.x += self.change_x
            self.rect.y += self.change_y
</code>```

答:
The flag doesn't move bit itself. bit the player carries the flag. Possibly the player can carry more than 1 flag.

Remove the collision detection from the method Flag.update:

class Flag(pygame.sprite.Sprite):
    def __init__(self, x, y,):
        super().__init__()
        #self.image = pygame.image.load("flag.png")
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0

    def moveFlag(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        self.rect.x += self.change_x
        self.rect.y += self.change_y
```

<p>Add an attribute <code>self.flags</code> to the <code>player</code> and move all the flags contained in the list by the same amount as the player:</p>

<pre class="lang-py prettyprint-override"><code>class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, gameCharacter):
        # [...]

        self.flags = []

    # [...]

    def update(self):

        current_pos = (self.rect.x, self.rect.y)

        self.rect.x += self.change_x
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_x > 0:
                self.rect.right = wall.rect.left
            else:
                self.rect.left = wall.rect.right
        self.rect.y += self.change_y
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_y > 0:
                self.rect.bottom = wall.rect.top
            else:
                self.rect.top = wall.rect.bottom

        for flag in self.flags:
            flag.rect.x += self.rect.x - current_pos[0]
            flag.rect.y += self.rect.y - current_pos[1]
</code>```

flag.move() is not needed any more. But if the player hits the flag, then the flag is add player.flags. That caused, that the plyer carries the flag:

def game(BLACK, WHITE, BLUE, RED, screen, clock, characterSelected, bigJoe):
    # [...]

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            keys = pygame.key.get_pressed()
            if keys[pygame.K_ESCAPE]:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT: player.changespeed(-3, 0)
                elif event.key == pygame.K_RIGHT: player.changespeed(3, 0)
                elif event.key == pygame.K_UP: player.changespeed(0, -3)
                elif event.key == pygame.K_DOWN: player.changespeed(0, 3)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT: player.changespeed(3, 0)
                elif event.key == pygame.K_RIGHT: player.changespeed(-3, 0)
                elif event.key == pygame.K_UP: player.changespeed(0, 3)
                elif event.key == pygame.K_DOWN: player.changespeed(0, -3)

        if flag not in player.flags:
            if pygame.sprite.collide_rect(flag, player):
                player.flags.append(flag)
                flag.rect.left = player.rect.right

        # [...]
```

Body:
I am making a capture the flag type game. From the code below, I have the fundamentals set up. However, I don't know how I stop the flag from moving when the character hits a wall. Can anyone help me with this? As you can see if you run the code, the flag is effectively picked up by the character and carried but the flag will not stop if the character hits a wall. I want the flag to stay on the right side of the character as well. Thanks for any help. (CODE HAS BEEN UPDATED SINCE ORIGINAL POST)

import pygame
def start():
    pygame.init()
    BLUE = (0, 0, 128)
    RED = (204, 0, 0)
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    screen = pygame.display.set_mode((1920,1080), flags=pygame.FULLSCREEN)
    pygame.display.set_caption("Recovery")
    clock = pygame.time.Clock()
    bigJoe = pygame.image.load("bigJoe.png")
    characterSelected = bigJoe
    game(BLACK, WHITE, BLUE, RED, screen, clock, characterSelected, bigJoe)
def game(BLACK, WHITE, BLUE, RED, screen, clock, characterSelected, bigJoe):
    if characterSelected == bigJoe:
        gameCharacter = "gameJoe.png"
    all_sprite_list = pygame.sprite.Group()
    playerList = pygame.sprite.Group()
    wall_list = pygame.sprite.Group()
    flagList = pygame.sprite.Group()
    playerFlag = pygame.sprite.Group()
    flag = Flag(1810,540)
    flagList.add(flag)
'''Design of Map Below'''
    topWall = Wall(0, 0, 1920, 5, BLUE)
    bottomWall = Wall(0, 1075, 1920, 5, BLUE)
    leftWall = Wall(0, 0, 5, 1080, BLUE)
    rightWall = Wall(1915, 0, 5, 1080, BLUE)
    baseWall1 = Wall(5, 300, 150, 75, WHITE)
    baseWall2 = Wall(5, 375, 100, 330, WHITE)
    baseWall3 = Wall(5, 705, 150, 75, WHITE)
    baseSquare = Wall(30, 530, 40, 40, RED)
    wall1 = Wall(400, 400, 200, 300, RED)
    wall_list.add(topWall, bottomWall, leftWall, rightWall, baseWall1, wall1, baseWall2, baseWall3)
    all_sprite_list.add(topWall, bottomWall, leftWall, rightWall, baseWall1, wall1, baseWall2, baseWall3, baseSquare, flag)
'''Adding Character to Game'''
    player = Player(110, 550, gameCharacter)
    flag.player = playerFlag
    player.wall = wall_list
    all_sprite_list.add(player)
    playerFlag.add(player, flag)
    playerList.add(player)
    flag.player = player
    flag.carried = playerFlag
    flag.walls = wall_list
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            keys = pygame.key.get_pressed()
            if keys[pygame.K_ESCAPE]:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.changespeed(-3, 0)
                    flag.moveFlag(-3, 0)
                elif event.key == pygame.K_RIGHT:
                    player.changespeed(3, 0)
                    flag.moveFlag(3, 0)
                elif event.key == pygame.K_UP:
                    player.changespeed(0, -3)
                    flag.moveFlag(0, -3,)
                elif event.key == pygame.K_DOWN:
                    player.changespeed(0, 3)
                    flag.moveFlag(0, 3)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player.changespeed(3, 0)
                    flag.moveFlag(3, 0)
                elif event.key == pygame.K_RIGHT:
                    player.changespeed(-3, 0)
                    flag.moveFlag(-3, 0)
                elif event.key == pygame.K_UP:
                    player.changespeed(0, 3)
                    flag.moveFlag(0, 3)
                elif event.key == pygame.K_DOWN:
                    player.changespeed(0, -3)
                    flag.moveFlag(0, -3)
        all_sprite_list.update()
        screen.fill(BLACK)
        all_sprite_list.draw(screen)
        pygame.display.flip()
        clock.tick(75)

start()

On a separate file

import pygame
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, gameCharacter):
        super().__init__()
        self.image = pygame.image.load(gameCharacter)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0
        self.wall = None

    def changespeed(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        self.rect.x += self.change_x
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_x > 0:
                self.rect.right = wall.rect.left
            else:
                self.rect.left = wall.rect.right
        self.rect.y += self.change_y
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_y > 0:
                self.rect.bottom = wall.rect.top
            else:
                self.rect.top = wall.rect.bottom

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height,color):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x

class Flag(pygame.sprite.Sprite):
    def __init__(self, x, y,):
        super().__init__()
        self.image = pygame.image.load("flag.png")
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0

    def moveFlag(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        hit = False
        allowMove = True
        flagCharacterList = pygame.sprite.spritecollide(self, self.carried, False)
        for i in flagCharacterList:
            if len(flagCharacterList) == 2:
                hit = True
            else:
                hit = False
        block_hit_list = pygame.sprite.groupcollide(self.walls, self.carried, False, False)
        for block in block_hit_list:
            if len(block_hit_list) == 1:
                allowMove = False
            else:
                allowMove = True
        if hit and allowMove:
            self.rect.x += self.change_x
            self.rect.y += self.change_y

Body:
The flag doesn't move bit itself. bit the player carries the flag. Possibly the player can carry more than 1 flag.

Remove the collision detection from the method Flag.update:

class Flag(pygame.sprite.Sprite):
    def __init__(self, x, y,):
        super().__init__()
        #self.image = pygame.image.load("flag.png")
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0

    def moveFlag(self, x, y):
        self.change_x += x
        self.change_y += y

    def update(self):
        self.rect.x += self.change_x
        self.rect.y += self.change_y

Add an attribute self.flags to the player and move all the flags contained in the list by the same amount as the player:

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, gameCharacter):
        # [...]

        self.flags = []

    # [...]

    def update(self):

        current_pos = (self.rect.x, self.rect.y)

        self.rect.x += self.change_x
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_x > 0:
                self.rect.right = wall.rect.left
            else:
                self.rect.left = wall.rect.right
        self.rect.y += self.change_y
        wallHitList = pygame.sprite.spritecollide(self, self.wall, False)
        for wall in wallHitList:
            if self.change_y > 0:
                self.rect.bottom = wall.rect.top
            else:
                self.rect.top = wall.rect.bottom

        for flag in self.flags:
            flag.rect.x += self.rect.x - current_pos[0]
            flag.rect.y += self.rect.y - current_pos[1]

flag.move() is not needed any more. But if the player hits the flag, then the flag is add player.flags. That caused, that the plyer carries the flag:

def game(BLACK, WHITE, BLUE, RED, screen, clock, characterSelected, bigJoe):
    # [...]

    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            keys = pygame.key.get_pressed()
            if keys[pygame.K_ESCAPE]:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT: player.changespeed(-3, 0)
                elif event.key == pygame.K_RIGHT: player.changespeed(3, 0)
                elif event.key == pygame.K_UP: player.changespeed(0, -3)
                elif event.key == pygame.K_DOWN: player.changespeed(0, 3)
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT: player.changespeed(3, 0)
                elif event.key == pygame.K_RIGHT: player.changespeed(-3, 0)
                elif event.key == pygame.K_UP: player.changespeed(0, 3)
                elif event.key == pygame.K_DOWN: player.changespeed(0, -3)

        if flag not in player.flags:
            if pygame.sprite.collide_rect(flag, player):
                player.flags.append(flag)
                flag.rect.left = player.rect.right

        # [...]


来源: stackexchange

问:
Remove the aspxerrorpath param with CustomErrors use ResponseRewrite
I'm using asp.net MVC4 + visual studio 2012. every thing all fine, But only the custom error always has the aspxerrorpath param on the URL.

I already config the custom error on web.config:

```<code><customErrors mode="On" defaultRedirect="~/Error/Error">
  <error redirect="~/Error/Error" statusCode="404" />
  <error redirect="~/Error/Error" statusCode="500" />
</customErrors>
</code>```

I also changed my Error Action to :

```<code>public ActionResult Error()
{
    Response.Status = "404 Not Found";
    Response.StatusCode = 404;
    return View();
}
</code>```

Will now when there is some 404 happening. I always got aspxerrorpath param on my URL.
I tried add redirectMode="ResponseRewrite" to the customError nodes but If add this , the error will display a run time exception.....

So Is there any best way to remove the aspxerrorpath param? Thanks.

答:
The absolute simplest solution is to use a blank querystring in the defaultRedirect in web.config to override (note the question mark):</p>

```<code><system.web>
    <customErrors defaultRedirect="~/error?" mode="On" />
</system.web>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using asp.net MVC4 + visual studio 2012. every thing all fine, But only the custom error always has the aspxerrorpath param on the URL.

I already config the custom error on web.config:

<customErrors mode="On" defaultRedirect="~/Error/Error">
  <error redirect="~/Error/Error" statusCode="404" />
  <error redirect="~/Error/Error" statusCode="500" />
</customErrors>

I also changed my Error Action to :

public ActionResult Error()
{
    Response.Status = "404 Not Found";
    Response.StatusCode = 404;
    return View();
}

Will now when there is some 404 happening. I always got aspxerrorpath param on my URL.
I tried add redirectMode="ResponseRewrite" to the customError nodes but If add this , the error will display a run time exception.....

So Is there any best way to remove the aspxerrorpath param? Thanks.

Body:
The absolute simplest solution is to use a blank querystring in the defaultRedirect in web.config to override (note the question mark):

<system.web>
    <customErrors defaultRedirect="~/error?" mode="On" />
</system.web>

ContentLicense: CC BY-SA 4.0


问:
Vuetify - Changing v-tabs via key
I have a vuetify tab component which includes a menu and a lot of different tabs which can show up in a random order. It seems like the v-tab toggling works via index-based. How can a vuetify v-tab be toggled to the correct tab via key/unique Id?

Example:

```<code> <v-tabs v-model="tab">
   <v-tab href="#tab-myUniqueKeyOne">TEST ONE</v-tab>
   <v-menu>
     <template v-slot:activator="{ on }">
       <v-btn text v-on="on">DROPDOWN_TAB</v-btn>
     </template>
     <v-list>
       <v-list-item @click="changeToTab('tab-foo')">Foo</v-list-item>
       <v-list-item @click="changeToTab('tab-bar')">Bar</v-list-item>
     </v-list>
   </v-menu>
   <v-tab href="#tab-myUniqueKeyThree">TEST THREE</v-tab>
   <v-tab href="#tab-myUniqueKeyTwo">TEST TWO</v-tab>
 </v-tabs>
 <v-tabs-items v-model="tab">
   <v-tab-item value="tab-foo">My Foo</v-tab-item>
   <v-tab-item value="tab-baz">Some Hidden Tab</v-tab-item>
   <v-tab-item value="tab-myUniqueKeyTwo">Two</v-tab-item>
   <v-tab-item value="tab-bar">My Bar</v-tab-item>
   <v-tab-item value="tab-myUniqueKeyThree">Three</v-tab-item>
   <v-tab-item value="tab-myUniqueKeyOne">One</v-tab-item>
 </v-tabs-items>

 data: () => {
   tab: null,
 }
 methods: {
   changeToTab(tab) {
     this.tab = tab;
   }
 }
</code>```

答:
Below is a simplified example. Bottom line, use href in the tabs and value in tab-items

https://codepen.io/jack3625/pen/xxwopad

Title: Vuetify - Changing v-tabs via key

Body:
I have a vuetify tab component which includes a menu and a lot of different tabs which can show up in a random order. It seems like the v-tab toggling works via index-based. How can a vuetify v-tab be toggled to the correct tab via key/unique Id?

Example:

 <v-tabs v-model="tab">
   <v-tab href="#tab-myUniqueKeyOne">TEST ONE</v-tab>
   <v-menu>
     <template v-slot:activator="{ on }">
       <v-btn text v-on="on">DROPDOWN_TAB</v-btn>
     </template>
     <v-list>
       <v-list-item @click="changeToTab('tab-foo')">Foo</v-list-item>
       <v-list-item @click="changeToTab('tab-bar')">Bar</v-list-item>
     </v-list>
   </v-menu>
   <v-tab href="#tab-myUniqueKeyThree">TEST THREE</v-tab>
   <v-tab href="#tab-myUniqueKeyTwo">TEST TWO</v-tab>
 </v-tabs>
 <v-tabs-items v-model="tab">
   <v-tab-item value="tab-foo">My Foo</v-tab-item>
   <v-tab-item value="tab-baz">Some Hidden Tab</v-tab-item>
   <v-tab-item value="tab-myUniqueKeyTwo">Two</v-tab-item>
   <v-tab-item value="tab-bar">My Bar</v-tab-item>
   <v-tab-item value="tab-myUniqueKeyThree">Three</v-tab-item>
   <v-tab-item value="tab-myUniqueKeyOne">One</v-tab-item>
 </v-tabs-items>

 data: () => {
   tab: null,
 }
 methods: {
   changeToTab(tab) {
     this.tab = tab;
   }
 }


问:
SQL Query to retrieve values inside tags(child nodes) from a XML data in SnowFlake
I have a XML(edited) File with the following data:

```<code><dept dept_id="1" dept_name="Marketing">
     <progress>1</progress>
    <employee empname="a">
         <end> 1 </end>
        <address addr1="123 abc">
        ...
        </address>
    </employee>
</dept>
<dept dept_id="2" dept_name="Sales">
    <progress>1</progress>
    <employee empname="b">
        <end> 1 </end>
        <address addr1="456 cde">
        ...
        </address>
    </employee>
</dept>
</code>```

I put this file in AWS S3 and then used 'copy into' to transfer this data into a external table in snowflake in a variant column. Like Below:

```<code>  copy into DB.AWS_S3_STAGE_SCHEMA.test_XML_copy
  from @AWS_S3_LANDING/websiteXML/Test_xml.xml
  FILE_FORMAT = ( TYPE =  XML STRIP_OUTER_ELEMENT = TRUE  )  ;
</code>```

Now, I can query the data from this table and retrieve data like 'marketing' and 'sales', which are inside tags using the following query(I got the syntax from snowflake docs and used it. ):

```<code>SELECT
    GET(xmldata, '@dept_id')::integer as dept_id,
    GET(xmldata, '@dept_name')::string as dept_name
FROM test_XML_copy;
</code>```

But, I cannot query the data inside tags which are in child nodes. For example: I need data like 'a' and '123 abc'.
If anybody can help me in this query, that would be appreciated.

答:
To extract data from the child nodes you will need to use LATERAL FLATTEN to transform the data, e.g. to flatten the <employee> element and get the emp_name attribute:

```<code>select
       XMLGET( xmldata, '@dept_id' ):"$"::string AS dept_id
     , XMLGET( xmldata, '@dept_name' ):"$"::string AS dept_name
     , XMLGET( emp.value, '@empname' ):"$"::string as empname
from
    test_XML_copy
    ,  lateral FLATTEN(test_XML_copy.xmldata:"$") emp
  where emp.value like '<employee>%'
  order by dept_id, empname;
</code>```

This article has some very useful info on querying XML in Snowflake: https://community.snowflake.com/s/article/Querying-Nested-XML-in-Snowflake

Body:
I have a XML(edited) File with the following data:

<dept dept_id="1" dept_name="Marketing">
     <progress>1</progress>
    <employee empname="a">
         <end> 1 </end>
        <address addr1="123 abc">
        ...
        </address>
    </employee>
</dept>
<dept dept_id="2" dept_name="Sales">
    <progress>1</progress>
    <employee empname="b">
        <end> 1 </end>
        <address addr1="456 cde">
        ...
        </address>
    </employee>
</dept>

I put this file in AWS S3 and then used 'copy into' to transfer this data into a external table in snowflake in a variant column. Like Below:

  copy into DB.AWS_S3_STAGE_SCHEMA.test_XML_copy
  from @AWS_S3_LANDING/websiteXML/Test_xml.xml
  FILE_FORMAT = ( TYPE =  XML STRIP_OUTER_ELEMENT = TRUE  )  ;

Now, I can query the data from this table and retrieve data like 'marketing' and 'sales', which are inside tags using the following query(I got the syntax from snowflake docs and used it. ):

SELECT
    GET(xmldata, '@dept_id')::integer as dept_id,
    GET(xmldata, '@dept_name')::string as dept_name
FROM test_XML_copy;

But, I cannot query the data inside tags which are in child nodes. For example: I need data like 'a' and '123 abc'.
If anybody can help me in this query, that would be appreciated.

Body:
To extract data from the child nodes you will need to use LATERAL FLATTEN to transform the data, e.g. to flatten the <employee> element and get the emp_name attribute:

select
       XMLGET( xmldata, '@dept_id' ):"$"::string AS dept_id
     , XMLGET( xmldata, '@dept_name' ):"$"::string AS dept_name
     , XMLGET( emp.value, '@empname' ):"$"::string as empname
from
    test_XML_copy
    ,  lateral FLATTEN(test_XML_copy.xmldata:"$") emp
  where emp.value like '<employee>%'
  order by dept_id, empname;

This article has some very useful info on querying XML in Snowflake: https://community.snowflake.com/s/article/Querying-Nested-XML-in-Snowflake


问:
I can't make a query select into in 2 table
"Make a query that having all orders by employees from employeeUK in the orderUK table"

my table of employeeUK:

```<code>select *
into employeeUK
from Employees
where Country = 'UK'
</code>```

then i want to make the orderUK table but i got confuse because my query always error.
How the query should be?

答:
The question is are you creating a Temp Table to a Perm table.  Does the Table already exist or not.

If you are creating a temp table use the following

```<code>Select *
Into #employeeUK
From Employees
Where Country = 'UK'
</code>```

If this is going into a Perm table you can use the same code as long as the table does not already exist.

If the table already exist then use this code.

```<code>Insert Into employeeUK
Select *
From Employees
Where Country = 'UK'
</code>```

Remember Temp Tables start with a '#' perm tables do not.

Body:
"Make a query that having all orders by employees from employeeUK in the orderUK table"

my table of employeeUK:

select *
into employeeUK
from Employees
where Country = 'UK'

then i want to make the orderUK table but i got confuse because my query always error.
How the query should be?

Body:
The question is are you creating a Temp Table to a Perm table.  Does the Table already exist or not.

If you are creating a temp table use the following

Select *
Into #employeeUK
From Employees
Where Country = 'UK'

If this is going into a Perm table you can use the same code as long as the table does not already exist.

If the table already exist then use this code.

Insert Into employeeUK
Select *
From Employees
Where Country = 'UK'

Remember Temp Tables start with a '#' perm tables do not.


问:
How do I use C++ STL list without iterator?
I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?</p>

答:
You could go ahead and use Nemanja Trifunovic idea. By using two lists you could "traverse" the list by popping an element from the front of the "original" list and pushing it at the end of the second "helper" list - having something like this:

```<code>[] [1, 2, 3, 4, 5]
    ^
[1] [2, 3, 4, 5]
     ^
[1, 2] [3, 4, 5]
        ^
[1, 2, 3] [4, 5]
           ^
[1, 2, 3, 4] [5]
              ^
</code>```

And your supposed "clever" avoidance of iterators would work like a bidirectional iterator, pretty much. ^ shows the "current" element.
Of course you'd probably make it into a class or whatnot...

The question is - is it really worth it? Just using an iterator would be much simpler (not to mention it's already implemented).

Body:
You could go ahead and use Nemanja Trifunovic idea. By using two lists you could "traverse" the list by popping an element from the front of the "original" list and pushing it at the end of the second "helper" list - having something like this:

[] [1, 2, 3, 4, 5]
    ^
[1] [2, 3, 4, 5]
     ^
[1, 2] [3, 4, 5]
        ^
[1, 2, 3] [4, 5]
           ^
[1, 2, 3, 4] [5]
              ^

And your supposed "clever" avoidance of iterators would work like a bidirectional iterator, pretty much. ^ shows the "current" element.
Of course you'd probably make it into a class or whatnot...

The question is - is it really worth it? Just using an iterator would be much simpler (not to mention it's already implemented).


问:
Unittest tests order
How can I be sure of the unittest methods' order? Is the alphabetical or numeric prefixes the proper way?

```<code>class TestFoo(TestCase):
    def test_1(self):
        ...
    def test_2(self):
        ...
</code>```

or

```<code>class TestFoo(TestCase):
    def test_a(self):
        ...
    def test_b(self):
        ...
</code>```

答:
Here is a simpler method that has the following advantages:

No need to create a custom TestCase class.

No need to decorate every test method.

Use the unittest standard load test protocol. See the Python docs here.

The idea is to go through all the test cases of the test suites given to the test loader protocol and create a new suite but with the tests ordered by their line number.

Here is the code:

```<code>import unittest

def load_ordered_tests(loader, standard_tests, pattern):
    """
    Test loader that keeps the tests in the order they were declared in the class.
    """
    ordered_cases = []
    for test_suite in standard_tests:
        ordered = []
        for test_case in test_suite:
            test_case_type = type(test_case)
            method_name = test_case._testMethodName
            testMethod = getattr(test_case, method_name)
            line = testMethod.__code__.co_firstlineno
            ordered.append( (line, test_case_type, method_name) )
        ordered.sort()
        for line, case_type, name in ordered:
            ordered_cases.append(case_type(name))
    return unittest.TestSuite(ordered_cases)
</code>```

You can put this in a module named order_tests and then in each unittest Python file, declare the test loader like this:

```<code>from order_tests import load_ordered_tests

# This orders the tests to be run in the order they were declared.
# It uses the unittest load_tests protocol.
load_tests = load_ordered_tests
</code>```

Note: the often suggested technique of setting the test sorter to None no longer works because Python now sorts the output of dir() and unittest uses dir() to find tests. So even though you have no sorting method, they still get sorted by Python itself!

Title: Unittest tests order

Body:
How can I be sure of the unittest methods' order? Is the alphabetical or numeric prefixes the proper way?

class TestFoo(TestCase):
    def test_1(self):
        ...
    def test_2(self):
        ...

or

class TestFoo(TestCase):
    def test_a(self):
        ...
    def test_b(self):
        ...

Body:
Here is a simpler method that has the following advantages:

No need to create a custom TestCase class.

No need to decorate every test method.

Use the unittest standard load test protocol. See the Python docs here.

The idea is to go through all the test cases of the test suites given to the test loader protocol and create a new suite but with the tests ordered by their line number.

Here is the code:

import unittest

def load_ordered_tests(loader, standard_tests, pattern):
    """
    Test loader that keeps the tests in the order they were declared in the class.
    """
    ordered_cases = []
    for test_suite in standard_tests:
        ordered = []
        for test_case in test_suite:
            test_case_type = type(test_case)
            method_name = test_case._testMethodName
            testMethod = getattr(test_case, method_name)
            line = testMethod.__code__.co_firstlineno
            ordered.append( (line, test_case_type, method_name) )
        ordered.sort()
        for line, case_type, name in ordered:
            ordered_cases.append(case_type(name))
    return unittest.TestSuite(ordered_cases)

You can put this in a module named order_tests and then in each unittest Python file, declare the test loader like this:

from order_tests import load_ordered_tests

# This orders the tests to be run in the order they were declared.
# It uses the unittest load_tests protocol.
load_tests = load_ordered_tests

Note: the often suggested technique of setting the test sorter to None no longer works because Python now sorts the output of dir() and unittest uses dir() to find tests. So even though you have no sorting method, they still get sorted by Python itself!


问:
Sieve of Eratosthenes - bitwise optimization problem
I guess every one of you has encountered the optimization code of Eratosthenes sieve with bitwise operations. I am trying to wrap my head around it and I have a question on one of the operations in this implementation. Here is the code from GeeksforGeeks:

bool ifnotPrime(int prime[], int x) {
    // checking whether the value of element
    // is set or not. Using prime[x/64], we find
    // the slot in prime array. To find the bit
    // number, we divide x by 2 and take its mod
    // with 32.
    return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}

// Marks x composite in prime[]
bool makeComposite(int prime[], int x) {
    // Set a bit corresponding to given element.
    // Using prime[x/64], we find the slot in prime
    // array. To find the bit number, we divide x
    // by 2 and take its mod with 32.
    prime[x / 64] |= (1 << ((x >> 1) & 31));
}

// Prints all prime numbers smaller than n.
void bitWiseSieve(int n) {
    // Assuming that n takes 32 bits, we reduce
    // size to n/64 from n/2.
    int prime[n / 64];

    // Initializing values to 0 .
    memset(prime, 0, sizeof(prime));

    // 2 is the only even prime so we can ignore that
    // loop starts from 3 as we have used in sieve of
    // Eratosthenes .
    for (int i = 3; i * i <= n; i += 2) {

        // If i is prime, mark all its multiples as
        // composite
        if (!ifnotPrime(prime, i))
            for (int j = i * i, k = i << 1; j < n; j += k)
                makeComposite(prime, j);
    }

    // writing 2 separately
    printf("2 ");

    // Printing other primes
    for (int i = 3; i <= n; i += 2)
        if (!ifnotPrime(prime, i))
            printf("%d ", i);
}

// Driver code
int main() {
    int n = 30;
    bitWiseSieve(n);
    return 0;
}
```

So my questions are:

what is the meaning of (prime[x/64] & (1 << ((x >> 1) & 31)) and more specifically (1 << ((x >> 1) & 31));

in prime[x/64] why do we divide by 64 and not with 32, when we work with  32 bit integer;

Is int prime[n/64] correct if n < 64?

答:
There are multiple problems in the code:

makeComposite() should have return type void.

(1 << ((x >> 1) & 31)) has undefined behavior if x == 63 because 1 << 31 overflows the range of type int. You should use 1U or preferably 1UL to ensure 32 bits.

it would be simpler to shift the table entry and mask the last bit: return (prime[x / 64] >> ((x >> 1) & 31)) & 1;

instead of assuming that type int has 32 bits, you should use uint32_t as the type for the bit array.

the array int prime[n / 64]; is too short if n is not a multiple of 64. Use uint32_t prime[n / 64 + 1]; instead. This is a problem for your example as n = 30, so the array is created with a length of 0.

ifnotPrime(n) only returns a valid result for odd values. It might be better and more readable to change this function and name it isOddPrime().

Regarding your questions:

what is the meaning of (prime[x/64] & (1 << ((x >> 1) & 31)) and more specifically (1 << ((x >> 1) & 31))?

x is first divided by 2 (shift right one position) because only odd numbers have a bit in the array, then the result is masked with 31 to keep the 5 low order bits as the bit number in the word. For any unsigned value x, x & 31 is equivalent to x % 32. x / 64 is the word number where to test this bit.

As mentioned above, 1 is an int and thus should not be shifted left by 31 positions. Using 1UL ensures that the type has at least 32 bits and can be shifted by 31 positions.

in prime[x/64] why do we divide by 64 and not with 32, when we work with 32-bit integer?

The bits in the array correspond to odd numbers, so a 32-bit word contains primeness information for 64 numbers: 32 even numbers that are known to be composite and 32 odd numbers for which the corresponding bit it set if the number is composite.

Is int prime[n/64] correct if n < 64?

Not it is not, it is incorrect if n is not a multiple of 64: the size expression should be (n + 63) / 64, or better int prime[n/64 + 1]

Here is a modified version, where you can pass a command line argument:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

bool isOddPrime(const uint32_t prime[], unsigned x) {
    // checking whether the value of element
    // is set or not. Using prime[x/64], we find
    // the slot in prime array. To find the bit
    // number, we divide x by 2 and take its mod
    // with 32.
    return 1 ^ ((prime[x / 64] >> ((x >> 1) & 31)) & 1);
}

// Marks x composite in prime[]
void makeComposite(uint32_t prime[], unsigned x) {
    // Set a bit corresponding to given element.
    // Using prime[x/64], we find the slot in prime
    // array. To find the bit number, we divide x
    // by 2 and take its mod with 32.
    prime[x / 64] |= (1UL << ((x >> 1) & 31));
}

// Prints all prime numbers smaller than n.
void bitWiseSieve(unsigned n) {
    // Assuming that n takes 32 bits, we reduce
    // size to n/64 from n/2.
    uint32_t prime[n / 64 + 1];

    // Initializing values to 0 .
    memset(prime, 0, sizeof(prime));

    // 2 is the only even prime so we can ignore that
    // loop starts from 3 as we have used in sieve of
    // Eratosthenes .
    for (unsigned i = 3; i * i <= n; i += 2) {
        // If i is prime, mark all its multiples as composite
        if (isOddPrime(prime, i)) {
            for (unsigned j = i * i, k = i << 1; j < n; j += k)
                makeComposite(prime, j);
        }
    }

    // writing 2 separately
    if (n >= 2)
        printf("2\n");

    // Printing other primes
    for (unsigned i = 3; i <= n; i += 2) {
        if (isOddPrime(prime, i))
            printf("%u\n", i);
    }
}

// Driver code
int main(int argc, char *argv[]) {
    unsigned n = argc > 1 ? strtol(argv[1], NULL, 0) : 1000;
    bitWiseSieve(n);
    return 0;
}
```

Body:
I guess every one of you has encountered the optimization code of Eratosthenes sieve with bitwise operations. I am trying to wrap my head around it and I have a question on one of the operations in this implementation. Here is the code from GeeksforGeeks:

bool ifnotPrime(int prime[], int x) {
    // checking whether the value of element
    // is set or not. Using prime[x/64], we find
    // the slot in prime array. To find the bit
    // number, we divide x by 2 and take its mod
    // with 32.
    return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}

// Marks x composite in prime[]
bool makeComposite(int prime[], int x) {
    // Set a bit corresponding to given element.
    // Using prime[x/64], we find the slot in prime
    // array. To find the bit number, we divide x
    // by 2 and take its mod with 32.
    prime[x / 64] |= (1 << ((x >> 1) & 31));
}

// Prints all prime numbers smaller than n.
void bitWiseSieve(int n) {
    // Assuming that n takes 32 bits, we reduce
    // size to n/64 from n/2.
    int prime[n / 64];

    // Initializing values to 0 .
    memset(prime, 0, sizeof(prime));

    // 2 is the only even prime so we can ignore that
    // loop starts from 3 as we have used in sieve of
    // Eratosthenes .
    for (int i = 3; i * i <= n; i += 2) {

        // If i is prime, mark all its multiples as
        // composite
        if (!ifnotPrime(prime, i))
            for (int j = i * i, k = i << 1; j < n; j += k)
                makeComposite(prime, j);
    }

    // writing 2 separately
    printf("2 ");

    // Printing other primes
    for (int i = 3; i <= n; i += 2)
        if (!ifnotPrime(prime, i))
            printf("%d ", i);
}

// Driver code
int main() {
    int n = 30;
    bitWiseSieve(n);
    return 0;
}

So my questions are:

what is the meaning of (prime[x/64] & (1 << ((x >> 1) & 31)) and more specifically (1 << ((x >> 1) & 31));

in prime[x/64] why do we divide by 64 and not with 32, when we work with  32 bit integer;

Is int prime[n/64] correct if n < 64?


问:
send subscription response as parameter to method Angular/rxJs
I Have a subscription like below in my Child-Component.

```<code>ngOnInit{
    this.subscription = this._cs.recieveData.subscribe((res) => {
    this.data= res;
  });
    UseDatafromSubs(this.data){
    //do Something
    }
}
</code>```

I have another method in child-Component like above (UseDatafromSubs) which accepts my subscription response as parameter:

In my ParentComponent i am updating the service like below:

```<code>senddata(){
     this._cs.send(sendData);
}
</code>```

I am able to send and receive updated Data from Parent to Child, but my useDataFromSubs is not being called when the new subscription data comes,to use the data, its not taking the subscription response as parameter. I tried using add method like below:

```<code> this.subscription = this._cs.recieveData.subscribe((res) => {
    this.data= res;
  }).add(()=>this.UseDatafromSubs(this.data));
</code>```

but no use.

can somebody please help.

Thanks in Advance.

答:
Can you just call the method you want inside the subscribe block?
e.g.</p>

```<code>ngOnInit{
    this.subscription = this._cs.recieveData.subscribe((res) => {
    this.data= res;
    this.UseDatafromSubs(res);
  })
}
</code>```

Body:
I Have a subscription like below in my Child-Component.

ngOnInit{
    this.subscription = this._cs.recieveData.subscribe((res) => {
    this.data= res;
  });
    UseDatafromSubs(this.data){
    //do Something
    }
}

I have another method in child-Component like above (UseDatafromSubs) which accepts my subscription response as parameter:

In my ParentComponent i am updating the service like below:

senddata(){
     this._cs.send(sendData);
}

I am able to send and receive updated Data from Parent to Child, but my useDataFromSubs is not being called when the new subscription data comes,to use the data, its not taking the subscription response as parameter. I tried using add method like below:

 this.subscription = this._cs.recieveData.subscribe((res) => {
    this.data= res;
  }).add(()=>this.UseDatafromSubs(this.data));

but no use.

can somebody please help.

Thanks in Advance.

Body:
Can you just call the method you want inside the subscribe block?
e.g.

ngOnInit{
    this.subscription = this._cs.recieveData.subscribe((res) => {
    this.data= res;
    this.UseDatafromSubs(res);
  })
}


问:
ASCII Visualisation of a graph of nodes in python
I have a class called Node

```<code>class Node:
   def __init__(self,name, childList, parentList):
      self.name = name
      # a list of all nodes which are children of this node
      # may have length 0 to many
      self.childList = childList
      # a list of all nodes which are parents of this node
      # may have length 0 to many
      self.parentList = parentList
</code>```

I have a list of Nodes (nodeList). These Nodes may be in each others parentLists or childLists. I want to be able to visualise the relationships between the Nodes dictated in their childLists and parentlists onto stdout (as an ASCII drawing).

e.g where the names below are names of the nodes in the nodeList.

```<code>                           Classifier
                                |
                                |
                         FeatureCombiner
                          /           \
                         /             \
                        /               \
               FeatureGenerator1     FeatureGenerator2
                      \                     /
                       \                   /
                        \                 /
                         \               /
                          \             /
                           \           /
                            \         /
                            Image Loader
</code>```

Classifier has an empty parentList and a childList of length 1 containing FeatureCombiner. FeatureGenerator1 and 2 have the same parent and childList containing FeatureCombiner and Image Loader respectively. Image Loader has an empty childList and a parentList containing FeatureGenerator1 and 2.

Thankyou in advance,
Matt

答:
We had a similar problem in DVC project and after lurking around and even trying to port Graph::Easy into Python, we've realized that there is no cross-platform python library that can do that and not require some heavy dependencies like Graphviz. So we've ended up with using an amazing library called Grandalf that handled the layout for us, then we render the results ourselves in ASCII and present them using a pager (this is how stuff like git log makes it's output nice and scrollable both horizontally and vertically). See the whole code here.

```<code>+-------------------+           +--------------------+
| test_data.csv.dvc |           | train_data.csv.dvc |
+-------------------+           +--------------------+
                  **              **
                    ***        ***
                       **    **
                +-------------------+
                | featurization.dvc |
                +-------------------+
                  ***            ***
                **                  ***
              **                       **
    +--------------+                     **
    | training.dvc |                   **
    +--------------+                ***
                  ***            ***
                     **        **
                       **    **
                     +---------+
                     | Dvcfile |
                     +---------+
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a class called Node

class Node:
   def __init__(self,name, childList, parentList):
      self.name = name
      # a list of all nodes which are children of this node
      # may have length 0 to many
      self.childList = childList
      # a list of all nodes which are parents of this node
      # may have length 0 to many
      self.parentList = parentList

I have a list of Nodes (nodeList). These Nodes may be in each others parentLists or childLists. I want to be able to visualise the relationships between the Nodes dictated in their childLists and parentlists onto stdout (as an ASCII drawing).

e.g where the names below are names of the nodes in the nodeList.

                           Classifier
                                |
                                |
                         FeatureCombiner
                          /           \
                         /             \
                        /               \
               FeatureGenerator1     FeatureGenerator2
                      \                     /
                       \                   /
                        \                 /
                         \               /
                          \             /
                           \           /
                            \         /
                            Image Loader

Classifier has an empty parentList and a childList of length 1 containing FeatureCombiner. FeatureGenerator1 and 2 have the same parent and childList containing FeatureCombiner and Image Loader respectively. Image Loader has an empty childList and a parentList containing FeatureGenerator1 and 2.

Thankyou in advance,
Matt

Body:
We had a similar problem in DVC project and after lurking around and even trying to port Graph::Easy into Python, we've realized that there is no cross-platform python library that can do that and not require some heavy dependencies like Graphviz. So we've ended up with using an amazing library called Grandalf that handled the layout for us, then we render the results ourselves in ASCII and present them using a pager (this is how stuff like git log makes it's output nice and scrollable both horizontally and vertically). See the whole code here.

+-------------------+           +--------------------+
| test_data.csv.dvc |           | train_data.csv.dvc |
+-------------------+           +--------------------+
                  **              **
                    ***        ***
                       **    **
                +-------------------+
                | featurization.dvc |
                +-------------------+
                  ***            ***
                **                  ***
              **                       **
    +--------------+                     **
    | training.dvc |                   **
    +--------------+                ***
                  ***            ***
                     **        **
                       **    **
                     +---------+
                     | Dvcfile |
                     +---------+


问:
How to overwrite portions of a DriverKit OSData internal buffer?
The documentation of OSData says that "...You can add bytes to them and overwrite portions of the byte array.". I can see a method to append bytes, but I don't understand how I am able to overwrite a portion of the buffer.

Another option would be to use IONewZero to allocate a number of elements of the type I need. I my case I just need this for ints.

Example:

```<code>T* dataBuffer = IONewZero(T, SIZE);
</code>```

And then deallocate with:

```<code>IOSafeDeleteNULL(dataBuffer_, T, SIZE);
</code>```

What are the advantages of using an OSData object compared to the solution with IONewZero / IOSafeDeleteNULL?

答:
I think the documentation might just be copy-pasted from the kernel variant of OSData. I've seen that in a bunch of places, especially USBDriverKit.

OSData is mostly useful for dealing with plist-like data structures (i.e. setting and getting properties on service objects) in conjunction with the other OSTypes: OSArray, OSDictionary, OSNumber, etc. It's also used for in-band (<= 4096 byte) "struct" arguments of user client external methods.

The only use I can see outside of those scenarios is when you absolutely have to reference-count a blob of data. But it's certainly not a particularly convenient or efficient container for data-in-progress. If you subsequently need to send the data to a device or map it to user space, IOBufferMemoryDescriptor is probably a better choice (and also reference counted) though it's even more heavyweight.

Body:
The documentation of OSData says that "...You can add bytes to them and overwrite portions of the byte array.". I can see a method to append bytes, but I don't understand how I am able to overwrite a portion of the buffer.

Another option would be to use IONewZero to allocate a number of elements of the type I need. I my case I just need this for ints.

Example:

T* dataBuffer = IONewZero(T, SIZE);

And then deallocate with:

IOSafeDeleteNULL(dataBuffer_, T, SIZE);

What are the advantages of using an OSData object compared to the solution with IONewZero / IOSafeDeleteNULL?


问:
How to change button props based on breakpoints in Material UI
I'm trying to change the variant and/or size on a material-ui button for different screen sizes.  For example, use no variant or size="small" below the "sm" breakpoint and variant="outlined" and/or size="large" above "sm".

Normally, I'd make use withStyles and create a style with theme.breakpoints to affect changes by applying the style to the element using className, however, variant and size are props.

After reading the api, scouring the web, and fiddling extensively, I can't seem to figure out any straight-forward way to change the props based on viewport width.

I've thought about creating a "width-detector" and then using some JS logic to change the button element's props accordingly, but that seems just a bit far out as a solution.

So I'm asking here to see if there is an easier solution out there.  Thanks.

答:
The withWidth HOC is deprecated per Material UI Docs.

This is the approach that works now, with a combination of useTheme and useMediaQuery.

Edit: useTheme is not really required here, since useMediaQuery automatically provides that as an argument.

```<code>// import { useTheme } from "@material-ui/core/styles";
import { useMediaQuery } from "@material-ui/core";
...

function ResponsiveButton() {
  // const theme = useTheme();
  // const isSmallScreen = useMediaQuery(theme.breakpoints.down("xs"));
  const isSmallScreen = useMediaQuery(theme => theme.breakpoints.down("xs"));

  const buttonProps = {
    variant: isSmallScreen ? "text" : "outlined",
    size: isSmallScreen ? "small" : "large"
  };
  return (
    <Button {...buttonProps} color="primary">
      Responsive Button
    </Button>
  );
}

export default ResponsiveButton;
</code>```

Body:
The withWidth HOC is deprecated per Material UI Docs.

This is the approach that works now, with a combination of useTheme and useMediaQuery.

Edit: useTheme is not really required here, since useMediaQuery automatically provides that as an argument.

// import { useTheme } from "@material-ui/core/styles";
import { useMediaQuery } from "@material-ui/core";
...

function ResponsiveButton() {
  // const theme = useTheme();
  // const isSmallScreen = useMediaQuery(theme.breakpoints.down("xs"));
  const isSmallScreen = useMediaQuery(theme => theme.breakpoints.down("xs"));

  const buttonProps = {
    variant: isSmallScreen ? "text" : "outlined",
    size: isSmallScreen ? "small" : "large"
  };
  return (
    <Button {...buttonProps} color="primary">
      Responsive Button
    </Button>
  );
}

export default ResponsiveButton;


问:
Powershell, Graph API and $select
I have an MS Graph API in PowerShell working for the most part.

I am using

```<code>$Uri = $null
$Uri = "https://graph.microsoft.com/v1.0/users?$select=displayName,givenName,postalCode"
$payload=$null
$payload = Invoke-RestMethod -uri $Uri  -Headers $Header -Method Get -ContentType "application/json"
$payload.value
</code>```

however, it is not changing the field selection. It keeps returning the default fields as demonstrated here

https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http

What could I possibly be doing wrong?

I am using application based authentication. The payload is being returned but it is not recognizing the $select statement.

No errors are being returned by the PowerShell

I run it in Graph Explorer it works fine.

答:
The error is caused by the type of string declaration used for the Uri string. You are declaring the string like this:

```<code>$Uri = "https://graph.microsoft.com/v1.0/users?$select=displayName,givenName,postalCode"
</code>```

This tells Powershell, that you want to evaluate the string. $ is Powershell's variable identifier. Undeclared variables are set automatically to an empty string, when evaluated in a string. Therefore the request executed against the Graph Api is:

```<code>https://graph.microsoft.com/v1.0/users?=displayName,givenName,postalCode
</code>```

Your can check this yourself by writing the variable to the host:

```<code>Write-Host $Uri
</code>```

If you execute this query with the Graph Explorer. It will return all users without an applied filter, which is the behaviour you have observed. You need to change the declaration to:

```<code>$Uri = 'https://graph.microsoft.com/v1.0/users?$select=displayName,givenName,postalCode'
</code>```

Then, Powershell will not interpret $select as a variable and your request should work properly.

Title: Powershell, Graph API and $select

Body:
I have an MS Graph API in PowerShell working for the most part.

I am using

$Uri = $null
$Uri = "https://graph.microsoft.com/v1.0/users?$select=displayName,givenName,postalCode"
$payload=$null
$payload = Invoke-RestMethod -uri $Uri  -Headers $Header -Method Get -ContentType "application/json"
$payload.value

however, it is not changing the field selection. It keeps returning the default fields as demonstrated here

https://learn.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http

What could I possibly be doing wrong?

I am using application based authentication. The payload is being returned but it is not recognizing the $select statement.

No errors are being returned by the PowerShell

I run it in Graph Explorer it works fine.

Body:
The error is caused by the type of string declaration used for the Uri string. You are declaring the string like this:

$Uri = "https://graph.microsoft.com/v1.0/users?$select=displayName,givenName,postalCode"

This tells Powershell, that you want to evaluate the string. $ is Powershell's variable identifier. Undeclared variables are set automatically to an empty string, when evaluated in a string. Therefore the request executed against the Graph Api is:

https://graph.microsoft.com/v1.0/users?=displayName,givenName,postalCode

Your can check this yourself by writing the variable to the host:

Write-Host $Uri

If you execute this query with the Graph Explorer. It will return all users without an applied filter, which is the behaviour you have observed. You need to change the declaration to:

$Uri = 'https://graph.microsoft.com/v1.0/users?$select=displayName,givenName,postalCode'

Then, Powershell will not interpret $select as a variable and your request should work properly.


问:
Aggregation Median/Mean Queries
I have an index with a type that can be reduced to:

```<code>{
  'date': DATE_STRING,
  'owner': INT,
  'color: 'red' | 'purple' | 'blue'
}
</code>```

and am looking to make queries to present the following data, where an owner's value is equal to the aggregate number of items they own that are 'blue' subtracted by the number of item's they own that are 'red' over a requested time (Don't ask why):

minimum value of any owner (within requested time)

maximum value of any owner (within requested time)

mean value of all owners (within requested time)

median value of all owners (within requested time)

a particular owner's value (within requested time)

答:
Set up the index:

```<code>PUT colorful
{
  "mappings": {
    "properties": {
      "date": {
        "type": "date"
      },
      "owner": {
        "type": "integer"
      },
      "color": {
        "type": "keyword"
      }
    }
  }
}
</code>```

Insert a few docs

```<code>POST colorful/_doc
{"date":"2020-05-28T19:56:12.237Z","owner":131351351,"color":"red"}

POST colorful/_doc
{"date":"2020-04-28T19:58:02.110Z","owner":35135125,"color":"purple"}

POST colorful/_doc
{"date":"2020-05-15T19:58:15.966Z","owner":997654341,"color":"blue"}

POST colorful/_doc
{"date":"2020-05-21T19:58:35.766Z","owner":366449,"color":"red"}
</code>```

Filter by a date range & aggregate. Min, Max, Avg(=Mean) can be calculated using stats, for median there's percentiles[50]. Not sure what you meant by a particular owner's value but the actual range-filtered docs can be fetched using top_hits plus you could add a filter for a specific doc.

```<code>GET colorful/_search
{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now-3M",
        "lte": "now-1h"
      }
    }
  },
  "aggs": {
    "1)general_stats": {
      "stats": {
        "field": "owner"
      }
    },
    "2)median": {
      "percentiles": {
        "field": "owner",
        "percents": [
          50
        ]
      }
    },
    "3)top_hits": {
      "top_hits": {
        "size": 10
      }
    }
  }
}
</code>```

Title: Aggregation Median/Mean Queries

Body:
I have an index with a type that can be reduced to:

{
  'date': DATE_STRING,
  'owner': INT,
  'color: 'red' | 'purple' | 'blue'
}

and am looking to make queries to present the following data, where an owner's value is equal to the aggregate number of items they own that are 'blue' subtracted by the number of item's they own that are 'red' over a requested time (Don't ask why):

minimum value of any owner (within requested time)

maximum value of any owner (within requested time)

mean value of all owners (within requested time)

median value of all owners (within requested time)

a particular owner's value (within requested time)

Body:
Set up the index:

PUT colorful
{
  "mappings": {
    "properties": {
      "date": {
        "type": "date"
      },
      "owner": {
        "type": "integer"
      },
      "color": {
        "type": "keyword"
      }
    }
  }
}

Insert a few docs

POST colorful/_doc
{"date":"2020-05-28T19:56:12.237Z","owner":131351351,"color":"red"}

POST colorful/_doc
{"date":"2020-04-28T19:58:02.110Z","owner":35135125,"color":"purple"}

POST colorful/_doc
{"date":"2020-05-15T19:58:15.966Z","owner":997654341,"color":"blue"}

POST colorful/_doc
{"date":"2020-05-21T19:58:35.766Z","owner":366449,"color":"red"}

Filter by a date range & aggregate. Min, Max, Avg(=Mean) can be calculated using stats, for median there's percentiles[50]. Not sure what you meant by a particular owner's value but the actual range-filtered docs can be fetched using top_hits plus you could add a filter for a specific doc.

GET colorful/_search
{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now-3M",
        "lte": "now-1h"
      }
    }
  },
  "aggs": {
    "1)general_stats": {
      "stats": {
        "field": "owner"
      }
    },
    "2)median": {
      "percentiles": {
        "field": "owner",
        "percents": [
          50
        ]
      }
    },
    "3)top_hits": {
      "top_hits": {
        "size": 10
      }
    }
  }
}


问:
Spring session bean: initialize with values
I've a doubt about Spring session bean. Let me try to explain what I need and what I did. I need to store on a session variable (in that case a Bean) the user_id so, when I need to create some record on db I can keep track of who did what.

To do that, for first, I created a bean and, second, I modified my application context in that way:

```<code><bean id="UserInfo" class="net.agdev.session.UserInfo" scope="session">
    <aop:scoped-proxy/>
</bean>
</code>```

I read that using this :

```<code>ContextLoader.getCurrentWebApplicationContext().getBean("UserInfo");
</code>```

is ppossible to access to the bean, but it's not yet clear how to fill that bean..

I tryed to read on Spring documentation how to initalize the bean and how to recall on my Class controller but I didn't find anything.

Could you suggest where to find an example or a tutorial to do that?

many thanks!

Andrea

答:
By aspect programming like AspectJ. You have to set some trigger, for example after an user does something you have to read your bean and fill it the operation info that have been performed by the user.

You can use @annotation to define trigger or you can do it by spring xml file. I think you have to use an application context bean and not a session bean.

Body:
I've a doubt about Spring session bean. Let me try to explain what I need and what I did. I need to store on a session variable (in that case a Bean) the user_id so, when I need to create some record on db I can keep track of who did what.

To do that, for first, I created a bean and, second, I modified my application context in that way:

<bean id="UserInfo" class="net.agdev.session.UserInfo" scope="session">
    <aop:scoped-proxy/>
</bean>

I read that using this :

ContextLoader.getCurrentWebApplicationContext().getBean("UserInfo");

is ppossible to access to the bean, but it's not yet clear how to fill that bean..

I tryed to read on Spring documentation how to initalize the bean and how to recall on my Class controller but I didn't find anything.

Could you suggest where to find an example or a tutorial to do that?

many thanks!

Andrea


问:
Why does np.ma.array take an inverted mask?
I have some array

```<code>a = np.array([1, 2, 3])
</code>```

and some mask

```<code>mask = np.ones(a.shape, dtype=bool)
</code>```

and can do

```<code>np.testing.assert_almost_equal(a[mask], a)  # True
</code>```

However,

```<code>np.ma.array(a, mask)
</code>```

is equivalent to

```<code>a[np.logical_not(mask)]
</code>```

and

```<code>np.ma.array(a, np.logical_not(mask))
</code>```

is equivalent to

```<code>a[mask]
</code>```

This seems counter intuitive to me.

Would love an explanation for this design choice by numpy.

答:
```<code>In [6]: a = np.array([1,2,3])
In [7]: idx = np.array([1,0,1], bool)
In [8]: idx
Out[8]: array([ True, False,  True])
In [9]: a[idx]
Out[9]: array([1, 3])
</code>```

Just because you called a boolean array mask, does not mean it behaves as 'mask' in every sense of the word.  I intentionally choose a different name.  Yes, we do often call such an array mask and talk of 'masking', but what we are really doing is 'selecting'.  The a[idx] operations returns the elements of a where the idx is True.  It's the same as indexing with the nonzero tuple:

```<code>In [13]: np.nonzero(idx)
Out[13]: (array([0, 2]),)
</code>```

In np.ma mask is used in the sense of 'mask out', covering over.

```<code>In [10]: mm = np.ma.masked_array(a, mask=idx)
In [11]: mm
Out[11]:
masked_array(data=[--, 2, --],
             mask=[ True, False,  True],
       fill_value=999999)
In [12]: mm.compressed()
Out[12]: array([2])
</code>```

In the display the masked values show up as '--'.  As the np.ma docs say, those elements a considered to be invalid, and will be excluded from computations.

mm.filled returns an array with the 'masked' value replaced by the 'fill':

```<code>In [16]: mm.filled()
Out[16]: array([999999,      2, 999999])
</code>```

we can do the same thing with idx:

```<code>In [17]: a[idx] = 999999
In [18]: a
Out[18]: array([999999,      2, 999999])
</code>```

Body:
I have some array

a = np.array([1, 2, 3])

and some mask

mask = np.ones(a.shape, dtype=bool)

and can do

np.testing.assert_almost_equal(a[mask], a)  # True

However,

np.ma.array(a, mask)

is equivalent to

a[np.logical_not(mask)]

and

np.ma.array(a, np.logical_not(mask))

is equivalent to

a[mask]

This seems counter intuitive to me.

Would love an explanation for this design choice by numpy.

Body:
In [6]: a = np.array([1,2,3])
In [7]: idx = np.array([1,0,1], bool)
In [8]: idx
Out[8]: array([ True, False,  True])
In [9]: a[idx]
Out[9]: array([1, 3])

Just because you called a boolean array mask, does not mean it behaves as 'mask' in every sense of the word.  I intentionally choose a different name.  Yes, we do often call such an array mask and talk of 'masking', but what we are really doing is 'selecting'.  The a[idx] operations returns the elements of a where the idx is True.  It's the same as indexing with the nonzero tuple:

In [13]: np.nonzero(idx)
Out[13]: (array([0, 2]),)

In np.ma mask is used in the sense of 'mask out', covering over.

In [10]: mm = np.ma.masked_array(a, mask=idx)
In [11]: mm
Out[11]:
masked_array(data=[--, 2, --],
             mask=[ True, False,  True],
       fill_value=999999)
In [12]: mm.compressed()
Out[12]: array([2])

In the display the masked values show up as '--'.  As the np.ma docs say, those elements a considered to be invalid, and will be excluded from computations.

mm.filled returns an array with the 'masked' value replaced by the 'fill':

In [16]: mm.filled()
Out[16]: array([999999,      2, 999999])

we can do the same thing with idx:

In [17]: a[idx] = 999999
In [18]: a
Out[18]: array([999999,      2, 999999])


问:
Android Multidex method invocation
I have a question regarding Multidex in Android. Given an application that consists of multiple Dex files (classes.dex, classes2.dex), how does invocation work in the bytecode?

Since the methods IDs referenced in the invoke instructions are still 16-bit (from https://source.android.com/devices/tech/dalvik/dalvik-bytecode#instructions):

invoke-direct {vC, vD, vE, vF, vG}, meth@BBBB

A: argument word count (4 bits),
B: method reference index (16 bits),
C..G: argument registers (4 bits each)

So how does a method defined in classes2.dex reference or more importantly invoke a method defined in classes.dex or classes3.dex?

Regards,

Loran

答:
According to: "Basically, how does it know the code offset and how does it know which dex file the method is located?"

Please consider that these dex files are "intermediate" files interpreted or compiled by the VM (ART) or a compiler (dex2oat). This means, there is no "offset" or relocation table as in ELF or MACH-O files.

As Antimony explained the id in the invoke call is just an index in the ref table of a single dex file. This ref table maps the class name, method name and signature to the index. In the end the VM loads all dex files and creates table of classes and methods in memory. If invoke(..) get's called it checks the ref table of the dex file and fetches the taret method, class name and signature. Now it searches for those three values in memory and invokes.

Please consider that you have to deal with an VM that translates intermediate language into architecture dependend code at:
 * Runtime (intepreter mode)
 * Runtime but caches if neccessary ("Just in time")
 * During installation of your app ("Ahead of time")

Please check: https://source.android.com/devices/tech/dalvik/configure

Here you have another example but using the JVM (means java opcodes):

```<code>    public final class org.chickenhook.binderfuzzy.BuildConfig
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER
Constant pool:
   #1 = Methodref          #6.#32         // java/lang/Object."<init>":()V
   #2 = String             #33            // true
   #3 = Methodref          #34.#35        // java/lang/Boolean.parseBoolean:(Ljava/lang/String;)Z
   #4 = Fieldref           #5.#36         // org/chickenhook/binderfuzzy/BuildConfig.DEBUG:Z
   #5 = Class              #37            // org/chickenhook/binderfuzzy/BuildConfig
   #6 = Class              #38            // java/lang/Object
   #7 = Utf8               DEBUG
   #8 = Utf8               Z
   #9 = Utf8               APPLICATION_ID
  #10 = Utf8               Ljava/lang/String;
  #11 = Utf8               ConstantValue
</code>```

Here you can see the "constant pool".
At INDEX #3 you have the methodref to java/lang/Boolean.parseBoolean:(Ljava/lang/String;)Z (as I told Class, method and signature). The VM, jit or aot reads this value and checks in memory at runtime for the class in a table where all classes of all intermediate files are represented.

The important thing is that the classpath points to all neccessary intermediates. Otherwise you'll get a "ClassNotFound" exception. It remembers a li'l bit to runtime linkers searching for symbol names and filling the relocation table of a binary yes, but it's technically complete differently.

Title: Android Multidex method invocation

Body:
According to: "Basically, how does it know the code offset and how does it know which dex file the method is located?"

Please consider that these dex files are "intermediate" files interpreted or compiled by the VM (ART) or a compiler (dex2oat). This means, there is no "offset" or relocation table as in ELF or MACH-O files.

As Antimony explained the id in the invoke call is just an index in the ref table of a single dex file. This ref table maps the class name, method name and signature to the index. In the end the VM loads all dex files and creates table of classes and methods in memory. If invoke(..) get's called it checks the ref table of the dex file and fetches the taret method, class name and signature. Now it searches for those three values in memory and invokes.

Please consider that you have to deal with an VM that translates intermediate language into architecture dependend code at:
 * Runtime (intepreter mode)
 * Runtime but caches if neccessary ("Just in time")
 * During installation of your app ("Ahead of time")

Please check: https://source.android.com/devices/tech/dalvik/configure

Here you have another example but using the JVM (means java opcodes):

    public final class org.chickenhook.binderfuzzy.BuildConfig
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER
Constant pool:
   #1 = Methodref          #6.#32         // java/lang/Object."<init>":()V
   #2 = String             #33            // true
   #3 = Methodref          #34.#35        // java/lang/Boolean.parseBoolean:(Ljava/lang/String;)Z
   #4 = Fieldref           #5.#36         // org/chickenhook/binderfuzzy/BuildConfig.DEBUG:Z
   #5 = Class              #37            // org/chickenhook/binderfuzzy/BuildConfig
   #6 = Class              #38            // java/lang/Object
   #7 = Utf8               DEBUG
   #8 = Utf8               Z
   #9 = Utf8               APPLICATION_ID
  #10 = Utf8               Ljava/lang/String;
  #11 = Utf8               ConstantValue

Here you can see the "constant pool".
At INDEX #3 you have the methodref to java/lang/Boolean.parseBoolean:(Ljava/lang/String;)Z (as I told Class, method and signature). The VM, jit or aot reads this value and checks in memory at runtime for the class in a table where all classes of all intermediate files are represented.

The important thing is that the classpath points to all neccessary intermediates. Otherwise you'll get a "ClassNotFound" exception. It remembers a li'l bit to runtime linkers searching for symbol names and filling the relocation table of a binary yes, but it's technically complete differently.


答:
It is working fine    </p>

```<code>library(dplyr)
d %>%
   count(ID)
#  ID n
#1  1 2
#2  2 1
#3  3 1
#4  4 4
#5  5 2
#6  6 1
</code>```

Title: dplyr::count and group_by misfunction

Body:
Anyone knows why I all of sudden get this error message?

library(dplyr)

d <- wrapr::build_frame( "ID" , "OP", "DATE" | 1 , "A" , "2001-01-02" | 1 , "B" , "2015-04-25" | 2 , "A" , "2000-04-01" | 3 , "D" , "2014-04-07" | 4 , "C" , "2012-12-01" | 4 , "A" , "2005-06-16" | 4 , "D" , "2009-01-20" | 4 , "B" , "2009-01-20" | 5 , "A" , "2010-10-10" | 5 , "B" , "2003-11-09" | 6 , "B" , "2004-01-09" )

d%>%count(ID)

Generates the following error:

Error in vapply(.x, .f, .mold, ..., USE.NAMES = FALSE) :
  values must be type 'logical',
 but FUN(X[[1]]) result is type 'integer'

Body:
It is working fine

library(dplyr)
d %>%
   count(ID)
#  ID n
#1  1 2
#2  2 1
#3  3 1
#4  4 4
#5  5 2
#6  6 1


问:
Image on Right, text on left
I'm pretty new to website development and currently still running a course..
We have this assignment and there is just one thing where I can't wrap my mind around (pun intended).

In the "problem" image, the image is in a correct position, but the text alignment is off..
The text should be as shown in the "solution" image

#article {
    width: 650px;
    min-height: 280px;
    margin: 20px;
}

#article p {
    font-size: .8em;
    line-height: 1.6em;
}

#win {
    position: relative;
    left: 160px;
    top: 40px;
    float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="article">

            <img id="win" src="img/gratis.png" alt="test"/>

        <h1>de spikes & de spikids</h1>

        <p>
            Dit is de officiële Spikes-site (dus: de enige echte)! Hier vindt u alle
            informatie en nog véél méér onzin over de knotsgekke bands de Spikes en de
            Spikids. Volg ons op
            Facebook. De
            foto's die wij van jou schieten op onze optredens – vind je voortaan op
            facebook. Op onze eigenste
            <a
            href="https://www.youtube.com/channel/UCTUYz6ynn0M-vHxUXJM15NA"
            target="_blank"
            >YouTube</a
            >
            SPIKES TV kom je alvast in de stemming. Véél kijkplezier!
        </p>

        <h1>De Spikes anno 2015</h1>

        <p>
            De Spikes hebben zichzelf microscopisch onder de loep genomen. Er is gewikt,
            gewogen en het orakel heeft beslist! Het jarenlange succesvolle
            Spikes-concept heeft z’n houdbaarheidsdatum bereikt. Het tijdperk van de
            “spottende parodieën en persiflages” is voorgoed voorbij. Het muzikaal
            voornemen is om “het muzikaal OORgasme” tot méérvoudige hoogtes te brengen
            in 2015 – en tegelijkertijd toch “dé allerleukste coverband uit België” te
            blijven.
        </p>
    </div></code>```

I've been struggling with this for a while now, a solution would help me out a LOT! :)

Thanks in advance for everyone who answers this!

PROBLEM_IMAGE

SOLUTION_IMAGE

答:
Try applying a max-width to your paragraph or image. In your css you can add:

```<code>article p {
    max-width:70%;
}
</code>```

or

```<code>win {
    max-width:30%;
}
</code>```

and play around with the percentages

Title: Image on Right, text on left

Body:
I'm pretty new to website development and currently still running a course..
We have this assignment and there is just one thing where I can't wrap my mind around (pun intended).

In the "problem" image, the image is in a correct position, but the text alignment is off..
The text should be as shown in the "solution" image

#article {
    width: 650px;
    min-height: 280px;
    margin: 20px;
}

#article p {
    font-size: .8em;
    line-height: 1.6em;
}

#win {
    position: relative;
    left: 160px;
    top: 40px;
    float: right;
}

de spikes & de spikids

            Dit is de officiële Spikes-site (dus: de enige echte)! Hier vindt u alle
            informatie en nog véél méér onzin over de knotsgekke bands de Spikes en de
            Spikids. Volg ons op
            Facebook. De
            foto's die wij van jou schieten op onze optredens – vind je voortaan op
            facebook. Op onze eigenste
            YouTube
            SPIKES TV kom je alvast in de stemming. Véél kijkplezier!

De Spikes anno 2015

            De Spikes hebben zichzelf microscopisch onder de loep genomen. Er is gewikt,
            gewogen en het orakel heeft beslist! Het jarenlange succesvolle
            Spikes-concept heeft z’n houdbaarheidsdatum bereikt. Het tijdperk van de
            “spottende parodieën en persiflages” is voorgoed voorbij. Het muzikaal
            voornemen is om “het muzikaal OORgasme” tot méérvoudige hoogtes te brengen
            in 2015 – en tegelijkertijd toch “dé allerleukste coverband uit België” te
            blijven.

I've been struggling with this for a while now, a solution would help me out a LOT! :)

Thanks in advance for everyone who answers this!

PROBLEM_IMAGE

SOLUTION_IMAGE

Body:
Try applying a max-width to your paragraph or image. In your css you can add:

article p {
    max-width:70%;
}

or

win {
    max-width:30%;
}

and play around with the percentages


问:
sort numbers numerically and strings alphabetically in an array perl
It's a very easy problem but can't get my way around it. I have an array

```<code>@arr = qw(txt text anothertext 38.09 100.87 0.876)
</code>```

How can I sort the numbers in the array numerically and the strings alphabetically. So the output would look like, either:

```<code>@sorted_as = (anothertext text txt 100.87 38.09 0.876)
</code>```

or,

```<code>@sorted_des = (txt text anothertext 100.87 38.09 0.876)
</code>```

Sorry if I duplicate any question but could not find a suitable answer.

答:
Using Sort::Key::Multi:

```<code># urns = (u)nsigned int, (r)everse (n)umber, (s)tring
use Sort::Key::Multi qw( urnskeysort );

my @sorted =
   urnskeysort {
      /^[0-9]/
         ? ( 1, $_, "" )
         : ( 0, 0, $_ )
   }
      @unsorted;
</code>```

Similarly, you can use urnrskeysort for the second order.

Body:
It's a very easy problem but can't get my way around it. I have an array

@arr = qw(txt text anothertext 38.09 100.87 0.876)

How can I sort the numbers in the array numerically and the strings alphabetically. So the output would look like, either:

@sorted_as = (anothertext text txt 100.87 38.09 0.876)

or,

@sorted_des = (txt text anothertext 100.87 38.09 0.876)

Sorry if I duplicate any question but could not find a suitable answer.

Body:
Using Sort::Key::Multi:

# urns = (u)nsigned int, (r)everse (n)umber, (s)tring
use Sort::Key::Multi qw( urnskeysort );

my @sorted =
   urnskeysort {
      /^[0-9]/
         ? ( 1, $_, "" )
         : ( 0, 0, $_ )
   }
      @unsorted;

Similarly, you can use urnrskeysort for the second order.


问:
Alert button to dismiss Alert and go back to previous View Controller
I'm kind of new to Swift and I can't figure this out. I have an Alert that should show on a successful URL request. After a user clicks an Ok button on the alert, I need the alert dismissed and I need the presented controller to go back in the navigation stack to the previous view controller. I don't get any errors but nothing happens. If I move the entire code for the Alert inside the CustomClass, then it works fine. I assume I am not referencing the CustomClass the right way. Any help would be greatly appreciated!

```<code> struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}
</code>```

答:
Dont create new instance  let vc = CustomClass() use the one you passed as parameter

```<code>struct Alert {
   static func CustomAlert(vc: UIViewController, title: String, message: String){

       var title = "Title...!"
       var message = "Message..."
       let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
       myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
           myAlert.dismiss(animated: true, completion: nil)

        if let controller = vc as? CustomClass {
           controller.GoBackToPreviousVC()
        }
       }))
        vc.present(myAlert, animated: true, completion: nil)
   }
}
</code>```

And better to use Protocol instead of hard code class

```<code>protocol Goback {
    func GoBackToPreviousVC()
}

struct Alert {
   static func CustomAlert(vc: UIViewController, title: String, message: String){

       var title = "Title...!"
       var message = "Message..."
       let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
       myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
           myAlert.dismiss(animated: true, completion: nil)

        if let controller = vc as? Goback {
           controller.GoBackToPreviousVC()
        }
       }))
        vc.present(myAlert, animated: true, completion: nil)
   }
}
</code>```

And confirm your class with that protocol in which you want to use Alert

```<code>class CustomClass: UIViewController,Goback {

    func GoBackToPreviousVC(){

        navigationController?.popViewController(animated: true)
    }
}
</code>```

Body:
I'm kind of new to Swift and I can't figure this out. I have an Alert that should show on a successful URL request. After a user clicks an Ok button on the alert, I need the alert dismissed and I need the presented controller to go back in the navigation stack to the previous view controller. I don't get any errors but nothing happens. If I move the entire code for the Alert inside the CustomClass, then it works fine. I assume I am not referencing the CustomClass the right way. Any help would be greatly appreciated!

 struct Alert {
    static func CustomAlert(vc: UIViewController, title: String, message: String){

        var title = "Title...!"
        var message = "Message..."
        let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
            myAlert.dismiss(animated: true, completion: nil)
            let vc = CustomClass()
            vc.GoBackToPreviousVC()
        }))
         vc.present(myAlert, animated: true, completion: nil)
    }
 }

 class: CustomClass: UIViewController {

    func GoBackToPreviousVC(){
        navigationController?popViewController(animated: true)
    }

    function Download(){

      code for URLRequest...

      DispatchQueue.main.async {
        if (self.response.Status == "200"){
            Alert.CustomAlert(vc: self, title: "", message: "")
        }

      }

    }
}

Body:
Dont create new instance  let vc = CustomClass() use the one you passed as parameter

struct Alert {
   static func CustomAlert(vc: UIViewController, title: String, message: String){

       var title = "Title...!"
       var message = "Message..."
       let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
       myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
           myAlert.dismiss(animated: true, completion: nil)

        if let controller = vc as? CustomClass {
           controller.GoBackToPreviousVC()
        }
       }))
        vc.present(myAlert, animated: true, completion: nil)
   }
}

And better to use Protocol instead of hard code class

protocol Goback {
    func GoBackToPreviousVC()
}

struct Alert {
   static func CustomAlert(vc: UIViewController, title: String, message: String){

       var title = "Title...!"
       var message = "Message..."
       let myAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
       myAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (actin) in
           myAlert.dismiss(animated: true, completion: nil)

        if let controller = vc as? Goback {
           controller.GoBackToPreviousVC()
        }
       }))
        vc.present(myAlert, animated: true, completion: nil)
   }
}

And confirm your class with that protocol in which you want to use Alert

class CustomClass: UIViewController,Goback {

    func GoBackToPreviousVC(){

        navigationController?.popViewController(animated: true)
    }
}


问:
Laravel 5.8 apply global scope on newQuery like 4.2 did
I am upgrading a laravel 4.2 project to 5.8.

In 4.2, I used the global scope trait to automatically add where conditions to my models. The where conditions would be added on 'newQuery' and were the first where conditions.

Now in 5.8, I added my global scope using the new way, it does not add the where conditions from the scope on 'newQuery', it applies the global scope conditions on 'get' by appending the where conditions to the query. This does not match my DB indexing, I can't do this, I need my global scopes to be applied on 'newQuery'.

```<code>class TenantScope implements Scope
{
  public function apply(Builder $builder, Model $model)
  {
    $builder->where($model->getQualifiedTenantColumn(), '=', \idweb\helpers\SessionHelper::getTenantId());
    $builder->whereNull($model->getQualifiedDateDeletedColumn());
  }
}

// when I do this:
$q = \myapp\MyModel::query();

// the following test should be true with my two where conditions applied from the scope
// with laravel 5.8, this fails, the scope has not been applied yet
$this->assertEquals(2, count($q->newQuery()->wheres));

$q->where('cat', 'dog');
$list = $q->get();

// this uses db query, which is wrong
select * from mymodel where cat=dog and tenant=1 and date_deleted is null;

// the query needs to be by having the scope applied on newQuery, not get:
select * from mymodel where tenant=1 and date_deleted is null and cat=dog;
</code>```

How do I get my scope applied on 'newQuery' like 4.2 did?

答:
It's not documented, but you can use 'extend' instead of 'apply'. 'extend' fires when the query is initiated so the where clauses are first.

In my scope class:

```<code>  /**
   * @param Builder $builder
   * @return void
   */
  public function extend(Builder $builder)
</code>```

Body:
I am upgrading a laravel 4.2 project to 5.8.

In 4.2, I used the global scope trait to automatically add where conditions to my models. The where conditions would be added on 'newQuery' and were the first where conditions.

Now in 5.8, I added my global scope using the new way, it does not add the where conditions from the scope on 'newQuery', it applies the global scope conditions on 'get' by appending the where conditions to the query. This does not match my DB indexing, I can't do this, I need my global scopes to be applied on 'newQuery'.

class TenantScope implements Scope
{
  public function apply(Builder $builder, Model $model)
  {
    $builder->where($model->getQualifiedTenantColumn(), '=', \idweb\helpers\SessionHelper::getTenantId());
    $builder->whereNull($model->getQualifiedDateDeletedColumn());
  }
}

// when I do this:
$q = \myapp\MyModel::query();

// the following test should be true with my two where conditions applied from the scope
// with laravel 5.8, this fails, the scope has not been applied yet
$this->assertEquals(2, count($q->newQuery()->wheres));

$q->where('cat', 'dog');
$list = $q->get();

// this uses db query, which is wrong
select * from mymodel where cat=dog and tenant=1 and date_deleted is null;

// the query needs to be by having the scope applied on newQuery, not get:
select * from mymodel where tenant=1 and date_deleted is null and cat=dog;

How do I get my scope applied on 'newQuery' like 4.2 did?

Body:
It's not documented, but you can use 'extend' instead of 'apply'. 'extend' fires when the query is initiated so the where clauses are first.

In my scope class:

  /**
   * @param Builder $builder
   * @return void
   */
  public function extend(Builder $builder)


问:
What is the difference between ActionScript 2.0 and ActionScript 3.0
What are the main differences between the versions?</p>

答:
As a couple of other people have stated AS2 and AS3 are different languages and even run on on different virtual machine in the flash player, AVM and AVM2 (Actionscript Virtual Machine).

However, that most of the AS2 code has direct AS3 equivalents and in the case of timeline code that names are usually the same (e.g. gotoAndPlay, stop, etc.). You can find a handy cheat sheet here:
http://actionscriptcheatsheet.com/downloads/as3cs_migration.pdf
Generally if there's no AS3 equivalent to what you have in your AS2 there's a better and more robust way instead.

There's also a book call 'The ActionScript 3.0 Migration Guide' that you might want to check out too.

Also you can make AS2 and AS3 code talk to each other through a LocalConnection. There're plenty of how-to's about this on the web.


问:
Python:Group By Multiple Column Pandas
I'm trying to group by a flattened data such as 2 columns group as list & the third one should be the sum of rows of that column .

Suppose data frame looks like

```<code>ColA      ColB     ColC     ColD
A         Hi       Hello     2
A         There    You       4
B         Okay     Tap       4
B         Bye      Here      6
</code>```

I want the output dataframe to look like:

```<code>ColA     ColB        ColC          ColD
A       [Hi,There]   [Hello,You]    6
B       [Okay,Bye]   [Tap,Here]     10
</code>```

答:
This is one way to achieve your desired output:

```<code>df1 = df.groupby(['ColA'])['ColB','ColC'].agg(lambda x: list(x))
df1['ColD'] = df.groupby('ColA')['ColD'].sum()
df1 = df1.reset_index()
</code>```

Output:

```<code>ColA    ColB         ColC           ColD
A       [Hi, There]  [Hello, You]   6
B       [Okay, Bye]  [Tap, Here]    10
</code>```

Title: Python:Group By Multiple Column Pandas

Body:
I'm trying to group by a flattened data such as 2 columns group as list & the third one should be the sum of rows of that column .

Suppose data frame looks like

ColA      ColB     ColC     ColD
A         Hi       Hello     2
A         There    You       4
B         Okay     Tap       4
B         Bye      Here      6

I want the output dataframe to look like:

ColA     ColB        ColC          ColD
A       [Hi,There]   [Hello,You]    6
B       [Okay,Bye]   [Tap,Here]     10

Body:
This is one way to achieve your desired output:

df1 = df.groupby(['ColA'])['ColB','ColC'].agg(lambda x: list(x))
df1['ColD'] = df.groupby('ColA')['ColD'].sum()
df1 = df1.reset_index()

Output:

ColA    ColB         ColC           ColD
A       [Hi, There]  [Hello, You]   6
B       [Okay, Bye]  [Tap, Here]    10