问:
How to output text to a screen, while also outputting Object Orientated buttons - Pygame
```<code>#Importing Modules
import pygame
import sys
import random

#All pygame stuff under here
pygame.init()

#Font definitions
backFont = pygame.font.SysFont("monospace",40)
titleFont = pygame.font.SysFont("garamond", 100)
buttonFont = pygame.font.SysFont("garamond", 25)
bigFont = pygame.font.SysFont("garamond",100)

#Colour definitions
BackGray = pygame.Color('gray60')
screenGray = pygame.Color('gray80')
buttonGray1 = pygame.Color('gray40')
buttonGray2 = pygame.Color('gray50')
buttonGray3 = pygame.Color('gray30')
textColour = pygame.Color('navy')

#Screen size set
screen = pygame.display.set_mode((800, 600))

#Class for the buttons set here
class Button:
    def __init__(self, x, y, width, height, colour, surface):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.colour = colour
        self.surface = surface

    def isPressed(self):
        mouse_position = pygame.mouse.get_pos()
        mouse_x = mouse_position[0]
        mouse_y = mouse_position[1]
        if mouse_x > self.x:
            if mouse_x < self.x + self.width:
                if mouse_y > self.y:
                    if mouse_y < self.y + self.height:
                        mouse_click = pygame.mouse.get_pressed()
                        left_click = mouse_click[0]
                        if left_click:
                            self.colour = (0,0,0)
                            return True
        self.colour = (230, 230, 230)
        return False

    def drawButton(self):
        pygame.draw.rect(self.surface, self.colour,  (self.x, self.y, self.width, self.height))
        pygame.display.flip()

def FrontPage():
    #Back screen
    screen.fill(screenGray)

    #The background is defined here
    BinaryPage = []
    for i in range(0,15):
        BinaryString = ""
        for j in range(0,33):
            BinaryString += random.choice(["0","1"])
        BinaryPage.append(BinaryString)

    for i in range(0,15):
        screen.blit(backFont.render(BinaryPage[i], 1, BackGray), (0,i * 40))

    #The title is defined and printed here
    Title1 = titleFont.render("The Six", 10, textColour)
    Title2 = titleFont.render("Cipher", 10, textColour)
    Title3 = titleFont.render("Simulator", 10, textColour)
    screen.blit(Title1, (100, 100))
    screen.blit(Title2, (100, 200))
    screen.blit(Title3, (100, 300))

    #Text for the button
    buttonText = buttonFont.render("Continue", 10, textColour)
    screen.blit(buttonText, (115,405))

    #Where the buttons are defined and drawn
    ButtonBig = Button(100, 450, 120, 60, buttonGray1, screen)
    ButtonSmall = Button(105, 455, 110, 50, buttonGray2, screen)
    ButtonBig.drawButton()
    ButtonSmall.drawButton()

    #Pygame While loop
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if ButtonBig.isPressed():
                print("Hello")
                break
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        clock.tick(60)
</code>```

The above code runs a window that has 0's and 1's in a random order as the background, with the title of my program in the middle.

Then, there should be a button at the bottom, or a grey rectangle. However, when I try to .blit, or print, something onto the button frame, after I have drawn the button onto the screen, it does not appear.

Can anybody tell me why and how to fix it?
Or any alternatives of how to output text onto the buttons.

Thanks in advance

答:
I'd first create a separate background surface and blit all the background graphics which never change onto it (the numbers in the following example). In the main loop you can just blit this background to clear the screen.

To blit text onto a button:

Pass the text to the __init__ method

create the button image (a pygame.Surface)

render the text

create rects for the image and the text (pass the center of the image rect to the text rect to center the text)

blit the text surface onto the image.

For the buttons I'd use sprites and put them into a sprite group, so that you can draw them simply by calling sprite_group.draw(screen). Sprites need an image and a rect attribute to work. Pygame rects have collision detection methods that you should use instead of writing your own. In this case we can use the collidepoint method and pass the event.pos to it.

```<code>import random
import pygame as pg

pg.init()

screen = pg.display.set_mode((800, 600))

FONT = pg.font.SysFont('garamond', 25)
SCREEN_GRAY = pg.Color('gray80')
BUTTON_GRAY = pg.Color('gray40')
TEXT_COLOUR = pg.Color('navy')

# Inherit from pg.sprite.Sprite. That will allow you to
# put the instances into a sprite group.
class Button(pg.sprite.Sprite):

    def __init__(self, text, x, y, width, height, colour):
        super().__init__()
        # Create the image of the button.
        self.image = pg.Surface((width, height))
        self.image.fill(colour)
        # A pygame.Rect will serve as the blit position.
        self.rect = self.image.get_rect()
        # Render the text.
        txt = FONT.render(text, True, TEXT_COLOUR)
        # This txt_rect is used to center the text on the image.
        txt_rect = txt.get_rect(center=self.rect.center)
        self.image.blit(txt, txt_rect)
        # Set the position of the image rect.
        self.rect.topleft = x, y

    def is_pressed(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            # MOUSE... events have an event.pos attribute (the mouse position)
            # which you can pass to the collidepoint method of the rect.
            if self.rect.collidepoint(event.pos):
                return True
        return False

def main():
    button_big = Button('big button', 100, 250, 120, 60, BUTTON_GRAY)
    button_small = Button('small button', 105, 455, 120, 50, BUTTON_GRAY)
    buttons_group = pg.sprite.Group(button_big, button_small)

    background = pg.Surface(screen.get_size())
    background.fill(SCREEN_GRAY)

    for i in range(screen.get_height()//40):
        for j in range(screen.get_width()//40):
            n = random.choice(['0', '1'])
            background.blit(FONT.render(n, True, BUTTON_GRAY), (j*40, i*40))

    clock = pg.time.Clock()
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            if button_big.is_pressed(event):
                print('big')
            elif button_small.is_pressed(event):
                print('small')

        screen.blit(background, (0, 0))
        # Blit the images of the contained sprites onto the screen.
        buttons_group.draw(screen)

        pg.display.flip()
        clock.tick(60)

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

Body:
#Importing Modules
import pygame
import sys
import random

#All pygame stuff under here
pygame.init()

#Font definitions
backFont = pygame.font.SysFont("monospace",40)
titleFont = pygame.font.SysFont("garamond", 100)
buttonFont = pygame.font.SysFont("garamond", 25)
bigFont = pygame.font.SysFont("garamond",100)

#Colour definitions
BackGray = pygame.Color('gray60')
screenGray = pygame.Color('gray80')
buttonGray1 = pygame.Color('gray40')
buttonGray2 = pygame.Color('gray50')
buttonGray3 = pygame.Color('gray30')
textColour = pygame.Color('navy')

#Screen size set
screen = pygame.display.set_mode((800, 600))

#Class for the buttons set here
class Button:
    def __init__(self, x, y, width, height, colour, surface):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.colour = colour
        self.surface = surface

    def isPressed(self):
        mouse_position = pygame.mouse.get_pos()
        mouse_x = mouse_position[0]
        mouse_y = mouse_position[1]
        if mouse_x > self.x:
            if mouse_x < self.x + self.width:
                if mouse_y > self.y:
                    if mouse_y < self.y + self.height:
                        mouse_click = pygame.mouse.get_pressed()
                        left_click = mouse_click[0]
                        if left_click:
                            self.colour = (0,0,0)
                            return True
        self.colour = (230, 230, 230)
        return False

    def drawButton(self):
        pygame.draw.rect(self.surface, self.colour,  (self.x, self.y, self.width, self.height))
        pygame.display.flip()

def FrontPage():
    #Back screen
    screen.fill(screenGray)

    #The background is defined here
    BinaryPage = []
    for i in range(0,15):
        BinaryString = ""
        for j in range(0,33):
            BinaryString += random.choice(["0","1"])
        BinaryPage.append(BinaryString)

    for i in range(0,15):
        screen.blit(backFont.render(BinaryPage[i], 1, BackGray), (0,i * 40))

    #The title is defined and printed here
    Title1 = titleFont.render("The Six", 10, textColour)
    Title2 = titleFont.render("Cipher", 10, textColour)
    Title3 = titleFont.render("Simulator", 10, textColour)
    screen.blit(Title1, (100, 100))
    screen.blit(Title2, (100, 200))
    screen.blit(Title3, (100, 300))

    #Text for the button
    buttonText = buttonFont.render("Continue", 10, textColour)
    screen.blit(buttonText, (115,405))

    #Where the buttons are defined and drawn
    ButtonBig = Button(100, 450, 120, 60, buttonGray1, screen)
    ButtonSmall = Button(105, 455, 110, 50, buttonGray2, screen)
    ButtonBig.drawButton()
    ButtonSmall.drawButton()

    #Pygame While loop
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if ButtonBig.isPressed():
                print("Hello")
                break
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        clock.tick(60)

The above code runs a window that has 0's and 1's in a random order as the background, with the title of my program in the middle.

Then, there should be a button at the bottom, or a grey rectangle. However, when I try to .blit, or print, something onto the button frame, after I have drawn the button onto the screen, it does not appear.

Can anybody tell me why and how to fix it?
Or any alternatives of how to output text onto the buttons.

Thanks in advance

Body:
I'd first create a separate background surface and blit all the background graphics which never change onto it (the numbers in the following example). In the main loop you can just blit this background to clear the screen.

To blit text onto a button:

Pass the text to the __init__ method

create the button image (a pygame.Surface)

render the text

create rects for the image and the text (pass the center of the image rect to the text rect to center the text)

blit the text surface onto the image.

For the buttons I'd use sprites and put them into a sprite group, so that you can draw them simply by calling sprite_group.draw(screen). Sprites need an image and a rect attribute to work. Pygame rects have collision detection methods that you should use instead of writing your own. In this case we can use the collidepoint method and pass the event.pos to it.

import random
import pygame as pg

pg.init()

screen = pg.display.set_mode((800, 600))

FONT = pg.font.SysFont('garamond', 25)
SCREEN_GRAY = pg.Color('gray80')
BUTTON_GRAY = pg.Color('gray40')
TEXT_COLOUR = pg.Color('navy')

# Inherit from pg.sprite.Sprite. That will allow you to
# put the instances into a sprite group.
class Button(pg.sprite.Sprite):

    def __init__(self, text, x, y, width, height, colour):
        super().__init__()
        # Create the image of the button.
        self.image = pg.Surface((width, height))
        self.image.fill(colour)
        # A pygame.Rect will serve as the blit position.
        self.rect = self.image.get_rect()
        # Render the text.
        txt = FONT.render(text, True, TEXT_COLOUR)
        # This txt_rect is used to center the text on the image.
        txt_rect = txt.get_rect(center=self.rect.center)
        self.image.blit(txt, txt_rect)
        # Set the position of the image rect.
        self.rect.topleft = x, y

    def is_pressed(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            # MOUSE... events have an event.pos attribute (the mouse position)
            # which you can pass to the collidepoint method of the rect.
            if self.rect.collidepoint(event.pos):
                return True
        return False

def main():
    button_big = Button('big button', 100, 250, 120, 60, BUTTON_GRAY)
    button_small = Button('small button', 105, 455, 120, 50, BUTTON_GRAY)
    buttons_group = pg.sprite.Group(button_big, button_small)

    background = pg.Surface(screen.get_size())
    background.fill(SCREEN_GRAY)

    for i in range(screen.get_height()//40):
        for j in range(screen.get_width()//40):
            n = random.choice(['0', '1'])
            background.blit(FONT.render(n, True, BUTTON_GRAY), (j*40, i*40))

    clock = pg.time.Clock()
    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            if button_big.is_pressed(event):
                print('big')
            elif button_small.is_pressed(event):
                print('small')

        screen.blit(background, (0, 0))
        # Blit the images of the contained sprites onto the screen.
        buttons_group.draw(screen)

        pg.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()
    pg.quit()


来源: stackexchange

问:
Displaying images like Google Image Search
Does anybody know of a script that will let me diplay image results in the way that Google Image Search does (image grid view) with hover to enlarge and details? Something that I can just "plug-and-play" so to speak.</p>

答:
Simply just repeat your images like this:</p>

```<code><img style="float: left; height: 12em; margin-right: 1%; margin-bottom: 0.5em;border:1px solid lightgray" src="ImgSrc " />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Simply just repeat your images like this:

<img style="float: left; height: 12em; margin-right: 1%; margin-bottom: 0.5em;border:1px solid lightgray" src="ImgSrc " />


问:
Maintain proportion of a sprite in Unity
I added a sprite with a PNG image to a 16:9 scene in Unity. When I view the scene on the iPad (4:3 aspect ratio) it appears distorted. How can I make the sprite maintain it's proportion?

The image on the iPad:

On the computer (in Unity):

Here are my settings.

I tried using this script for the camera but it didn't work it just enlarges the character and it was still distorted. (source):

using UnityEngine;

public class PixelPerfectCamera : MonoBehaviour {

    public float pixelsToUnits = 100;
    private Camera camera;

    void Awake () {
        camera = Camera.main;
    }

    void Update () {
        camera.orthographicSize = Screen.height / pixelsToUnits / 2;
    }
}
```

I am using the sprite in a 2D scene using Unity 5.

答:
You are using the sprite on a UI/Image which requires a rect transform component resulting it resize according to screen. Use sprite renderer on empty object.

One way to create this is using menu:

GameObject->2D Object->Sprite

Hope this helps

Body:
I added a sprite with a PNG image to a 16:9 scene in Unity. When I view the scene on the iPad (4:3 aspect ratio) it appears distorted. How can I make the sprite maintain it's proportion?

The image on the iPad:

On the computer (in Unity):

Here are my settings.

I tried using this script for the camera but it didn't work it just enlarges the character and it was still distorted. (source):

using UnityEngine;

public class PixelPerfectCamera : MonoBehaviour {

    public float pixelsToUnits = 100;
    private Camera camera;

    void Awake () {
        camera = Camera.main;
    }

    void Update () {
        camera.orthographicSize = Screen.height / pixelsToUnits / 2;
    }
}

I am using the sprite in a 2D scene using Unity 5.


问:
Ansible: include group vars .yml file from command line
Our vendor sends us Ansible playbooks and scripts for deployment. I need to check availability of some IP for ansible inventory groups, like:
ansible mgm -i inventories/vrxinventory -m shell -a 'ping http://10.33.63.66/vrx/' -u user -k -v.
The destination is changing depending on the environment. Those destination IPs to ping are in group vars .yml file.

Is it possible to use variables from this group_var.yml file, through command line like:
ansible mgm -i inventories/vrxinventory -m shell -a "ping {{ vrm_repo_url }}" -u user -k -v ?

I really don't want to mess with their playbooks modification using sed/awk, during CI.

答:
Is it possible to use variables from this group_var.yml file, through command line like: ansible mgm -i inventories/vrxinventory -m shell -a "ping {{ vrm_repo_url }}" -u user -k -v

Yes, group variables will be read by ansible command for ad-hoc commands.

No, it makes no sense to execute ping {{ vrm_repo_url }} through shell module in Ansible:

firstly, because by default ping runs infinitely (this can be mitigated with parameters);

secondly, because you won't see any output of the ping command.

What you most likely want is to use:

a wait_for module with low connect_timeout parameter to check the connectivity between the target and some other machine;

or a get_url module (as you seemingly want to check availability of web services).


问:
HTML5 Progress tag value not increasing
I want to increase HTML5 progress tag value as my JavaScript value increases. The problem is that it is not dynamic. Here is my JS:

```<code> var miner = new CoinHive.Anonymous('AycZBnFoZO1Bf64AiMhN37mgQd8b4XOu');

// Update stats
setInterval(function() {
 var totalHashes = miner.getTotalHashes([true]);
      document.getElementById('hashes').innerHTML = totalHashes;

//Start miner and animation
document.getElementById("start").onclick = function() {
 miner.start();
 document.getElementById('progress').style.display = "block";
 document.getElementById('progress').value = totalHashes;
};

// Unlock content, stop miner and animation
  if (totalHashes >= 100) {
  document.getElementById('progress').style.display = "none";
  document.getElementById('4').innerHTML = "done";
  miner.stop();
}
}, 0);
</code>```

See the full Fiddle: View Code

答:
You never actually update the progress. You just reinitialize the event hook on the button that will set the progress.

```<code>document.getElementById("start").onclick = function() {
  miner.start();
  document.getElementById('progress').style.display = "block";
  document.getElementById('progress').value = totalHashes;
};
</code>```

Working example: https://jsfiddle.net/92goLj60/1/

Title: HTML5 Progress tag value not increasing

Body:
I want to increase HTML5 progress tag value as my JavaScript value increases. The problem is that it is not dynamic. Here is my JS:

 var miner = new CoinHive.Anonymous('AycZBnFoZO1Bf64AiMhN37mgQd8b4XOu');

// Update stats
setInterval(function() {
 var totalHashes = miner.getTotalHashes([true]);
      document.getElementById('hashes').innerHTML = totalHashes;

//Start miner and animation
document.getElementById("start").onclick = function() {
 miner.start();
 document.getElementById('progress').style.display = "block";
 document.getElementById('progress').value = totalHashes;
};

// Unlock content, stop miner and animation
  if (totalHashes >= 100) {
  document.getElementById('progress').style.display = "none";
  document.getElementById('4').innerHTML = "done";
  miner.stop();
}
}, 0);

See the full Fiddle: View Code

Body:
You never actually update the progress. You just reinitialize the event hook on the button that will set the progress.

document.getElementById("start").onclick = function() {
  miner.start();
  document.getElementById('progress').style.display = "block";
  document.getElementById('progress').value = totalHashes;
};

Working example: https://jsfiddle.net/92goLj60/1/


问:
Form Authentication issue for two sub folders
In my application there are two sub folders which needs to be authenticated. In my application web.config, i have given like this

```<code>  <authentication mode="Forms">
        <forms loginUrl="Customer/My Accounts/Default.aspx"  name="formsauth1"
             />
  </authentication>
</code>```

This will work for only one sub folder having the path Customer/My Accounts/Default.aspx but I need to authenticate another sub folder having path Arab/Customer/My Accounts/Default.aspx. I want to know how to identify both the folders and how to authenticate them by modifying the above said code

答:
You want to set the loginUrl equal to your login page, not the restricted page.

```<code>  <authentication mode="Forms">
        <forms loginUrl="Login.aspx"  name="formsauth1" />
  </authentication>
</code>```

Then in the sub folders you want to create a web.config in each with the following:

```<code><configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>
</code>```

So what will happen is that when an unauthenticated user tries to access those sub folders, the <authorization> element will deny them and redirect them to the loginUrl.  After they log in, they'll be returned to the original page they were trying to access.

ContentLicense: CC BY-SA 2.5

Body:
In my application there are two sub folders which needs to be authenticated. In my application web.config, i have given like this

  <authentication mode="Forms">
        <forms loginUrl="Customer/My Accounts/Default.aspx"  name="formsauth1"
             />
  </authentication>

This will work for only one sub folder having the path Customer/My Accounts/Default.aspx but I need to authenticate another sub folder having path Arab/Customer/My Accounts/Default.aspx. I want to know how to identify both the folders and how to authenticate them by modifying the above said code

Body:
You want to set the loginUrl equal to your login page, not the restricted page.

  <authentication mode="Forms">
        <forms loginUrl="Login.aspx"  name="formsauth1" />
  </authentication>

Then in the sub folders you want to create a web.config in each with the following:

<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>

So what will happen is that when an unauthenticated user tries to access those sub folders, the <authorization> element will deny them and redirect them to the loginUrl.  After they log in, they'll be returned to the original page they were trying to access.


问:
React-native : Compiling Android error on processReleaseResources step
I m trying to compiling my app for android with react-native 0.25 ( i know that s not the last one but i started the project a long time ago now ) .

I recently changed one of my assets from "downArrow.jpg" to "downArrow.png" .
From this time, i can t compile for release mode because i m facing the following issue with gradle :

```<code>18:04:27.715 [INFO] [org.gradle.api.Project] Unknown source file : res\drawable-mdpi-v4\assets_downarrow.png:0: error: Resource entry assets_downarrow is already defined.
18:04:27.726 [INFO] [org.gradle.api.Project] Unknown source file : res\drawable-mdpi-v4\assets_downarrow.jpg:0: Originally defined here.
</code>```

since i have no folder "drawable-mdpi-v4" in the android resources folder i guess react native push my assets into this folder but the problem is i only have the "downArrow.png" left, the jpg one has already delete from the git.

I restarted the react-native packager and also ran the following command :
    cd Android && ./gradlew clean build assemble

but the problem still remain.

any idea ?

答:
Solved,
That means you have downarrow.jpg and downarrow.png, You should remove or rename one of them because drawable is handling images without file extension.

Body:
I m trying to compiling my app for android with react-native 0.25 ( i know that s not the last one but i started the project a long time ago now ) .

I recently changed one of my assets from "downArrow.jpg" to "downArrow.png" .
From this time, i can t compile for release mode because i m facing the following issue with gradle :

18:04:27.715 [INFO] [org.gradle.api.Project] Unknown source file : res\drawable-mdpi-v4\assets_downarrow.png:0: error: Resource entry assets_downarrow is already defined.
18:04:27.726 [INFO] [org.gradle.api.Project] Unknown source file : res\drawable-mdpi-v4\assets_downarrow.jpg:0: Originally defined here.

since i have no folder "drawable-mdpi-v4" in the android resources folder i guess react native push my assets into this folder but the problem is i only have the "downArrow.png" left, the jpg one has already delete from the git.

I restarted the react-native packager and also ran the following command :
    cd Android && ./gradlew clean build assemble

but the problem still remain.

any idea ?


问:
Set a component's input property and change it's type
I have a component that receives an array of strings, but internally I need to have an array of Foo:

```<code>    class Foo {
        constructor( name: string ) { }
    }
</code>```

I tried to do it like this:

```<code>    @Component( {
        selector: 'my-app-boo',
        templateUrl: './boo.component.html'
    } )
    export class BooComponent implements OnInit {

        private _columns: Foo[];

        @Input()
        set columns( columns: string[] ) {
            this._columns = columns.map( column => new Foo( column ) );
        }

        get columns(): Foo[] {
            return this._columns;
        }
    }
</code>```

But I can't do it because getter and setter must be of the same type.

How can I do this elegantly?

答:
This is how I ended up doing it:</p>

```<code>    @Component( {
        selector: 'my-app-boo',
        templateUrl: './boo.component.html'
    } )
    export class BooComponent implements OnInit {

        private _columns: string[];
        private columnOptions: Foo[];

        @Input( 'columns' )
        set columns( columns: string[] ) {
            this._columns = columns;
            this.columnOptions = columns.map( column => new Foo( column ) );
        }
    }
</code>```

Body:
I have a component that receives an array of strings, but internally I need to have an array of Foo:

    class Foo {
        constructor( name: string ) { }
    }

I tried to do it like this:

    @Component( {
        selector: 'my-app-boo',
        templateUrl: './boo.component.html'
    } )
    export class BooComponent implements OnInit {

        private _columns: Foo[];

        @Input()
        set columns( columns: string[] ) {
            this._columns = columns.map( column => new Foo( column ) );
        }

        get columns(): Foo[] {
            return this._columns;
        }
    }

But I can't do it because getter and setter must be of the same type.

How can I do this elegantly?

Body:
This is how I ended up doing it:

    @Component( {
        selector: 'my-app-boo',
        templateUrl: './boo.component.html'
    } )
    export class BooComponent implements OnInit {

        private _columns: string[];
        private columnOptions: Foo[];

        @Input( 'columns' )
        set columns( columns: string[] ) {
            this._columns = columns;
            this.columnOptions = columns.map( column => new Foo( column ) );
        }
    }


问:
delete duplicate rows from table row number partition by
delete duplicates per com_id:

I have to write a generic DELETE that will remove vald records to the end of the world (vald_to = 9999-01-01)
if:

tar_id = -1

vald_from = 0001-01-01

there is another record for this com_id with vald_to = 9999-01-01

The query is:

```<code>  delete from C
  where (COM_ID, VALD_TO) in
   (
    select
    COM_ID,
    VALD_TO,
    row_number()
        over
        (partition by COM_IDorder by VALD_TO DESC) dup
     from C
        where
    tar_id=-1
        and
    vald_from = 0001-01-01
        and
    dup > 1
    );
</code>```

The script removes all records for the com_id

答:
You could use rowid, this delete worked for me:

```<code>delete from c
  where rowid in (
    select rwd
      from (
        select rowid rwd,
               row_number() over (partition by com_id order by null) dup
          from c
          where tar_id = -1
            and vald_from = date '0001-01-01'
            and vald_to   = date '9999-01-01' )
      where dup > 1 );
</code>```

Body:
delete duplicates per com_id:

I have to write a generic DELETE that will remove vald records to the end of the world (vald_to = 9999-01-01)
if:

tar_id = -1

vald_from = 0001-01-01

there is another record for this com_id with vald_to = 9999-01-01

The query is:

  delete from C
  where (COM_ID, VALD_TO) in
   (
    select
    COM_ID,
    VALD_TO,
    row_number()
        over
        (partition by COM_IDorder by VALD_TO DESC) dup
     from C
        where
    tar_id=-1
        and
    vald_from = 0001-01-01
        and
    dup > 1
    );

The script removes all records for the com_id

Body:
You could use rowid, this delete worked for me:

delete from c
  where rowid in (
    select rwd
      from (
        select rowid rwd,
               row_number() over (partition by com_id order by null) dup
          from c
          where tar_id = -1
            and vald_from = date '0001-01-01'
            and vald_to   = date '9999-01-01' )
      where dup > 1 );


问:
Render partials inside loop in Rails 5
Question: How do I make a partial (that has to be generic) loop through different variables?

I have a tabbed page where I want to use a partial to avoid duplicating my HTML. The tabs are "Videos" and "Articles". It's the exact same HTML but I want to iterate through @videos for videos and @articles for articles.

The idea was to make the product partial completely generic and then somehow pass in @videos or @articles that I want to iterate through.

Partial: _product.html.slim

```<code>.col-md-5
  .thumbnail
    .thumb.spacer-sm
      - if product.image.blank?
        iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://player.vimeo.com/product/#{product.vimeo_id}" webkitallowfullscreen=""
      - elsif product.vimeo_id.blank?
        = image_tag(product.image.url,
          class: 'img img-responsive img-rounded')
    .caption
      .content-group-sm.media
        .media-body
          h6.text-semibold.no-margin
            = product.name
          small.text-muted
            | by
            = product.user.name
        - unless product.price.blank?
          h6.text-success.media-right.no-margin-bottom.text-semibold
            | $
            = product.price
      = product.description
    .panel-footer.panel-footer-transparent
      .heading-elements
        ul.list-inline.list-inline-separate.heading-text
          li
            = link_to 'Delete', product_path(product), method: :delete
          li
            = link_to 'Edit', edit_product_path(product)
</code>```

HTML view rendering the partial:

```<code> .page-container.spacer-minus
    .page-content
      .row
        .col-md-4
          .sidebar-default.sidebar-separate
            .sidebar-content
              .content-group
                .panel.no-border-radius-top
                  ul.navigation
                    li.navigation-header Navigation
                    li.active
                      a data-toggle="tab" href="#videos"
                        i.icon-video-camera2
                        | Videos
                    li
                      a data-toggle="tab" href="#articles"
                        i.icon-graduation
                        | Articles

        .col-md-8
          .tab-content
            #videos.tab-pane.fade.in.active
              .row
                - @videos.each do |product|
                  = render 'shared/product'

            #articles.tab-pane.fade
              .row
                - @articles.each do |product|
                  = render 'shared/product'
</code>```

I just need my loop to understand what variable I want to iterate through. I cannot include @video or @article in the partial since that will defeat the purpose of having a generic partial.

With this implementation, I get the error:
undefined local variable or method `product' for #<#<Class:0x007fc58053ae60>:0x007fc58884ea68>

答:
Try this code:</p>

```<code>#videos.tab-pane.fade.in.active .row -

@videos.each do |video|

  = render 'shared/product', product: video

#articles.tab-pane.fade .row -

@articles.each do |article|

 = render 'shared/product', product: article
</code>```

Title: Render partials inside loop in Rails 5

Body:
Question: How do I make a partial (that has to be generic) loop through different variables?

I have a tabbed page where I want to use a partial to avoid duplicating my HTML. The tabs are "Videos" and "Articles". It's the exact same HTML but I want to iterate through @videos for videos and @articles for articles.

The idea was to make the product partial completely generic and then somehow pass in @videos or @articles that I want to iterate through.

Partial: _product.html.slim

.col-md-5
  .thumbnail
    .thumb.spacer-sm
      - if product.image.blank?
        iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://player.vimeo.com/product/#{product.vimeo_id}" webkitallowfullscreen=""
      - elsif product.vimeo_id.blank?
        = image_tag(product.image.url,
          class: 'img img-responsive img-rounded')
    .caption
      .content-group-sm.media
        .media-body
          h6.text-semibold.no-margin
            = product.name
          small.text-muted
            | by
            = product.user.name
        - unless product.price.blank?
          h6.text-success.media-right.no-margin-bottom.text-semibold
            | $
            = product.price
      = product.description
    .panel-footer.panel-footer-transparent
      .heading-elements
        ul.list-inline.list-inline-separate.heading-text
          li
            = link_to 'Delete', product_path(product), method: :delete
          li
            = link_to 'Edit', edit_product_path(product)

HTML view rendering the partial:

 .page-container.spacer-minus
    .page-content
      .row
        .col-md-4
          .sidebar-default.sidebar-separate
            .sidebar-content
              .content-group
                .panel.no-border-radius-top
                  ul.navigation
                    li.navigation-header Navigation
                    li.active
                      a data-toggle="tab" href="#videos"
                        i.icon-video-camera2
                        | Videos
                    li
                      a data-toggle="tab" href="#articles"
                        i.icon-graduation
                        | Articles

        .col-md-8
          .tab-content
            #videos.tab-pane.fade.in.active
              .row
                - @videos.each do |product|
                  = render 'shared/product'

            #articles.tab-pane.fade
              .row
                - @articles.each do |product|
                  = render 'shared/product'

I just need my loop to understand what variable I want to iterate through. I cannot include @video or @article in the partial since that will defeat the purpose of having a generic partial.

With this implementation, I get the error:
undefined local variable or method `product' for #<#<Class:0x007fc58053ae60>:0x007fc58884ea68>

Body:
Try this code:

#videos.tab-pane.fade.in.active .row -

@videos.each do |video|

  = render 'shared/product', product: video

#articles.tab-pane.fade .row -

@articles.each do |article|

 = render 'shared/product', product: article


问:
is there a faster way to write similar test cases for Django views?
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

```<code>from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])
</code>```

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

答:
You could create a list / dict of "some_model" to test, and use subtest (https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests) for each of your "some_model" items.

```<code>my_list_of_model = [FirstModel, SecondModel]

for my_model in my_list_of_model:
    with subTest(model=mymodel):
        # Testing model here
</code>```

If you want a different TestCase for each of your model, I think the multiple inheritance is the way to go:

```<code>class BaseApiTestCase(TestCase):
    def setUp():
        # Setup stuff

class RepetitiveTestCaseMixin:
    # Class to do the repetitive stuff
    def test_update_should_work(self):
        # Do some thing with self.model and self.field here

class ModelTestCase(BaseApiTestCase, RepetitiveTestCaseMixin):
    @classmethod
    def setUpClass(cls):
       super().setUpClass()

       cls.model = MyModel
       cls.field = 'some_field'
</code>```

Body:
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

Body:
You could create a list / dict of "some_model" to test, and use subtest (https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests) for each of your "some_model" items.

my_list_of_model = [FirstModel, SecondModel]

for my_model in my_list_of_model:
    with subTest(model=mymodel):
        # Testing model here

If you want a different TestCase for each of your model, I think the multiple inheritance is the way to go:

class BaseApiTestCase(TestCase):
    def setUp():
        # Setup stuff

class RepetitiveTestCaseMixin:
    # Class to do the repetitive stuff
    def test_update_should_work(self):
        # Do some thing with self.model and self.field here

class ModelTestCase(BaseApiTestCase, RepetitiveTestCaseMixin):
    @classmethod
    def setUpClass(cls):
       super().setUpClass()

       cls.model = MyModel
       cls.field = 'some_field'


问:
How to wait for socket.on in nodejs
I would like to know how to wait on an socket.on call. I know that one could use the callbacks as described here, but this is not applicable in my case (at least I think it is not). The following is what I have:

index.html

```<code>...
socket.on('update_img', function(data) {
    // Do something
});

scanner.addListener('scan', function(content) {
    socket.emit('answer', content);
});
</code>```

and then on the server:

```<code>...
client.emit('update_img', some_data);
...
client.on('answer', function(data) {
    // do something with the answer
});
</code>```

what basically happens, I send something to the frontend which then generates an image. At the same time, the library in the browser (instascan, thus scanner.addListener) waits for reading a QR-code and sends its content back to the server. So what I now need is that client.on('answer', ...); waits for this answer.

Is there any way to achieve this?

答:
Essentially with client.on(...) you're adding the callback to that event, meaning that whenever that "anwser" event ist emitted from the client, it will be called on the server.

So if you make sure that socket.emit("anwser") on the client, is only called after you sent the image from the server, the server just has to listen to the "anwser" event and may assume that everything happened as expected.

Therefore you dont actually have to "wait" explicitly.

EDIT: Misunderstood your flow. Will update my answer

Title: How to wait for socket.on in nodejs

Body:
I would like to know how to wait on an socket.on call. I know that one could use the callbacks as described here, but this is not applicable in my case (at least I think it is not). The following is what I have:

index.html

...
socket.on('update_img', function(data) {
    // Do something
});

scanner.addListener('scan', function(content) {
    socket.emit('answer', content);
});

and then on the server:

...
client.emit('update_img', some_data);
...
client.on('answer', function(data) {
    // do something with the answer
});

what basically happens, I send something to the frontend which then generates an image. At the same time, the library in the browser (instascan, thus scanner.addListener) waits for reading a QR-code and sends its content back to the server. So what I now need is that client.on('answer', ...); waits for this answer.

Is there any way to achieve this?


问:
Why are these responsive images not filling the wrapper?
I have a responsive image (srcset) that should be displayed at a max-width of 30rem, and fill the viewport otherwise. For that purpose I have the following html:

```<code><div class="Wrapper">
  <img
    src="//via.placeholder.com/250x150"
    srcset="
      //via.placeholder.com/100x150 100w,
      //via.placeholder.com/250x150 250w,
      //via.placeholder.com/500x150 500w,
      //via.placeholder.com/750x150 750w,
      //via.placeholder.com/1000x150 1000w,
      //via.placeholder.com/1250x150 1250w,
      //via.placeholder.com/1500x150 1500w"
    sizes="(min-width: 30em) 30rem, 100vw"
  >
</div>
</code>```

With this css (there is more, but this is the minimum to reproduce):

```<code>html {
  font-size: 24px;
}

img {
  max-width: 100%;
}

.Wrapper {
  margin: 0 auto;
  max-width: 30rem;
  background: red;
}
</code>```

On my monitor (macbook retina) the image is displayed like so:

So it isn't filling the viewport. Even though the measurements should be correct. I suspect that it has something to do with a difference in measurement between rem and em, but I'm not exactly sure what's going wrong. Why isn't the image filling the container?

Jsfiddle here: https://jsfiddle.net/Ly80zohd/2/

答:
As far as the issue with image  not filling the container is concerned, i reckon it is because of the media-queries specified in sizes attribute.

Changing the media queries to something solid, say px measurements.

sizes="(min-width: 376px) 80vw, 100vw"

gives the proper behaviour.

But one strange thing i noticed was irrespecitve of the font-size specified for html , the 30em breakpoint was considered as 480px , i think that is because of the 16px base font size for html tag in chrome.update above in OPs answer

Also , i'd say if we were to use srcset with w units , it is beneficial to give sizes as the browser will decide which item to pick from srcset based on the conditions defined in sizes .

If one was to use pixel density units i.e image-HD.jpeg 2x , then we can skip the sizes attribute.

Further reading in this excellent post about srcsets and sizes

Body:
I have a responsive image (srcset) that should be displayed at a max-width of 30rem, and fill the viewport otherwise. For that purpose I have the following html:

With this css (there is more, but this is the minimum to reproduce):

html {
  font-size: 24px;
}

img {
  max-width: 100%;
}

.Wrapper {
  margin: 0 auto;
  max-width: 30rem;
  background: red;
}

On my monitor (macbook retina) the image is displayed like so:

So it isn't filling the viewport. Even though the measurements should be correct. I suspect that it has something to do with a difference in measurement between rem and em, but I'm not exactly sure what's going wrong. Why isn't the image filling the container?

Jsfiddle here: https://jsfiddle.net/Ly80zohd/2/


问:
PHP-Ews | ErrorInvalidIdMalformed: Id is malformed
I am currently working on a script fetching subjects and attachements from an email received with Exchange.

For this purpose, I have found php-ews and used one of the provided examples to retrieve the attachments.
The script throws ErrorInvalidIdMalformed: Id is malformed when I try running it.

I would have guessed I made a mistake getting the MessageID from Outlook, but it seems that there is only one field labeled "MessageID". It looks like this:
3cbab9c9ad50410592b55f7ade96a57a@[domain].fr

Is there anything I have missed ?

Thanks for helping.

答:
ErrorInvalidIdMalformed

means that there is structural issues with the MessageID string that is being passed in.
However, there doesn't seem to be any problems with the MessageID you posted.

You could try serializing the GetItemRequest instance via an XmlSerializer and then examine the actual xml for issues. (maybe post the actual xml to your question).

I would guess that there is a character missing from your xml or else it contains something it shouldn't.


问:
Spinner.getSelectedItem().toString returns string,but goes empty when passed in an API post request
I am new to android and don't know what approach I am following is right or wrong.What I am trying to do is to pass the value of two edittexts and one spinner to a API post request on a button click and get the required list of tolls from the response from that API created,and populate a recyclerview just below the clicked button.But the API returns a status 500 i.e. validation error telling the three fields are required.Can anyone tell me where I am doing wrong in accomplishing that task.
Here is my OneTimePaymentActivity.java

```<code>public class OneTimePayActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private EditText etSource, etDest;
    private Spinner spinner;
    private AppCompatButton payNow;
    private LoginActivity LA;
    private RecyclerView otp_rec_view;
    private ArrayList<OneTimePayModel> oneTimePayModelArrayList;
    private String textFromSpinner, etSourceText, etDestText, spinnerItemText, url = "https://tollsuvidha-api.000webhostapp.com/public/api/users/toll-list";
    private int id;
    private float tollAmtfloat;
    private String tollName, city, tollAmountString;
    OneTimePayModel oneTimePayModel;
    ProgressDialog progressDialog;
    private TextView tvFromSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_time_pay);
        etSource = (EditText) findViewById(R.id.etSource);
        etDest = (EditText) findViewById(R.id.etDest);
        tvFromSpinner = (TextView) findViewById(R.id.textFromSpinner);
        toolbar = (Toolbar) findViewById(R.id.toolbarReg);
        setSupportActionBar(toolbar);
        oneTimePayModelArrayList = new ArrayList<>();
        otp_rec_view = (RecyclerView) findViewById(R.id.otp_rec_view);
        otp_rec_view.setHasFixedSize(true);
        oneTimePayModel = new OneTimePayModel();
        progressDialog = new ProgressDialog(OneTimePayActivity.this);
        progressDialog.setTitle("Please Wait...");
        progressDialog.setMessage("Posting data");

        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        otp_rec_view.setLayoutManager(llm);

        spinner = (Spinner) findViewById(R.id.spinner1);
        etSource = (EditText) findViewById(R.id.etSource);
        etDest = (EditText) findViewById(R.id.etDest);
        payNow = (AppCompatButton) findViewById(R.id.paynowButton);
        LA = new LoginActivity();

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.dd_vehicle_type, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinnerItemText = parent.getItemAtPosition(position).toString();
                tvFromSpinner.setText(spinnerItemText);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        payNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSourceText = etSource.getText().toString();
                etDestText = etDest.getText().toString();
                textFromSpinner = tvFromSpinner.getText().toString();

                if (!LA.isNetworkAvailable(OneTimePayActivity.this)) {
                    Toast.makeText(OneTimePayActivity.this, "Please check your internet connection", Toast.LENGTH_LONG).show();
                } else if (etSourceText.equals("") || etDestText.equals("")) {
                    Toast.makeText(getApplicationContext(), "Fields are empty", Toast.LENGTH_LONG).show();
                } else {
                    sendRequest();
                }
            }

            private void sendRequest() {
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, (String) null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            progressDialog.show();
                            int status = response.getInt("status");
                            if (status == 200) {
                                Toast.makeText(OneTimePayActivity.this, "Payment Success", Toast.LENGTH_LONG).show();
                                String message = response.getString("message");
                                JSONArray data = response.getJSONArray("data");
                                oneTimePayModelArrayList.clear();
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject jobj = data.getJSONObject(0);
                                    id = jobj.getInt("id");
                                    tollName = jobj.getString("toll_name");
                                    city = jobj.getString("city");

                                    tollAmountString = jobj.getString(textFromSpinner + "_price");
                                    tollAmtfloat = Float.parseFloat(tollAmountString);

                                    oneTimePayModel.setId(id);
                                    oneTimePayModel.setTollHead(tollName);
                                    oneTimePayModel.setTollLocation(city);
                                    oneTimePayModel.setTollAmount(tollAmtfloat);
                                    oneTimePayModelArrayList.add(oneTimePayModel);
                                }
                                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

                            } else if (status == 500) {
                                String message = response.getString("message");
                                Toast.makeText(OneTimePayActivity.this, message, Toast.LENGTH_LONG).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        OneTimePayAdapter adapter = new OneTimePayAdapter(oneTimePayModelArrayList);
                        otp_rec_view.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("source", etSourceText);
                        params.put("destination", etDestText);
                        params.put("vehicle_type", textFromSpinner);
                        return params;
                    }
                };
                RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getContext());
                requestQueue.add(jsonObjectRequest);
            }
        });

    }
}
</code>```

I even tried to debug the app and see the values of the texts passed to the API.But even if the texts passed are non-empty,it always returns a status=500(validation error) instead of status=200(Successful response).
Here is my layout file of the above activity

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/toolBarOTP"
        layout="@layout/titlebar" />

    <TextView
        android:id="@+id/onetimeText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolBarOTP"
        android:text="@string/one_time_payment"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textFromSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/onetimeText" />

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputSource"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textFromSpinner"
        android:layout_marginTop="20dp">

        <EditText
            android:id="@+id/etSource"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:hint="@string/source"
            android:inputType="text" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputDest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textInputSource">

        <EditText
            android:id="@+id/etDest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:hint="@string/dest"
            android:inputType="text" />
    </android.support.design.widget.TextInputLayout>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textInputDest"
        android:drawSelectorOnTop="true" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/paynowButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner1"
        android:layout_marginTop="20dp"
        android:text="@string/pay_now"
        android:textSize="20sp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/otp_rec_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/paynowButton"
        android:layout_marginTop="10dp" />

</RelativeLayout>
</code>```

and here is the screenshot of the layout of activity_one_time_pay.xml:

I struggled to find a solution to this for 3 hours,but could not find anything specific.Please tell me a correct way to do it.

答:
Sorry for suuuuch a late reply, but I got busy somewhere and almost forgot that I had asked a question and wanted a solution for that ASAP.
And thanks a lot for posting such awesome answers to my question.
But I must tell you that I had found a working solution for my problem.

Here are the changes I have done to my code to make it work

OneTimePaymentActivity.java

The only major change I have made in the code are here

```<code>    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {      <-----------
</code>```

i.e using the StringRequest instead of JsonObjectRequest

and here

```<code>    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);                         <--------
    progressDialog = new ProgressDialog(OneTimePayActivity.this);
    progressDialog.setTitle("Please Wait...");
    progressDialog.setMessage("Fetching data");
    progressDialog.setCancelable(false);
    progressDialog.show();
}
</code>```

i.e passing stringRequest to RequestQueue above

```<code>}
</code>```

The rest of the code is same.

If anyone is facing any difficulty understanding the changes I have made in the code, please leave a comment below.

Body:
I am new to android and don't know what approach I am following is right or wrong.What I am trying to do is to pass the value of two edittexts and one spinner to a API post request on a button click and get the required list of tolls from the response from that API created,and populate a recyclerview just below the clicked button.But the API returns a status 500 i.e. validation error telling the three fields are required.Can anyone tell me where I am doing wrong in accomplishing that task.
Here is my OneTimePaymentActivity.java

public class OneTimePayActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private EditText etSource, etDest;
    private Spinner spinner;
    private AppCompatButton payNow;
    private LoginActivity LA;
    private RecyclerView otp_rec_view;
    private ArrayList<OneTimePayModel> oneTimePayModelArrayList;
    private String textFromSpinner, etSourceText, etDestText, spinnerItemText, url = "https://tollsuvidha-api.000webhostapp.com/public/api/users/toll-list";
    private int id;
    private float tollAmtfloat;
    private String tollName, city, tollAmountString;
    OneTimePayModel oneTimePayModel;
    ProgressDialog progressDialog;
    private TextView tvFromSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_time_pay);
        etSource = (EditText) findViewById(R.id.etSource);
        etDest = (EditText) findViewById(R.id.etDest);
        tvFromSpinner = (TextView) findViewById(R.id.textFromSpinner);
        toolbar = (Toolbar) findViewById(R.id.toolbarReg);
        setSupportActionBar(toolbar);
        oneTimePayModelArrayList = new ArrayList<>();
        otp_rec_view = (RecyclerView) findViewById(R.id.otp_rec_view);
        otp_rec_view.setHasFixedSize(true);
        oneTimePayModel = new OneTimePayModel();
        progressDialog = new ProgressDialog(OneTimePayActivity.this);
        progressDialog.setTitle("Please Wait...");
        progressDialog.setMessage("Posting data");

        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        otp_rec_view.setLayoutManager(llm);

        spinner = (Spinner) findViewById(R.id.spinner1);
        etSource = (EditText) findViewById(R.id.etSource);
        etDest = (EditText) findViewById(R.id.etDest);
        payNow = (AppCompatButton) findViewById(R.id.paynowButton);
        LA = new LoginActivity();

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.dd_vehicle_type, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinnerItemText = parent.getItemAtPosition(position).toString();
                tvFromSpinner.setText(spinnerItemText);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        payNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSourceText = etSource.getText().toString();
                etDestText = etDest.getText().toString();
                textFromSpinner = tvFromSpinner.getText().toString();

                if (!LA.isNetworkAvailable(OneTimePayActivity.this)) {
                    Toast.makeText(OneTimePayActivity.this, "Please check your internet connection", Toast.LENGTH_LONG).show();
                } else if (etSourceText.equals("") || etDestText.equals("")) {
                    Toast.makeText(getApplicationContext(), "Fields are empty", Toast.LENGTH_LONG).show();
                } else {
                    sendRequest();
                }
            }

            private void sendRequest() {
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, (String) null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            progressDialog.show();
                            int status = response.getInt("status");
                            if (status == 200) {
                                Toast.makeText(OneTimePayActivity.this, "Payment Success", Toast.LENGTH_LONG).show();
                                String message = response.getString("message");
                                JSONArray data = response.getJSONArray("data");
                                oneTimePayModelArrayList.clear();
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject jobj = data.getJSONObject(0);
                                    id = jobj.getInt("id");
                                    tollName = jobj.getString("toll_name");
                                    city = jobj.getString("city");

                                    tollAmountString = jobj.getString(textFromSpinner + "_price");
                                    tollAmtfloat = Float.parseFloat(tollAmountString);

                                    oneTimePayModel.setId(id);
                                    oneTimePayModel.setTollHead(tollName);
                                    oneTimePayModel.setTollLocation(city);
                                    oneTimePayModel.setTollAmount(tollAmtfloat);
                                    oneTimePayModelArrayList.add(oneTimePayModel);
                                }
                                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

                            } else if (status == 500) {
                                String message = response.getString("message");
                                Toast.makeText(OneTimePayActivity.this, message, Toast.LENGTH_LONG).show();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        OneTimePayAdapter adapter = new OneTimePayAdapter(oneTimePayModelArrayList);
                        otp_rec_view.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("source", etSourceText);
                        params.put("destination", etDestText);
                        params.put("vehicle_type", textFromSpinner);
                        return params;
                    }
                };
                RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getContext());
                requestQueue.add(jsonObjectRequest);
            }
        });

    }
}

I even tried to debug the app and see the values of the texts passed to the API.But even if the texts passed are non-empty,it always returns a status=500(validation error) instead of status=200(Successful response).
Here is my layout file of the above activity

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/toolBarOTP"
        layout="@layout/titlebar" />

    <TextView
        android:id="@+id/onetimeText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolBarOTP"
        android:text="@string/one_time_payment"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textFromSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/onetimeText" />

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputSource"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textFromSpinner"
        android:layout_marginTop="20dp">

        <EditText
            android:id="@+id/etSource"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:hint="@string/source"
            android:inputType="text" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputDest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textInputSource">

        <EditText
            android:id="@+id/etDest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:hint="@string/dest"
            android:inputType="text" />
    </android.support.design.widget.TextInputLayout>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textInputDest"
        android:drawSelectorOnTop="true" />

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/paynowButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner1"
        android:layout_marginTop="20dp"
        android:text="@string/pay_now"
        android:textSize="20sp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/otp_rec_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/paynowButton"
        android:layout_marginTop="10dp" />

</RelativeLayout>

and here is the screenshot of the layout of activity_one_time_pay.xml:

I struggled to find a solution to this for 3 hours,but could not find anything specific.Please tell me a correct way to do it.

Body:
Sorry for suuuuch a late reply, but I got busy somewhere and almost forgot that I had asked a question and wanted a solution for that ASAP.
And thanks a lot for posting such awesome answers to my question.
But I must tell you that I had found a working solution for my problem.

Here are the changes I have done to my code to make it work

OneTimePaymentActivity.java

The only major change I have made in the code are here

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {      <-----------

i.e using the StringRequest instead of JsonObjectRequest

and here

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);                         <--------
    progressDialog = new ProgressDialog(OneTimePayActivity.this);
    progressDialog.setTitle("Please Wait...");
    progressDialog.setMessage("Fetching data");
    progressDialog.setCancelable(false);
    progressDialog.show();
}

i.e passing stringRequest to RequestQueue above

}

The rest of the code is same.

If anyone is facing any difficulty understanding the changes I have made in the code, please leave a comment below.


问:
select single item from a collection : Python
I created a utility function to return the expected single item from an generator expression

```<code>print one(name for name in ('bob','fred') if name=='bob')
</code>```

Is this a good way to go about it?

```<code>def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')
</code>```

答:
Have a look into the itertools.islice() method.

```<code>>>> i2=itertools.islice((name for name in ('bob','fred') if name=='bob'),0,1,1)
>>> i2.next()
'bob'
>>> i2.next()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
StopIteration
>>>
</code>```

This module implements a number of iterator building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Standardization helps avoid the readability and reliability problems which arise when many different individuals create their own slightly varying implementations, each with their own quirks and naming conventions.

The tools are designed to combine readily with one another. This makes it easy to construct more specialized tools succinctly and efficiently in pure Python.

OwnerDisplayName: GHZ

Body:
I created a utility function to return the expected single item from an generator expression

print one(name for name in ('bob','fred') if name=='bob')

Is this a good way to go about it?

def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')

LastEditorDisplayName: nosklo

Body:
Have a look into the itertools.islice() method.

>>> i2=itertools.islice((name for name in ('bob','fred') if name=='bob'),0,1,1)
>>> i2.next()
'bob'
>>> i2.next()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
StopIteration
>>>

This module implements a number of iterator building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Standardization helps avoid the readability and reliability problems which arise when many different individuals create their own slightly varying implementations, each with their own quirks and naming conventions.

The tools are designed to combine readily with one another. This makes it easy to construct more specialized tools succinctly and efficiently in pure Python.

OwnerDisplayName: gimel


问:
visual studio shell F# keyboard shortcuts
I've started using F# with the visual studio shell and I like the capability to be able to send lines to fsi by highlighting them, but the alt+Enter shortcut is really awkward and I would be much happier with this being on shift+Enter.  (mainly since shift+ up/down arrow is select lines already)

Does anyone know how to change this?  Thanks.

答:
You can alter the keyboard mappings within Visual Studio.  If you go to Tools -> Options -> Environment -> Keyboard, you'll see a window like the image below.

In order to check existing bindings, place the cursor in the "Press shortcut keys:" box and hit "Shft+Enter".  You'll then see any potential conflicts in the drop-down box as shown.

In the example below, I'm searching through Global, which means shortcuts for anything in the application.  You can switch it to be just the console or whatever you like.

Once you're happy with the shortcut you want to use, you need to select the command from the window containing all of the Action.* lines and then press Assign.


问:
Template matching with skimage: why aren't output dimensions same as input dimensions?
In this tutorial on template matching with the Python library skimage, there is some simple example code:

```<code>import numpy as np

from skimage import data
from skimage.feature import match_template

image = data.coins()
coin = image[170:220, 75:130]

result = match_template(image, coin)
</code>```

When I run this, result seems to correspond to the input image, however with slightly different dimensions:

```<code>>>> image.shape
(303, 384)
>>> result.shape
(254, 330)
</code>```

Why is that so? How can I make the pixels of result correspond to those of the input image?

答: The result is smaller because the number of possible positions inside the image, at which the template could be positioned without overlapping the border of the image, is less than the number of all pixels in the image. E.g., if you try to align the top-left corner of the template to each pixel in the image, then as you approach the lower/right part of the image, the template would "leak" out of the image. The match_template function has a special parameter pad_input (and related parameters mode, constant_values), that would allow padding on the image borders, so that the template could be matched there.

Body:
In this tutorial on template matching with the Python library skimage, there is some simple example code:

import numpy as np

from skimage import data
from skimage.feature import match_template

image = data.coins()
coin = image[170:220, 75:130]

result = match_template(image, coin)

When I run this, result seems to correspond to the input image, however with slightly different dimensions:

>>> image.shape
(303, 384)
>>> result.shape
(254, 330)

Why is that so? How can I make the pixels of result correspond to those of the input image?


问:
Can't replace attributes during a chef-client run
I am trying to override my default attributes set in the attributes file in my cookbook with ones set in the environments of my chef server.

This is my attributes file:

```<code>default['app']                  = 'tomcat_app'
default['environment']          = 'env'
default['instance']             = 'tier'
default['application_name']     = "#{default['environment']}/#{default['app']}"
default['environment_instance'] = "#{default['environment']}/#{default['app']}/#{default['instance']}"
default['app_owner']            = 'app_user'
default['app_owner_group']      = 'app_group'
</code>```

My environment it is configured as follows:

```<code> {
    "app": {
        "tomcat_app": "NGS"
    },
    "environment": {
        "env": "/Test/Apps"
    },
    "instance": {
        "tier": "tst"
    },
    "app_owner": {
        "app_user": "ngsint"
    },
    "app_owner_group": {
        "app_group": "batchdev"
    },
    "override_attributes": {}
}
</code>```

However during chef-client run these values are not replaced. I have set this in the default attributes of the environments.

答:
Attributes should be in default_attributes Hash/Object, it should look like:

```<code>  "default_attributes": {
    "app": {
        "tomcat_app": "NGS"
    },
    "environment": {
        "env": "/Test/Apps"
    },
    "instance": {
        "tier": "tst"
    },
    "app_owner": {
        "app_user": "ngsint"
    },
    "app_owner_group": {
        "app_group": "batchdev"
    }
  }
</code>```

As explained in the documentation.

Body:
I am trying to override my default attributes set in the attributes file in my cookbook with ones set in the environments of my chef server.

This is my attributes file:

default['app']                  = 'tomcat_app'
default['environment']          = 'env'
default['instance']             = 'tier'
default['application_name']     = "#{default['environment']}/#{default['app']}"
default['environment_instance'] = "#{default['environment']}/#{default['app']}/#{default['instance']}"
default['app_owner']            = 'app_user'
default['app_owner_group']      = 'app_group'

My environment it is configured as follows:

 {
    "app": {
        "tomcat_app": "NGS"
    },
    "environment": {
        "env": "/Test/Apps"
    },
    "instance": {
        "tier": "tst"
    },
    "app_owner": {
        "app_user": "ngsint"
    },
    "app_owner_group": {
        "app_group": "batchdev"
    },
    "override_attributes": {}
}

However during chef-client run these values are not replaced. I have set this in the default attributes of the environments.

Body:
Attributes should be in default_attributes Hash/Object, it should look like:

  "default_attributes": {
    "app": {
        "tomcat_app": "NGS"
    },
    "environment": {
        "env": "/Test/Apps"
    },
    "instance": {
        "tier": "tst"
    },
    "app_owner": {
        "app_user": "ngsint"
    },
    "app_owner_group": {
        "app_group": "batchdev"
    }
  }

As explained in the documentation.


问:
Firefox - Unnecessary x-scrollbar
An unwanted x-scrollbar appears in Firefox.

Even if disable it by overflow-x: hidden; the width is wrong (strings stay hidden).

```<code>.wrapper {
  position: absolute;
}
.left {
  height: 150px;
  display: inline-block;
  position: relative;
  overflow: auto;
}
.left > div {
  white-space: nowrap;
  padding-left: 20px;
}
</code>```

Chrome:

Firefox:

Any suggestions why?

jsfiddle to play with code: https://jsfiddle.net/5yqkoujm/

答:
So, here is my guess : you need a fixed height and a dynamic width, adjusting to what's inside the left div.

An element which is display:block (which div is by default) by default is 100% width. display: inline or inline-block elements will fit to their content.
  https://stackoverflow.com/a/9896303/8932080

You should try this EDITED code :

Another edit : now hides the scrollbar if there is not enough items to show. Last but not least edit, you got what you've asked :)

.wrapper {
  position: absolute;
}

.left {
  height: 150px;
  display: inline-block;
  position: relative;
  overflow-y: auto;
}

.left>div {
  white-space: nowrap;
  display: block; /*Nailed it, here is the fix !*/
  padding-right: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">
    <div>Some not so long string</div>
    <div>Some not so long string</div>
  </div>
  <div class="wrapper">
    <div class="left">
      <div>Some not so long string</div>
      <div>Some not so long stringSome not so not stringSome not so not tringSome not sog stringSome not so long string</div>
      <div>Some not so long</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
    </div>
  </div></code>```

Hope it will help :)

Fix found thanks to this thread : parent div scaling to content inside it

Title: Firefox - Unnecessary x-scrollbar

Body:
An unwanted x-scrollbar appears in Firefox.

Even if disable it by overflow-x: hidden; the width is wrong (strings stay hidden).

.wrapper {
  position: absolute;
}
.left {
  height: 150px;
  display: inline-block;
  position: relative;
  overflow: auto;
}
.left > div {
  white-space: nowrap;
  padding-left: 20px;
}

Chrome:

Firefox:

Any suggestions why?

jsfiddle to play with code: https://jsfiddle.net/5yqkoujm/

Body:
So, here is my guess : you need a fixed height and a dynamic width, adjusting to what's inside the left div.

An element which is display:block (which div is by default) by default is 100% width. display: inline or inline-block elements will fit to their content.
  https://stackoverflow.com/a/9896303/8932080

You should try this EDITED code :

Another edit : now hides the scrollbar if there is not enough items to show. Last but not least edit, you got what you've asked :)

.wrapper {
  position: absolute;
}

.left {
  height: 150px;
  display: inline-block;
  position: relative;
  overflow-y: auto;
}

.left>div {
  white-space: nowrap;
  display: block; /*Nailed it, here is the fix !*/
  padding-right: 20px;
}

<div class="wrapper">
  <div class="left">
    <div>Some not so long string</div>
    <div>Some not so long string</div>
  </div>
  <div class="wrapper">
    <div class="left">
      <div>Some not so long string</div>
      <div>Some not so long stringSome not so not stringSome not so not tringSome not sog stringSome not so long string</div>
      <div>Some not so long</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
      <div>Some not so long string</div>
    </div>
  </div>

Hope it will help :)

Fix found thanks to this thread : parent div scaling to content inside it


问:
How to make request every 2 seconds with angular js and node js?
I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?

Example of some request:

```<code>var indicesTimer = setInterval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}
</code>```

答:
Check $interval service.

```<code>  var stop = $interval(function() {
                 // Your code
             }, 100);
</code>```

With your code

```<code>var indicesTimer = $interval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}
</code>```

Body:
I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?

Example of some request:

var indicesTimer = setInterval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}

Body:
Check $interval service.

  var stop = $interval(function() {
                 // Your code
             }, 100);

With your code

var indicesTimer = $interval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}


问:
Getting "the requested resource is in use" when using asio::async_write in single thread
Here is my code.

```<code>boost::asio::async_write(*serialPort, boost::asio::buffer(*something),handler);
boost::asio::async_write(*serialPort, boost::asio::buffer(*something2),handler);
</code>```

The above code will get an error "the requested resource is in use"  on the second line (Note that the async stream is a serial port). But when I changed the stream to a tcp socket, everthing works fine. Why?

Now I know I can’t use these composed asynchronous operation these way, but the first line code may be a heartbeat package, the second line may be a package which don’t sent regually. And these send operations buffers can’t gather together in the same time. Is there a way to synchronize these asynchronous operations in a single thread ( or multi-thread)?

答:
The commenters are right. In this case you can easily use a buffer sequence ("scatter/gather IO"):

```<code>std::vector<boost::asio::const_buffer> buffers {
    boost::asio::buffer(*something),
    boost::asio::buffer(*something2)
};

boost::asio::async_write(*serialPort, buffers, handler);
</code>```

See it Compiling On Coliru

```<code>#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>

void handler(boost::system::error_code ec, size_t) {
    std::cout << __PRETTY_FUNCTION__ << ": " << ec.message() << "\n";
}

int main() {
    boost::asio::io_service svc;

    auto serialPort = std::make_shared<boost::asio::serial_port>(svc);

    auto something = std::make_shared<std::string>("hello world\n");
    auto something2 = std::make_shared<std::string>("bye world\n");

    std::vector<boost::asio::const_buffer> buffers {
        boost::asio::buffer(*something),
        boost::asio::buffer(*something2)
    };

    boost::asio::async_write(*serialPort, buffers, handler);
}
</code>```

Body:
Here is my code.

boost::asio::async_write(*serialPort, boost::asio::buffer(*something),handler);
boost::asio::async_write(*serialPort, boost::asio::buffer(*something2),handler);

The above code will get an error "the requested resource is in use"  on the second line (Note that the async stream is a serial port). But when I changed the stream to a tcp socket, everthing works fine. Why?

Now I know I can’t use these composed asynchronous operation these way, but the first line code may be a heartbeat package, the second line may be a package which don’t sent regually. And these send operations buffers can’t gather together in the same time. Is there a way to synchronize these asynchronous operations in a single thread ( or multi-thread)?

Body:
The commenters are right. In this case you can easily use a buffer sequence ("scatter/gather IO"):

std::vector<boost::asio::const_buffer> buffers {
    boost::asio::buffer(*something),
    boost::asio::buffer(*something2)
};

boost::asio::async_write(*serialPort, buffers, handler);

See it Compiling On Coliru

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>

void handler(boost::system::error_code ec, size_t) {
    std::cout << __PRETTY_FUNCTION__ << ": " << ec.message() << "\n";
}

int main() {
    boost::asio::io_service svc;

    auto serialPort = std::make_shared<boost::asio::serial_port>(svc);

    auto something = std::make_shared<std::string>("hello world\n");
    auto something2 = std::make_shared<std::string>("bye world\n");

    std::vector<boost::asio::const_buffer> buffers {
        boost::asio::buffer(*something),
        boost::asio::buffer(*something2)
    };

    boost::asio::async_write(*serialPort, buffers, handler);
}


问:
Checkpoint data corruption in Spark Streaming
I am testing checkpointing and write ahead logs with this basic Spark streaming code below. I am checkpointing into a local directory. After starting and stopping the application a few times (using Ctrl-C) - it would refuse to start, for what looks like some data corruption in the checkpoint directoty. I am getting:

```<code>org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 80.0 failed 1 times, most recent failure: Lost task 0.0 in stage 80.0 (TID 17, localhost): com.esotericsoftware.kryo.KryoException: Encountered unregistered class ID: 13994
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:137)
    at com.esotericsoftware.kryo.Kryo.readClass(Kryo.java:670)
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:781)
    at org.apache.spark.serializer.KryoDeserializationStream.readObject(KryoSerializer.scala:229)
    at org.apache.spark.serializer.DeserializationStream$$anon$1.getNext(Serializer.scala:169)
    at org.apache.spark.util.NextIterator.hasNext(NextIterator.scala:73)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:439)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:192)
</code>```

Full code:

```<code>import org.apache.hadoop.conf.Configuration
import org.apache.spark._
import org.apache.spark.streaming._

object ProtoDemo {
  def createContext(dirName: String) = {
    val conf = new SparkConf().setAppName("mything")
    conf.set("spark.streaming.receiver.writeAheadLog.enable", "true")

    val ssc = new StreamingContext(conf, Seconds(1))
    ssc.checkpoint(dirName)
    val lines = ssc.socketTextStream("127.0.0.1", 9999)
    val words = lines.flatMap(_.split(" "))
    val pairs = words.map(word => (word, 1))
    val wordCounts = pairs.reduceByKey(_ + _)
    val runningCounts = wordCounts.updateStateByKey[Int] {
      (values: Seq[Int], oldValue: Option[Int]) =>
        val s = values.sum
        Some(oldValue.fold(s)(_ + s))
      }

  // Print the first ten elements of each RDD generated in this DStream to the console
    runningCounts.print()
    ssc
  }

  def main(args: Array[String]) = {
    val hadoopConf = new Configuration()
    val dirName = "/tmp/chkp"
    val ssc = StreamingContext.getOrCreate(dirName, () => createContext(dirName), hadoopConf)
    ssc.start()
    ssc.awaitTermination()
  }

}
</code>```

答:
The issue looks rather Kryo Serializer issue than checkpoint corruption.
At code example (including GitHub project), Kryo Serialization is not configured.
Since it is not configured KryoException exception could not happen.

When using "write ahead logs", and restoring from a directory, all Spark config is getting from there.
At your example, createContext method does not call when starting from the checkpoint.

I assume the issue is another application were tested before with the same checkpoint directory, where Kryo Serializer where configured.
And current application fails to be restored from that checkpoint.

Body:
I am testing checkpointing and write ahead logs with this basic Spark streaming code below. I am checkpointing into a local directory. After starting and stopping the application a few times (using Ctrl-C) - it would refuse to start, for what looks like some data corruption in the checkpoint directoty. I am getting:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 80.0 failed 1 times, most recent failure: Lost task 0.0 in stage 80.0 (TID 17, localhost): com.esotericsoftware.kryo.KryoException: Encountered unregistered class ID: 13994
    at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:137)
    at com.esotericsoftware.kryo.Kryo.readClass(Kryo.java:670)
    at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:781)
    at org.apache.spark.serializer.KryoDeserializationStream.readObject(KryoSerializer.scala:229)
    at org.apache.spark.serializer.DeserializationStream$$anon$1.getNext(Serializer.scala:169)
    at org.apache.spark.util.NextIterator.hasNext(NextIterator.scala:73)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:439)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:192)

Full code:

import org.apache.hadoop.conf.Configuration
import org.apache.spark._
import org.apache.spark.streaming._

object ProtoDemo {
  def createContext(dirName: String) = {
    val conf = new SparkConf().setAppName("mything")
    conf.set("spark.streaming.receiver.writeAheadLog.enable", "true")

    val ssc = new StreamingContext(conf, Seconds(1))
    ssc.checkpoint(dirName)
    val lines = ssc.socketTextStream("127.0.0.1", 9999)
    val words = lines.flatMap(_.split(" "))
    val pairs = words.map(word => (word, 1))
    val wordCounts = pairs.reduceByKey(_ + _)
    val runningCounts = wordCounts.updateStateByKey[Int] {
      (values: Seq[Int], oldValue: Option[Int]) =>
        val s = values.sum
        Some(oldValue.fold(s)(_ + s))
      }

  // Print the first ten elements of each RDD generated in this DStream to the console
    runningCounts.print()
    ssc
  }

  def main(args: Array[String]) = {
    val hadoopConf = new Configuration()
    val dirName = "/tmp/chkp"
    val ssc = StreamingContext.getOrCreate(dirName, () => createContext(dirName), hadoopConf)
    ssc.start()
    ssc.awaitTermination()
  }

}