问:
How to combine lists or alternatively create list of lists
I have a memory game where you have to find pairs of tiles with identical images. I want to modify the game so that you have to find pairs of a tile with image and a tile with corresponding text. For example find a tile with an image of a cat and a tile with the text "cat".

To understand the problem, here's the code that I believe is most relevant, showing how I currently use a list of images to create pairs of tiles:

```<code>class Tile(object):
    def __init__(self, canvas, x, y, image, cardback):
        self.image = image
        more stuff...

class MemGame(tk.Frame):
    def __init__(self, master):
        super(MemGame, self).__init__(master)

        self.images = [
            photoDog,
            more images...
        ]

        selected = []
        for i in range(10):
            randomInd = randint(0, len(self.images) - 1)
            animalImg = self.images[randomInd]
            selected.append(animalImg)
            selected.append(animalImg)
            del self.images[randomInd]
        shuffle(selected)
        self.flippedTiles = []
        NUM_COLS = 5
        NUM_ROWS = 4

        for x in range(0, NUM_COLS):
            for y in range(0, NUM_ROWS):
                self.tiles.append(Tile(self.canvas, x * 108 + 10, y * 108 + 40, selected.pop(), photoCardback))
</code>```

I'm not sure if I should create another list of texts, or change the list of images to a list of lists with an image and a text.

In case it's needed, here's the full code:

```<code>import tkinter as tk
from random import randint
from random import shuffle
import pygame
pygame.init()

class Controller(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        if True:
            self.frames = {}
            for F in (PageMG,):
                page_name = F.__name__
                frame = F(parent=container, controller=self)
                self.frames[page_name] = frame

                # put all of the pages in the same location;
                # the one on the top of the stacking order
                # will be the one that is visible.
                frame.grid(row=0, column=0, sticky="nsew")

            self.show_frame("PageMG")
        self.geometry("800x480")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class PageMG(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        x = MemGame(self)
        x.pack()

class Tile(object):
    def __init__(self, canvas, x, y, image, cardback):
        self.cardback = cardback
        self.canvas = canvas
        self.y = y
        self.x = x
        self.image = image

    def drawFaceDown(self):
        self.canvas.create_rectangle(self.x, self.y, self.x + 100, self.y + 100, fill = "white")
        self.canvas.create_image(self.x + 50, self.y + 50, image=self.cardback)
        self.isFaceUp = False

    def drawFaceUp(self):
        self.canvas.create_rectangle(self.x, self.y, self.x + 100, self.y + 100, fill = "white")
        self.canvas.create_image(self.x + 50, self.y + 50, image=self.image)
        self.isFaceUp = True

    def isUnderMouse(self, event):
        if(event.x > self.x and event.x < self.x + 100):
            if(event.y > self.y and event.y < self.y + 100):
                return True

class MemGame(tk.Frame):
    def __init__(self, master):
        super(MemGame, self).__init__(master)

        photoRestart = tk.PhotoImage(file="restart.png")
        imgRestart = tk.Label(self, anchor="s", image=photoRestart)
        imgRestart.image = photoRestart
        buttonRestart = tk.Button(self, activebackground="white",
                                  image=photoRestart, highlightthickness=0, borderwidth=0,
                                  command=lambda: self.restart())
        buttonRestart.place(x=560, y=200)

        photoDog = tk.PhotoImage(file="Dyr/dog.png")
        photoElefant = tk.PhotoImage(file="Dyr/elefant.png")
        photoFlamingo = tk.PhotoImage(file="Dyr/flamingo.png")
        photoFlodhest = tk.PhotoImage(file="Dyr/flodhest.png")
        photoKamel = tk.PhotoImage(file="Dyr/kamel.png")
        photoKatt = tk.PhotoImage(file="Dyr/katt.png")
        photoKroko = tk.PhotoImage(file="Dyr/krokodille.png")
        photoNeshorn = tk.PhotoImage(file="Dyr/neshorn.png")
        photoSkilpadde = tk.PhotoImage(file="Dyr/skilpadde.png")
        photoStruts = tk.PhotoImage(file="Dyr/struts.png")
        photoZebra = tk.PhotoImage(file="Dyr/zebra.png")
        photoLove = tk.PhotoImage(file="Dyr/love.png")

        photoCardback = tk.PhotoImage(file="cardback.png")
        self.cardback = photoCardback

        self.riktig_sound = pygame.mixer.Sound("riktig.wav")
        self.click_sound = pygame.mixer.Sound("camerashutter.wav")

        self.configure(width=650, height=480, bg="white")
        self.canvas = tk.Canvas(self, bg="white", width=550, height=480, highlightthickness=0, borderwidth=0)
        self.canvas.place(x=0, y=-30)
        self.tiles = []
        self.images = [
            photoDog,
            photoElefant,
            photoFlamingo,
            photoFlodhest,
            photoKamel,
            photoKatt,
            photoKroko,
            photoNeshorn,
            photoSkilpadde,
            photoStruts,
            photoZebra,
            photoLove
        ]

        selected = []
        for i in range(10):
            randomInd = randint(0, len(self.images) - 1)
            animalImg = self.images[randomInd]
            selected.append(animalImg)
            selected.append(animalImg)
            del self.images[randomInd]
        shuffle(selected)
        self.flippedTiles = []
        NUM_COLS = 5
        NUM_ROWS = 4

        for x in range(0, NUM_COLS):
            for y in range(0, NUM_ROWS):
                self.tiles.append(Tile(self.canvas, x * 108 + 10, y * 108 + 40, selected.pop(), photoCardback))

        for i in range(len(self.tiles)):
            self.tiles[i].drawFaceDown()
        self.flippedThisTurn = 0
        self.canvas.bind("<Button-1>", self.mouseClicked)

    def mouseClicked(self, event):
        for tile in self.tiles:
            if tile.isUnderMouse(event) and (self.flippedThisTurn < 2):
                if (not(tile.isFaceUp)):
                    self.clickSound()
                    tile.drawFaceUp()
                    self.flippedTiles.append(tile)
                    self.flippedThisTurn += 1

                if (self.flippedThisTurn == 2):
                    if (self.flippedTiles[-1].image == self.flippedTiles[-2].image): #check last two elements
                        self.riktig()
                    self.after(1000, self.checkTiles)

    def checkTiles(self):
        self.flippedThisTurn = 0

        if not(self.flippedTiles[-1].image == self.flippedTiles[-2].image):
            self.flippedTiles[-1].drawFaceDown()
            self.flippedTiles[-2].drawFaceDown()
            del self.flippedTiles[-2:]

    def restart(self):
        for i in range(len(self.tiles)):
            self.tiles[i].drawFaceDown()

    def riktig(self):
        pygame.mixer.Sound.play(self.riktig_sound)
        pygame.mixer.music.stop()

    def clickSound(self):
        pygame.mixer.Sound.play(self.click_sound)
        pygame.mixer.music.stop()

if __name__ == '__main__':
    c = Controller()
    c.mainloop()
</code>```

答:
I think the easiest approach, which causes the least changes to your current code is to:

Make your list of images (done)

Make a list of text-based corresponding tiles (to do)

Make a combined list of the two above and draw each image only once instead of twice as you are doing now (easy)

Make a dictionary that you can use to look up matches (see below)

Modify your "check tiles" function to see if they match using the dictionary (one-line change)

The dictionary created can be used bi-directionally so it will find match regardless of how comparison is done.

```<code>In [6]: image_tiles = ['dog_img', 'cat_img', 'hen_img']

In [7]: tag_tiles = ['dog', 'cat', 'hen']

In [8]: all_tiles = image_tiles + tag_tiles  # use this to draw tiles

In [9]: matches = { k:v for (k, v) in zip(image_tiles, tag_tiles) }

In [10]: # add opposite lookup

In [11]: matches.update([(k, v) for (k, v) in zip(tag_tiles, image_tiles)])

In [12]: matches
Out[12]:
{'dog_img': 'dog',
 'cat_img': 'cat',
 'hen_img': 'hen',
 'dog': 'dog_img',
 'cat': 'cat_img',
 'hen': 'hen_img'}
</code>```

Body:
I have a memory game where you have to find pairs of tiles with identical images. I want to modify the game so that you have to find pairs of a tile with image and a tile with corresponding text. For example find a tile with an image of a cat and a tile with the text "cat".

To understand the problem, here's the code that I believe is most relevant, showing how I currently use a list of images to create pairs of tiles:

class Tile(object):
    def __init__(self, canvas, x, y, image, cardback):
        self.image = image
        more stuff...

class MemGame(tk.Frame):
    def __init__(self, master):
        super(MemGame, self).__init__(master)

        self.images = [
            photoDog,
            more images...
        ]

        selected = []
        for i in range(10):
            randomInd = randint(0, len(self.images) - 1)
            animalImg = self.images[randomInd]
            selected.append(animalImg)
            selected.append(animalImg)
            del self.images[randomInd]
        shuffle(selected)
        self.flippedTiles = []
        NUM_COLS = 5
        NUM_ROWS = 4

        for x in range(0, NUM_COLS):
            for y in range(0, NUM_ROWS):
                self.tiles.append(Tile(self.canvas, x * 108 + 10, y * 108 + 40, selected.pop(), photoCardback))

I'm not sure if I should create another list of texts, or change the list of images to a list of lists with an image and a text.

In case it's needed, here's the full code:

import tkinter as tk
from random import randint
from random import shuffle
import pygame
pygame.init()

class Controller(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        if True:
            self.frames = {}
            for F in (PageMG,):
                page_name = F.__name__
                frame = F(parent=container, controller=self)
                self.frames[page_name] = frame

                # put all of the pages in the same location;
                # the one on the top of the stacking order
                # will be the one that is visible.
                frame.grid(row=0, column=0, sticky="nsew")

            self.show_frame("PageMG")
        self.geometry("800x480")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class PageMG(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        x = MemGame(self)
        x.pack()

class Tile(object):
    def __init__(self, canvas, x, y, image, cardback):
        self.cardback = cardback
        self.canvas = canvas
        self.y = y
        self.x = x
        self.image = image

    def drawFaceDown(self):
        self.canvas.create_rectangle(self.x, self.y, self.x + 100, self.y + 100, fill = "white")
        self.canvas.create_image(self.x + 50, self.y + 50, image=self.cardback)
        self.isFaceUp = False

    def drawFaceUp(self):
        self.canvas.create_rectangle(self.x, self.y, self.x + 100, self.y + 100, fill = "white")
        self.canvas.create_image(self.x + 50, self.y + 50, image=self.image)
        self.isFaceUp = True

    def isUnderMouse(self, event):
        if(event.x > self.x and event.x < self.x + 100):
            if(event.y > self.y and event.y < self.y + 100):
                return True

class MemGame(tk.Frame):
    def __init__(self, master):
        super(MemGame, self).__init__(master)

        photoRestart = tk.PhotoImage(file="restart.png")
        imgRestart = tk.Label(self, anchor="s", image=photoRestart)
        imgRestart.image = photoRestart
        buttonRestart = tk.Button(self, activebackground="white",
                                  image=photoRestart, highlightthickness=0, borderwidth=0,
                                  command=lambda: self.restart())
        buttonRestart.place(x=560, y=200)

        photoDog = tk.PhotoImage(file="Dyr/dog.png")
        photoElefant = tk.PhotoImage(file="Dyr/elefant.png")
        photoFlamingo = tk.PhotoImage(file="Dyr/flamingo.png")
        photoFlodhest = tk.PhotoImage(file="Dyr/flodhest.png")
        photoKamel = tk.PhotoImage(file="Dyr/kamel.png")
        photoKatt = tk.PhotoImage(file="Dyr/katt.png")
        photoKroko = tk.PhotoImage(file="Dyr/krokodille.png")
        photoNeshorn = tk.PhotoImage(file="Dyr/neshorn.png")
        photoSkilpadde = tk.PhotoImage(file="Dyr/skilpadde.png")
        photoStruts = tk.PhotoImage(file="Dyr/struts.png")
        photoZebra = tk.PhotoImage(file="Dyr/zebra.png")
        photoLove = tk.PhotoImage(file="Dyr/love.png")

        photoCardback = tk.PhotoImage(file="cardback.png")
        self.cardback = photoCardback

        self.riktig_sound = pygame.mixer.Sound("riktig.wav")
        self.click_sound = pygame.mixer.Sound("camerashutter.wav")

        self.configure(width=650, height=480, bg="white")
        self.canvas = tk.Canvas(self, bg="white", width=550, height=480, highlightthickness=0, borderwidth=0)
        self.canvas.place(x=0, y=-30)
        self.tiles = []
        self.images = [
            photoDog,
            photoElefant,
            photoFlamingo,
            photoFlodhest,
            photoKamel,
            photoKatt,
            photoKroko,
            photoNeshorn,
            photoSkilpadde,
            photoStruts,
            photoZebra,
            photoLove
        ]

        selected = []
        for i in range(10):
            randomInd = randint(0, len(self.images) - 1)
            animalImg = self.images[randomInd]
            selected.append(animalImg)
            selected.append(animalImg)
            del self.images[randomInd]
        shuffle(selected)
        self.flippedTiles = []
        NUM_COLS = 5
        NUM_ROWS = 4

        for x in range(0, NUM_COLS):
            for y in range(0, NUM_ROWS):
                self.tiles.append(Tile(self.canvas, x * 108 + 10, y * 108 + 40, selected.pop(), photoCardback))

        for i in range(len(self.tiles)):
            self.tiles[i].drawFaceDown()
        self.flippedThisTurn = 0
        self.canvas.bind("<Button-1>", self.mouseClicked)

    def mouseClicked(self, event):
        for tile in self.tiles:
            if tile.isUnderMouse(event) and (self.flippedThisTurn < 2):
                if (not(tile.isFaceUp)):
                    self.clickSound()
                    tile.drawFaceUp()
                    self.flippedTiles.append(tile)
                    self.flippedThisTurn += 1

                if (self.flippedThisTurn == 2):
                    if (self.flippedTiles[-1].image == self.flippedTiles[-2].image): #check last two elements
                        self.riktig()
                    self.after(1000, self.checkTiles)

    def checkTiles(self):
        self.flippedThisTurn = 0

        if not(self.flippedTiles[-1].image == self.flippedTiles[-2].image):
            self.flippedTiles[-1].drawFaceDown()
            self.flippedTiles[-2].drawFaceDown()
            del self.flippedTiles[-2:]

    def restart(self):
        for i in range(len(self.tiles)):
            self.tiles[i].drawFaceDown()

    def riktig(self):
        pygame.mixer.Sound.play(self.riktig_sound)
        pygame.mixer.music.stop()

    def clickSound(self):
        pygame.mixer.Sound.play(self.click_sound)
        pygame.mixer.music.stop()

if __name__ == '__main__':
    c = Controller()
    c.mainloop()

Body:
I think the easiest approach, which causes the least changes to your current code is to:

Make your list of images (done)

Make a list of text-based corresponding tiles (to do)

Make a combined list of the two above and draw each image only once instead of twice as you are doing now (easy)

Make a dictionary that you can use to look up matches (see below)

Modify your "check tiles" function to see if they match using the dictionary (one-line change)

The dictionary created can be used bi-directionally so it will find match regardless of how comparison is done.

In [6]: image_tiles = ['dog_img', 'cat_img', 'hen_img']

In [7]: tag_tiles = ['dog', 'cat', 'hen']

In [8]: all_tiles = image_tiles + tag_tiles  # use this to draw tiles

In [9]: matches = { k:v for (k, v) in zip(image_tiles, tag_tiles) }

In [10]: # add opposite lookup

In [11]: matches.update([(k, v) for (k, v) in zip(tag_tiles, image_tiles)])

In [12]: matches
Out[12]:
{'dog_img': 'dog',
 'cat_img': 'cat',
 'hen_img': 'hen',
 'dog': 'dog_img',
 'cat': 'cat_img',
 'hen': 'hen_img'}


来源: stackexchange

问:
angular service ready flag
i'm try to rewrite my angularJS app to angular2
so i got service which download i18n labels from different endpoints
and i need to know when all of data is ready.

in my angularJS components i can do like so

vm.loading = true;
backend.ready.then(() => {
   loading = false;
   backend.getAlias('anyLabel')
})
```

<p>so when loading === false i'm hide loader and can get aliases
But i can't figure out how i can do it with angular2 services and observables. Now i have something like this:</p>

<pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, zip, of, Subject } from 'rxjs';

export interface Alias {
    code: string;
    value: string;
}

@Injectable({
    providedIn: 'root'
})
export class BackendService {
    private aliases: Alias[];
    private aliasDeclaration: Alias[];
    public ready: Observable<boolean>;

    constructor(private http: HttpClient) {
        this.aliases = [];
        this.aliasDeclaration = [];
        this.ready = new Observable<boolean>();
    }

    private getAliases(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/json/get-aliases?lang=ru');
    }

    private getDeclarations(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/themes/backend/aliases-declaration.json');
    }

    public init(): void {
        zip(this.getAliases(), this.getDeclarations()).subscribe(([aliases, declarations]) => {
            this.aliases = aliases;
            this.aliasDeclaration = declarations;
            // i need to set ready = true here, but can't figure out how :)
        });
    }

    public getAlias(code): Alias {
        return this.aliases.find(alias => alias.code === code);
    }

    public getAliasDeclaration(code): Alias {
        return this.aliasDeclaration.find(alias => alias.code === code);
    }
}

</code>```

答:
There are various options but I would return an Observable from the init method although I prefer to add the suffix Async to my methods that return an observable or promise.

```<code>import { shareReplay, map } from 'rxjs/operators';
</code>```

```<code>public initAsync(): Observable<BackendService> {
    const merged = zip(this.getAliases(), this.getDeclarations()).pipe(shareReplay());

    merged.subscribe(([aliases, declarations]) => {
        this.aliases = aliases;
        this.aliasDeclaration = declarations;
    // i need to set ready = true here, but can't figure out how :)
    });
    return merged.pipe(map(() => this));
}
</code>```

shareReplay ensures that the same result is used. I also am returning the service itself from the Observable although that is not really necessary. It does make it easy for the subscriber to use the service that is now ready but return whatever you want.

Calling code

```<code>ngOnInit() {
  this.service.initAsync().subscribe(_ => /*do something*/);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: angular service ready flag

Body:
i'm try to rewrite my angularJS app to angular2
so i got service which download i18n labels from different endpoints
and i need to know when all of data is ready.

in my angularJS components i can do like so

vm.loading = true;
backend.ready.then(() => {
   loading = false;
   backend.getAlias('anyLabel')
})

so when loading === false i'm hide loader and can get aliases
But i can't figure out how i can do it with angular2 services and observables. Now i have something like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, zip, of, Subject } from 'rxjs';

export interface Alias {
    code: string;
    value: string;
}

@Injectable({
    providedIn: 'root'
})
export class BackendService {
    private aliases: Alias[];
    private aliasDeclaration: Alias[];
    public ready: Observable<boolean>;

    constructor(private http: HttpClient) {
        this.aliases = [];
        this.aliasDeclaration = [];
        this.ready = new Observable<boolean>();
    }

    private getAliases(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/json/get-aliases?lang=ru');
    }

    private getDeclarations(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/themes/backend/aliases-declaration.json');
    }

    public init(): void {
        zip(this.getAliases(), this.getDeclarations()).subscribe(([aliases, declarations]) => {
            this.aliases = aliases;
            this.aliasDeclaration = declarations;
            // i need to set ready = true here, but can't figure out how :)
        });
    }

    public getAlias(code): Alias {
        return this.aliases.find(alias => alias.code === code);
    }

    public getAliasDeclaration(code): Alias {
        return this.aliasDeclaration.find(alias => alias.code === code);
    }
}

Body:
There are various options but I would return an Observable from the init method although I prefer to add the suffix Async to my methods that return an observable or promise.

import { shareReplay, map } from 'rxjs/operators';

public initAsync(): Observable<BackendService> {
    const merged = zip(this.getAliases(), this.getDeclarations()).pipe(shareReplay());

    merged.subscribe(([aliases, declarations]) => {
        this.aliases = aliases;
        this.aliasDeclaration = declarations;
    // i need to set ready = true here, but can't figure out how :)
    });
    return merged.pipe(map(() => this));
}

shareReplay ensures that the same result is used. I also am returning the service itself from the Observable although that is not really necessary. It does make it easy for the subscriber to use the service that is now ready but return whatever you want.

Calling code

ngOnInit() {
  this.service.initAsync().subscribe(_ => /*do something*/);
}


问:
Sending objects through Java NIO non-blocking sockets
I am getting an exception when trying to use:

```<code>oos = new ObjectOutputStream(socketChannel.socket().getOutputStream());
oos.writeObject(o);
</code>```

And this raises the exception:

```<code>java.nio.channels.IllegalBlockingModeException
</code>```

Is it impossible to pass objects in non-blocking sockets?
If it is, how should I proceed on passing message objects through the socket channels?

I've looked other places for this answer but couldn't find one...

答:
You'll probably want to write your own ObjectOutputStream implementation that constructs a ByteBuffer and write()s it to the channel.

With non-blocking sockets, you cannot directly use the channel's socket; you need to use the channel's read() and write() methods.

When you write your own ObjectOutputStream, you'll mainly need to override the write() methods to buffer output and use the flush() method to write the buffer to the channel. Then, override the writeObject() method to look like this:

```<code>public void writeObject(Object o) throws IOException {
    super.writeObject(o);
    flush();
}
</code>```

to make sure the data gets written after each object write.

ContentLicense: CC BY-SA 3.0

Body:
I am getting an exception when trying to use:

oos = new ObjectOutputStream(socketChannel.socket().getOutputStream());
oos.writeObject(o);

And this raises the exception:

java.nio.channels.IllegalBlockingModeException

Is it impossible to pass objects in non-blocking sockets?
If it is, how should I proceed on passing message objects through the socket channels?

I've looked other places for this answer but couldn't find one...

Body:
You'll probably want to write your own ObjectOutputStream implementation that constructs a ByteBuffer and write()s it to the channel.

With non-blocking sockets, you cannot directly use the channel's socket; you need to use the channel's read() and write() methods.

When you write your own ObjectOutputStream, you'll mainly need to override the write() methods to buffer output and use the flush() method to write the buffer to the channel. Then, override the writeObject() method to look like this:

public void writeObject(Object o) throws IOException {
    super.writeObject(o);
    flush();
}

to make sure the data gets written after each object write.


问:
Getopts default case bash script
I want to use getopts but the default case doesn't work.

The code that I tried is:

while getopts "sdp" arg; do
case "$arg" in
s)
    echo "1"
;;
p)
    echo "2"
;;
d)
   echo "3"
;;
*)
   echo "default"
;;
esac
```

when I run the process: ./myTask

I didn't receive any output

答:
It's working as intended.

The default case is not to handle the case where you don't have arguments, but the case where you supply invalid arguments:

```<code>$ ./myTest -X
./myTest: illegal option -- X
default
</code>```

Normally you would write a usage message in this case.

Title: Getopts default case bash script

Body:
I want to use getopts but the default case doesn't work.

The code that I tried is:

while getopts "sdp" arg; do
case "$arg" in
s)
    echo "1"
;;
p)
    echo "2"
;;
d)
   echo "3"
;;
*)
   echo "default"
;;
esac

when I run the process: ./myTask

I didn't receive any output

Body:
It's working as intended.

The default case is not to handle the case where you don't have arguments, but the case where you supply invalid arguments:

$ ./myTest -X
./myTest: illegal option -- X
default

Normally you would write a usage message in this case.


问:
actualSolve raise PulpSolverError("CPLEX_PY: Not Available")
I am trying to run an optimization program using pulp and cplex I have installed cplex studio. I have change the path name as instructed

```<code>Name: Path
C:\Program Files\IBM\ILOG\CPLEX_Studio_Community129\cplex\python\3.7\x64_win64\cplex\_internal
</code>```

but I am still receiving the error CPLEX_PY: Not Available.
I was wondering if anyone else was able to solve this problem or what I'm missing.

答:
At first, I thought you were trying to use the CPLEX_CMD solver, but I see that you want to use CPLEX_PY instead. The former relies on the CPLEX interactive (cplex.exe) being in your PATH environment variable. The later requires that you either install the CPLEX Python API or include it in your PYTHONPATH environment variable. Please see the documentation here for setting up the CPLEX Python API.

Based on what you have in your question, you could run setup.py like so:

```<code>cd "C:\Program Files\IBM\ILOG\CPLEX_Studio_Community129\cplex\python\3.7\x64_win64"
python setup.py install
</code>```

Or, you could add the following to PYTHONPATH:

```<code>C:\Program Files\IBM\ILOG\CPLEX_Studio_Community129\cplex\python\3.7\x64_win64
</code>```

See how to do this here.

In any case, you need to make sure that you can do the following from the python prompt:

```<code>>>> import cplex
</code>```

Also, make sure you are using a 64-bit python.

Body:
I am trying to run an optimization program using pulp and cplex I have installed cplex studio. I have change the path name as instructed

Name: Path
C:\Program Files\IBM\ILOG\CPLEX_Studio_Community129\cplex\python\3.7\x64_win64\cplex\_internal

but I am still receiving the error CPLEX_PY: Not Available.
I was wondering if anyone else was able to solve this problem or what I'm missing.

Body:
At first, I thought you were trying to use the CPLEX_CMD solver, but I see that you want to use CPLEX_PY instead. The former relies on the CPLEX interactive (cplex.exe) being in your PATH environment variable. The later requires that you either install the CPLEX Python API or include it in your PYTHONPATH environment variable. Please see the documentation here for setting up the CPLEX Python API.

Based on what you have in your question, you could run setup.py like so:

cd "C:\Program Files\IBM\ILOG\CPLEX_Studio_Community129\cplex\python\3.7\x64_win64"
python setup.py install

Or, you could add the following to PYTHONPATH:

C:\Program Files\IBM\ILOG\CPLEX_Studio_Community129\cplex\python\3.7\x64_win64

See how to do this here.

In any case, you need to make sure that you can do the following from the python prompt:

>>> import cplex

Also, make sure you are using a 64-bit python.


问:
Is it safe to catch an Exception object
I use a Java lib that relies on exceptions. Simplified code below:

    try {
      val eventTime = eventTimeString.as[Date]
    } catch {
      case e: Exception =>
        logger.error(s"Can't parse eventTime from $eventTimeString", e)
        // take action for the bad Date string.
    }
```

In Java I would catch only the exception from parsing a string into a Date, letting the rest go uncaught since they could be fatal. Here my understanding is that catching Exception means to catch ANY non-fatal/non-serious exceptions. Since it is not the same a catching Throwable it is safe—but is it truly? The rationale for using this is that unknown exceptions might be thrown from deeper in the stack and if they are not fatal, why not catch all of them. This has always been a problem in Java where it is easy to find possible exceptions from the direct call you are making but not from deeper. Is this the Scala solution that basically means, 'catch all recoverable exceptions"?

My question is; is the above code considered good Scala style, is it "safe", meaning better than catching only the string to Date cast exception.

答:
Addressing the style aspect of the question, Try, as suggested by @LuisMiguelMejiaSuarez, provides a more idiomatic Scala style like so

```<code>Try(eventTimeString.as[Date]) match {
  case Success(eventTimeDate) => // work with eventTimeDate
  case Failure(e: IllegalArgumentException) => // work with e
  case Failure(e: NullPointerException) => // work with e
  ...
  case Failure(e) => // work with e
}
</code>```

Syntactically it appears not much different, however conceptually it is quite a shift because Success and Failure represent regular values as opposed to some exceptional control-structure. Success is a value like 7 is value, whilst try-catch is more like while or if-else control facility.

Wrapping any library call that might throw in Try, provided by, say, Java libraries, we could make use of for-yield sugar to chain calls like so

```<code>for {
  a <- Try(foo)
  b <- Try(bar)
  c <- Try(qux)
} yield {
  // work with a, b and c
}
</code>```

where

```<code>def foo: Int = {
  throw new TimeoutException("foo")
  42
}

def bar: String = {
  throw new IllegalArgumentException("bar")
  "hello"
}

def qux: Boolean = {
  throw new NullPointerException("qux")
  true
}
</code>```

We can read this chain sequentially without having to interrupt our flow of thought and try to understand how some exceptional control structure fits into the algorithm.

Regarding safety aspect of the question, arguably, we should not catch fatal exception such as LinkageError, and indeed Try does not match the following exceptions

```<code>VirtualMachineError
ThreadDeath
InterruptedException
LinkageError
ControlThrowable
</code>```

as shown by the way it is constructed

```<code>object Try {
  def apply[T](r: => T): Try[T] =
    try Success(r) catch {
      case NonFatal(e) => Failure(e)
    }
}
</code>```

where NonFatal is

```<code>object NonFatal {
   def apply(t: Throwable): Boolean = t match {
     case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
     case _ => true
   }

  def unapply(t: Throwable): Option[Throwable] = if (apply(t)) Some(t) else None
}
</code>```

Title: Is it safe to catch an Exception object

Body:
I use a Java lib that relies on exceptions. Simplified code below:

    try {
      val eventTime = eventTimeString.as[Date]
    } catch {
      case e: Exception =>
        logger.error(s"Can't parse eventTime from $eventTimeString", e)
        // take action for the bad Date string.
    }

In Java I would catch only the exception from parsing a string into a Date, letting the rest go uncaught since they could be fatal. Here my understanding is that catching Exception means to catch ANY non-fatal/non-serious exceptions. Since it is not the same a catching Throwable it is safe—but is it truly? The rationale for using this is that unknown exceptions might be thrown from deeper in the stack and if they are not fatal, why not catch all of them. This has always been a problem in Java where it is easy to find possible exceptions from the direct call you are making but not from deeper. Is this the Scala solution that basically means, 'catch all recoverable exceptions"?

My question is; is the above code considered good Scala style, is it "safe", meaning better than catching only the string to Date cast exception.

Body:
Addressing the style aspect of the question, Try, as suggested by @LuisMiguelMejiaSuarez, provides a more idiomatic Scala style like so

Try(eventTimeString.as[Date]) match {
  case Success(eventTimeDate) => // work with eventTimeDate
  case Failure(e: IllegalArgumentException) => // work with e
  case Failure(e: NullPointerException) => // work with e
  ...
  case Failure(e) => // work with e
}

Syntactically it appears not much different, however conceptually it is quite a shift because Success and Failure represent regular values as opposed to some exceptional control-structure. Success is a value like 7 is value, whilst try-catch is more like while or if-else control facility.

Wrapping any library call that might throw in Try, provided by, say, Java libraries, we could make use of for-yield sugar to chain calls like so

for {
  a <- Try(foo)
  b <- Try(bar)
  c <- Try(qux)
} yield {
  // work with a, b and c
}

where

def foo: Int = {
  throw new TimeoutException("foo")
  42
}

def bar: String = {
  throw new IllegalArgumentException("bar")
  "hello"
}

def qux: Boolean = {
  throw new NullPointerException("qux")
  true
}

We can read this chain sequentially without having to interrupt our flow of thought and try to understand how some exceptional control structure fits into the algorithm.

Regarding safety aspect of the question, arguably, we should not catch fatal exception such as LinkageError, and indeed Try does not match the following exceptions

VirtualMachineError
ThreadDeath
InterruptedException
LinkageError
ControlThrowable

as shown by the way it is constructed

object Try {
  def apply[T](r: => T): Try[T] =
    try Success(r) catch {
      case NonFatal(e) => Failure(e)
    }
}

where NonFatal is

object NonFatal {
   def apply(t: Throwable): Boolean = t match {
     case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
     case _ => true
   }

  def unapply(t: Throwable): Option[Throwable] = if (apply(t)) Some(t) else None
}


问:
Fail to start H2o cluster in docker containers because it can not bind external or host ip
Now we try to use H2o to construct training cluster. It is easy to use by running java -jar ./h2o.jar and we can setup the cluster with simple flatfile.txt which contain multiple ip and ports.

But we found that it is impossible to setup the h2o cluster within docker containers. Although we can start multiple containers to run java -jar ./h2o.jar and add the prepared flatfile.txt, the h2o process will try to bind local(container's eth0) ip which is different from the one in flatfile.txt. We can java -jar ./h2o.jar -ip $ip to set the one which is in flatfile.txt but h2o instance is not able to run without this "external" ip.

答: See my response to a similar issue here. I describe how it is possible to start an H2O cluster using a flatfile and docker swarm. Basically, you have to run a script in each service before starting H2O, to identify the correct IP addresses for the cluster. This is because docker assigns two IPs to each service. The flatfile needs to use the $HOSTNAME IP for each cluster member, which is difficult to determine in advance.</p>


问:
Python comparing two lists for values
Let's say that i have:

```<code>usa = ["kebab","pizza", "hamburger"]
uk = ["kebab", "hamburger"]
</code>```

How do i check if uk has all the meals that usa has?

I have tried this:

```<code>for i in usa:
if i not in str(uk):
    print("UK doesn't serve %s" % i)
</code>```

This works but only returns on missing item on uk's list. I need to know exactly what is missing. and this meal list might contain around 1000 or more records

答:
You can use the following comprehension way using all

```<code>usa = ["kebab","pizza", "hamburger"]
uk = ["kebab", "hamburger"]

print (all(i in usa for i in uk))
# True
</code>```

Title: Python comparing two lists for values

Body:
Let's say that i have:

usa = ["kebab","pizza", "hamburger"]
uk = ["kebab", "hamburger"]

How do i check if uk has all the meals that usa has?

I have tried this:

for i in usa:
if i not in str(uk):
    print("UK doesn't serve %s" % i)

This works but only returns on missing item on uk's list. I need to know exactly what is missing. and this meal list might contain around 1000 or more records

Body:
You can use the following comprehension way using all

usa = ["kebab","pizza", "hamburger"]
uk = ["kebab", "hamburger"]

print (all(i in usa for i in uk))
# True


问:
Property 'controls' does not exist on type 'AbstractControl' - angular4
there are lots of blogs already posted for this error but none is specified for angular4.

I am adding and removing dynamic controls on the form

add controls to the form during intialization

    ngOnInit() {

        this.lienHolder = this._fb.group({
          emailAddress: ['', [Validators.required, Validators.email]],
          policyDetails: this._fb.array([
            this.initPolicyTemplate(),
          ])
        });

      }

     initPolicyTemplate() {
        return this._fb.group({
          policyNumber: ['', [Validators.required, Validators.pattern("(^[^0][A-Z]{1}[0-9]*$)")]],
          vinNumber: ['', [Validators.required, Validators.pattern('^[0-9]{6}$')]],
        });
      }
```
<p><strong>adding more control by calling this method</strong></p>
<pre class="lang-js prettyprint-override"><code>     addPolicyTemplate() {
        const control = <FormArray>this.lienHolder.controls['policyDetails'];
        control.push(this.initPolicyTemplate());
      }
</code>```

removing controls from the form

      removePolicyTemplate(i: number) {
        const control = <FormArray>this.lienHolder.controls['policyDetails'];
        control.removeAt(i);
      }
```
<p>but when i build the code i get error like this</p>
<p><img src="https://i.stack.imgur.com/tuArK.png" alt="enter image description here" /></p>
<p>this is my html</p>
<pre class="lang-html prettyprint-override"><code>      <div formArrayName="policyDetails">
            <div *ngFor="let _policy of lienHolder.controls.policyDetails.controls; let i=index">
              <div class="panel panel-default">
                <div class="panel-head">
                  <div class="glyphicon glyphicon-remove pull-right" *ngIf="lienHolder.controls.policyDetails.controls.length > 1" (click)="removePolicyTemplate(i)"></div>
                </div>
                <div class="panel-body">
                  <div [formGroupName]="i">
                    <address [policyGroup]="lienHolder.controls.policyDetails.controls[i]"></address>
                  </div>
                </div>
              </div>
            </div>
          </div>
</code>```

I am not able to resolve this issue. i have followed this blog to come up with the dynamic control

UPDATE 1

when i changed my .ts code like this

    get DynamicFormControls() {

        return <FormArray>this.lienHolder.get('policyDetails');
      }
```
<p>and the HTML code like this</p>
<pre class="lang-html prettyprint-override"><code>     <div formArrayName="policyDetails">
            <div *ngFor="let _policy of DynamicFormControls.controls ; let i=index" style="position: relative">
              <add-policy-details [policyGroup]="lienHolder.controls.policyDetails.controls[i]"></add-policy-details>
              <div class="remove-btn" (click)="removePolicyTemplate(i)" *ngIf="lienHolder.controls.policyDetails.controls.length > 1">
              </div>
            </div>
          </div>
</code>```

it was working, and i was able to compile the file in t he production mode, using the command

ng build --target=production --environment=prod

but from the past few days, i am facing the same error and not able to compile it in the production mode, i have not updated any of my application

node version - v6.11.1

npm version - 3.10.10

angular version - 4.0

dont know what exactly is causing the error.

答:
```<code>getArrayControls() {
    return (<FormArray>this.sampleForm.get('formArr')).controls;
  }

<div *ngFor="let elem of getArrayControls(); let i = index" [formGroupName]="i">
  <input formControlName="sampleElementOfArr">
</div>
</code>```

UPDATE:

Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead

```<code>getArrayControls() {
    return (this.sampleForm.get('formArr') as FormArray).controls;
}
</code>```

read more about Dynamically Creating Form Fields With FormArray

Body:
there are lots of blogs already posted for this error but none is specified for angular4.

I am adding and removing dynamic controls on the form

add controls to the form during intialization

    ngOnInit() {

        this.lienHolder = this._fb.group({
          emailAddress: ['', [Validators.required, Validators.email]],
          policyDetails: this._fb.array([
            this.initPolicyTemplate(),
          ])
        });

      }

     initPolicyTemplate() {
        return this._fb.group({
          policyNumber: ['', [Validators.required, Validators.pattern("(^[^0][A-Z]{1}[0-9]*$)")]],
          vinNumber: ['', [Validators.required, Validators.pattern('^[0-9]{6}$')]],
        });
      }

adding more control by calling this method

     addPolicyTemplate() {
        const control = <FormArray>this.lienHolder.controls['policyDetails'];
        control.push(this.initPolicyTemplate());
      }

removing controls from the form

      removePolicyTemplate(i: number) {
        const control = <FormArray>this.lienHolder.controls['policyDetails'];
        control.removeAt(i);
      }

but when i build the code i get error like this

this is my html

 1" (click)="removePolicyTemplate(i)">

                    <address [policyGroup]="lienHolder.controls.policyDetails.controls[i]"></address>

I am not able to resolve this issue. i have followed this blog to come up with the dynamic control

UPDATE 1

when i changed my .ts code like this

    get DynamicFormControls() {

        return <FormArray>this.lienHolder.get('policyDetails');
      }

and the HTML code like this

              <add-policy-details [policyGroup]="lienHolder.controls.policyDetails.controls[i]"></add-policy-details>

 1">

it was working, and i was able to compile the file in t he production mode, using the command

ng build --target=production --environment=prod

but from the past few days, i am facing the same error and not able to compile it in the production mode, i have not updated any of my application

node version - v6.11.1

npm version - 3.10.10

angular version - 4.0

dont know what exactly is causing the error.

Body:
getArrayControls() {
    return (<FormArray>this.sampleForm.get('formArr')).controls;
  }

<div *ngFor="let elem of getArrayControls(); let i = index" [formGroupName]="i">
  <input formControlName="sampleElementOfArr">
</div>

UPDATE:

Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead

getArrayControls() {
    return (this.sampleForm.get('formArr') as FormArray).controls;
}

read more about Dynamically Creating Form Fields With FormArray


问:
How i can fetch the data from the sqlite based on 1 spinner?
I have created an app in which I was declared 2 spinners in the first spinner I want to fetch the name of users from the SQLite database and in second spinner I want to fetch the last name based on the selection of spinner one data. In the first spinner, I was able to fetch the users name but I am not able to fetch the user last name based on name (spinner 1). </p>

<p>My spinners code  </p>

```<code>     private void loadSpinnerData() {
        List<String> lables = myDb.getAllLabels();
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                layout.simple_spinner_item, lables);
        dataAdapter           .setDropDownViewResource(layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);

//spinner 2 for last name
 List<String> lables1 = myDb.getAllLabels_one(name);//passinng name for serch in database

        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
                layout.simple_spinner_item, lables1);

        dataAdapter1            .setDropDownViewResource(layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(dataAdapter1);

     }

    public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,
                                   long id) {
            switch (parent.getId()) {
                case R.id.spinner:
                    name = parent.getItemAtPosition(position).toString();
                    spinner1.setEnabled(true);
                    break;
                case R.id.spinner1:
                    surname=parent.getItemAtPosition(position).toString();
            }
</code>```

答:
Here's a simple complete working example :-

The Database Helper DBHelper.java

```<code>public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSON = 1;

    public static final String TBL_MYTABLE = "mytable";
    public static final String COl_MYTABLE_ID = BaseColumns._ID;
    public static final String COl_MYTABLE_NAME = "name";
    public static final String COl_MYTABLE_LASTNAME = "lastname";

    public DBHelper(@Nullable Context context) {
        super(context, DBNAME, null, DBVERSON);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TBL_MYTABLE +
                "(" +
                COl_MYTABLE_ID + " INTEGER PRIMARY KEY," +
                COl_MYTABLE_NAME + " TEXT," +
                COl_MYTABLE_LASTNAME + " TEXT" +
                ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long addRow(String name, String lastname) {
        ContentValues cv = new ContentValues();
        cv.put(COl_MYTABLE_NAME,name);
        cv.put(COl_MYTABLE_LASTNAME,lastname);
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert(TBL_MYTABLE,null,cv);
    }

    public ArrayList<String> getRows(String NameFilter, boolean return__name) {
        ArrayList<String> rv = new ArrayList<>();
        String whereclause = null;
        String[] whereargs = null;
        String groupby = null;
        if (NameFilter != null && NameFilter.length() > 0) {
            whereclause = COl_MYTABLE_NAME + "=?";
            whereargs = new String[]{NameFilter};
        }
        if (return__name) {
            groupby = COl_MYTABLE_NAME;
        }
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor csr = db.query(TBL_MYTABLE,null,whereclause,whereargs,groupby,null,COl_MYTABLE_NAME);
        while (csr.moveToNext()) {
            if (return__name) {
                rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_NAME)));
            } else {
                rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_LASTNAME)));
            }
        }
        csr.close();
        return rv;
    }
}
</code>```

The getRows method takes two parameters

the first a String with the name to be selected "" or null equates to get everything.

the second, boolean, indicates whether to return the name (true) otherwsie the last name (false).

the second additionally, if true, introduces GROUP BY name thus duplicate names are not listed.

The Activity MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    Spinner mNameSpinner, mLastNameSpinner;
    ArrayAdapter<String> mNameAdapter, mLastNameAdapter;
    ArrayList<String> mNameList, mLastNameList;
    DBHelper mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNameSpinner = this.findViewById(R.id.namespinner);
        mLastNameSpinner = this.findViewById(R.id.lastnamespinner);
        mDBHlpr = new DBHelper(this);
        addSomeTestingData(); //Add some data
        manageNameSpinner(); //Manage the Name Spinner (which will manage the Lastname Spinner)
    }

    //Manage the Name Spinner - Called every-time the Spinner needs to be displayed or re-displayed
    private void manageNameSpinner() {
        mNameList = mDBHlpr.getRows(null, true);
        if (mNameAdapter == null) {
            mNameAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,mNameList);
            mNameSpinner.setAdapter(mNameAdapter);
            //NOTE if a selection is made then the LastName Spinner is managed
            mNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    manageLastNameSpinner();
                }

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

                }
            });
        } else {
            mNameAdapter.clear();
            mNameAdapter.addAll(mNameList);
            mNameAdapter.notifyDataSetChanged();
        }

    }

    //Manage the LastName Spinner - Called every-time the Spinner needs to be displayed or re-displayed
    private void manageLastNameSpinner() {
        if (mNameAdapter == null) return;
        mLastNameList = mDBHlpr.getRows(mNameSpinner.getSelectedItem().toString(),false);
        if (mLastNameAdapter == null) {
            mLastNameAdapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,mLastNameList);
            mLastNameSpinner.setAdapter(mLastNameAdapter);
        } else {
            mLastNameAdapter.clear();
            mLastNameAdapter.addAll(mLastNameList);
            mLastNameAdapter.notifyDataSetChanged();
        }
    }

    //Add some data to the database if none exists
    private void addSomeTestingData() {
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DBHelper.TBL_MYTABLE) > 0) return;
        mDBHlpr.addRow("Fred","Bloggs");
        mDBHlpr.addRow("Joe","Smith");
        mDBHlpr.addRow("Joe","Bloggs");
        mDBHlpr.addRow("Fred","Smith");
        mDBHlpr.addRow("Mary", "Jones");
        mDBHlpr.addRow("Mary", "Taylor");
        mDBHlpr.addRow("Mary", "QuiteContrary");
        mDBHlpr.addRow("Anne","Boleyn");
        mDBHlpr.addRow("Anne","Hathaway");
        mDBHlpr.addRow("Annabel","Jones");
    }
}
</code>```

Comments should explain

Result

When first run and selecting the Name Spinner :-

Selecting Anne from the Name Spinner and then selecting the LastName Spinner :-

Body:
I have created an app in which I was declared 2 spinners in the first spinner I want to fetch the name of users from the SQLite database and in second spinner I want to fetch the last name based on the selection of spinner one data. In the first spinner, I was able to fetch the users name but I am not able to fetch the user last name based on name (spinner 1).

My spinners code

     private void loadSpinnerData() {
        List<String> lables = myDb.getAllLabels();
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                layout.simple_spinner_item, lables);
        dataAdapter           .setDropDownViewResource(layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);

//spinner 2 for last name
 List<String> lables1 = myDb.getAllLabels_one(name);//passinng name for serch in database

        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
                layout.simple_spinner_item, lables1);

        dataAdapter1            .setDropDownViewResource(layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(dataAdapter1);

     }

    public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,
                                   long id) {
            switch (parent.getId()) {
                case R.id.spinner:
                    name = parent.getItemAtPosition(position).toString();
                    spinner1.setEnabled(true);
                    break;
                case R.id.spinner1:
                    surname=parent.getItemAtPosition(position).toString();
            }

Body:
Here's a simple complete working example :-

The Database Helper DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSON = 1;

    public static final String TBL_MYTABLE = "mytable";
    public static final String COl_MYTABLE_ID = BaseColumns._ID;
    public static final String COl_MYTABLE_NAME = "name";
    public static final String COl_MYTABLE_LASTNAME = "lastname";

    public DBHelper(@Nullable Context context) {
        super(context, DBNAME, null, DBVERSON);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TBL_MYTABLE +
                "(" +
                COl_MYTABLE_ID + " INTEGER PRIMARY KEY," +
                COl_MYTABLE_NAME + " TEXT," +
                COl_MYTABLE_LASTNAME + " TEXT" +
                ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long addRow(String name, String lastname) {
        ContentValues cv = new ContentValues();
        cv.put(COl_MYTABLE_NAME,name);
        cv.put(COl_MYTABLE_LASTNAME,lastname);
        SQLiteDatabase db = this.getWritableDatabase();
        return db.insert(TBL_MYTABLE,null,cv);
    }

    public ArrayList<String> getRows(String NameFilter, boolean return__name) {
        ArrayList<String> rv = new ArrayList<>();
        String whereclause = null;
        String[] whereargs = null;
        String groupby = null;
        if (NameFilter != null && NameFilter.length() > 0) {
            whereclause = COl_MYTABLE_NAME + "=?";
            whereargs = new String[]{NameFilter};
        }
        if (return__name) {
            groupby = COl_MYTABLE_NAME;
        }
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor csr = db.query(TBL_MYTABLE,null,whereclause,whereargs,groupby,null,COl_MYTABLE_NAME);
        while (csr.moveToNext()) {
            if (return__name) {
                rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_NAME)));
            } else {
                rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_LASTNAME)));
            }
        }
        csr.close();
        return rv;
    }
}

The getRows method takes two parameters

the first a String with the name to be selected "" or null equates to get everything.

the second, boolean, indicates whether to return the name (true) otherwsie the last name (false).

the second additionally, if true, introduces GROUP BY name thus duplicate names are not listed.

The Activity MainActivity.java

public class MainActivity extends AppCompatActivity {

    Spinner mNameSpinner, mLastNameSpinner;
    ArrayAdapter<String> mNameAdapter, mLastNameAdapter;
    ArrayList<String> mNameList, mLastNameList;
    DBHelper mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNameSpinner = this.findViewById(R.id.namespinner);
        mLastNameSpinner = this.findViewById(R.id.lastnamespinner);
        mDBHlpr = new DBHelper(this);
        addSomeTestingData(); //Add some data
        manageNameSpinner(); //Manage the Name Spinner (which will manage the Lastname Spinner)
    }

    //Manage the Name Spinner - Called every-time the Spinner needs to be displayed or re-displayed
    private void manageNameSpinner() {
        mNameList = mDBHlpr.getRows(null, true);
        if (mNameAdapter == null) {
            mNameAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,mNameList);
            mNameSpinner.setAdapter(mNameAdapter);
            //NOTE if a selection is made then the LastName Spinner is managed
            mNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    manageLastNameSpinner();
                }

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

                }
            });
        } else {
            mNameAdapter.clear();
            mNameAdapter.addAll(mNameList);
            mNameAdapter.notifyDataSetChanged();
        }

    }

    //Manage the LastName Spinner - Called every-time the Spinner needs to be displayed or re-displayed
    private void manageLastNameSpinner() {
        if (mNameAdapter == null) return;
        mLastNameList = mDBHlpr.getRows(mNameSpinner.getSelectedItem().toString(),false);
        if (mLastNameAdapter == null) {
            mLastNameAdapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,mLastNameList);
            mLastNameSpinner.setAdapter(mLastNameAdapter);
        } else {
            mLastNameAdapter.clear();
            mLastNameAdapter.addAll(mLastNameList);
            mLastNameAdapter.notifyDataSetChanged();
        }
    }

    //Add some data to the database if none exists
    private void addSomeTestingData() {
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DBHelper.TBL_MYTABLE) > 0) return;
        mDBHlpr.addRow("Fred","Bloggs");
        mDBHlpr.addRow("Joe","Smith");
        mDBHlpr.addRow("Joe","Bloggs");
        mDBHlpr.addRow("Fred","Smith");
        mDBHlpr.addRow("Mary", "Jones");
        mDBHlpr.addRow("Mary", "Taylor");
        mDBHlpr.addRow("Mary", "QuiteContrary");
        mDBHlpr.addRow("Anne","Boleyn");
        mDBHlpr.addRow("Anne","Hathaway");
        mDBHlpr.addRow("Annabel","Jones");
    }
}

Comments should explain

Result

When first run and selecting the Name Spinner :-

Selecting Anne from the Name Spinner and then selecting the LastName Spinner :-


问:
How can I open a file in a new tab?
How do I open a new file using Ctrl+P, so it doesn't override the current file, but rather use a new tab?

Also, would it be possible to focus the searched file instead of opening it, if it was already opened on a tab, to avoid duplicates?

答:
Go to menu File → Preferences → Settings → search for "settings.json", and at the last line before }, add a comma to the last option and paste:

"workbench.editor.enablePreview": false

For example:

```<code>{
    "editor.fontFamily": "'Consolas', 'monospace', 'Times New Roman'",
    "terminal.integrated.fontFamily": "monospace",
    "editor.fontSize": 13,
    "workbench.iconTheme": "vscode-icons",
    "workbench.editor.enablePreview": false
}
</code>```

Title: How can I open a file in a new tab?

Body:
Go to menu File → Preferences → Settings → search for "settings.json", and at the last line before }, add a comma to the last option and paste:

"workbench.editor.enablePreview": false

For example:

{
    "editor.fontFamily": "'Consolas', 'monospace', 'Times New Roman'",
    "terminal.integrated.fontFamily": "monospace",
    "editor.fontSize": 13,
    "workbench.iconTheme": "vscode-icons",
    "workbench.editor.enablePreview": false
}


问:
.htaccess - remove everything after third slash in path
On my website, I only use 3 slashes in my URL path:

```<code>https://example.com/this/isatest/
</code>```

Right now I use .htaccess which makes it possible (as a side effect) to add as many stuff on the URL as you like:

```<code>https://example.com/this/isatest/hipperdihopperdus/pizza/bacon/with/cheese
</code>```

I'd like to automatically remove everything after "isatest" while keeping the trailing slash using .htaccess.

This is what my .htaccess currently looks like:

```<code>Options -Indexes
Options +FollowSymLinks
RewriteEngine on

# 301 Redirect all requests that don't contain a dot or trailing slash to
# include a trailing slash
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !\.
RewriteRule ^(.*) %{REQUEST_URI}/ [R=301,L]

RewriteCond %{THE_REQUEST} /index\.html [NC]
RewriteRule ^index\.html$ /? [R=301,L,NC]

RewriteRule ^listen/$ /console/ [NC,L]

# Rewrites urls in the form of /parent/child/
# but only rewrites if the requested URL is not a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L,QSA]
</code>```

How can I achieve this?

答:
As your first rule, after the RewriteEngine directive, you can do something like the following:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]
</code>```

This checks if there is anything else (the dot) after two path segments and a slash, and redirects to removed "anything else".

Note that this is a 302 (temporary) redirect. Only change this to a 301 (permanent) redirect - if that is the intention - once you have confirmed that it works OK. This is to avoid the browser caching erroneous redirects whilst testing.

UPDATE: It may be more efficient to simply avoid redirecting files that end in a recognised file extension. Or perhaps exclude known directory location(s) of your static resources. For example:

```<code>RewriteCond %{REQUEST_URI} !\.(css|js|jpg|png|gif)$ [NC]
RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]
</code>```

OR,

```<code>RewriteCond %{REQUEST_URI} !^/static-resources/
RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]
</code>```

Body:
On my website, I only use 3 slashes in my URL path:

https://example.com/this/isatest/

Right now I use .htaccess which makes it possible (as a side effect) to add as many stuff on the URL as you like:

https://example.com/this/isatest/hipperdihopperdus/pizza/bacon/with/cheese

I'd like to automatically remove everything after "isatest" while keeping the trailing slash using .htaccess.

This is what my .htaccess currently looks like:

Options -Indexes
Options +FollowSymLinks
RewriteEngine on

# 301 Redirect all requests that don't contain a dot or trailing slash to
# include a trailing slash
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !\.
RewriteRule ^(.*) %{REQUEST_URI}/ [R=301,L]

RewriteCond %{THE_REQUEST} /index\.html [NC]
RewriteRule ^index\.html$ /? [R=301,L,NC]

RewriteRule ^listen/$ /console/ [NC,L]

# Rewrites urls in the form of /parent/child/
# but only rewrites if the requested URL is not a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L,QSA]

How can I achieve this?

Body:
As your first rule, after the RewriteEngine directive, you can do something like the following:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]

This checks if there is anything else (the dot) after two path segments and a slash, and redirects to removed "anything else".

Note that this is a 302 (temporary) redirect. Only change this to a 301 (permanent) redirect - if that is the intention - once you have confirmed that it works OK. This is to avoid the browser caching erroneous redirects whilst testing.

UPDATE: It may be more efficient to simply avoid redirecting files that end in a recognised file extension. Or perhaps exclude known directory location(s) of your static resources. For example:

RewriteCond %{REQUEST_URI} !\.(css|js|jpg|png|gif)$ [NC]
RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]

OR,

RewriteCond %{REQUEST_URI} !^/static-resources/
RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]


答:
You can add this rule just below RewriteEngine On line:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+/[^/]+/).+$ /$1 [R=301,L,NE]
</code>```

Title: .htaccess - remove everything after third slash in path

Body:
You can add this rule just below RewriteEngine On line:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+/[^/]+/).+$ /$1 [R=301,L,NE]


答:
Use set:

```<code>usa = ["kebab","pizza", "hamburger"]
uk = ["kebab", "hamburger"]

s1 = set(usa)
s2 = set(uk)

s1.issuperset(s2) # True
s2.issubset(s1)   # False
</code>```

And find the intersection:

```<code>s1.intersection(s2) # {'hamburger', 'kebab'}
</code>```

Title: Python comparing two lists for values

Body:
Use set:

usa = ["kebab","pizza", "hamburger"]
uk = ["kebab", "hamburger"]

s1 = set(usa)
s2 = set(uk)

s1.issuperset(s2) # True
s2.issubset(s1)   # False

And find the intersection:

s1.intersection(s2) # {'hamburger', 'kebab'}


问:
How to multiply the two nearby elements in a list?
I have a list like below:

```<code>a = [ 1, 2 , 3, 4, s, s+1]
</code>```

I want to keep the first two elements and then multiply the rest two nearby elements.
The result would be like below:

```<code>b = [1, 2, 12, s**2 + s]
</code>```

I know if I want the summation, I can use the code below:

```<code>b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)
</code>```

and I will get the result which is : [1, 2, 7, 2*s + 1]
However, I don't know how to get the multpilication result.
Thanks

Body:
I have a list like below:

a = [ 1, 2 , 3, 4, s, s+1]

I want to keep the first two elements and then multiply the rest two nearby elements.
The result would be like below:

b = [1, 2, 12, s**2 + s]

I know if I want the summation, I can use the code below:

b = [*a[:2], *map(sum, (a[i: i + 2] for i in range(2, len(a), 2)))]
print (b)

and I will get the result which is : [1, 2, 7, 2*s + 1]
However, I don't know how to get the multpilication result.
Thanks

Body:
Can also use zip:

a = list(range(1, 11))

b = a[:2] + [x*y  for x, y in zip(a[2::2], a[3::2])]
b
[1, 2, 12, 30, 56, 90]


问:
C# Multiply Each row of array by set of factors
I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.

Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }

and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}

to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }

I've tried to use .Length within a for loop using the example code.

```<code>double [] factors = {0.5, 0.4, 0, 0.8};

int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};

double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
    output[i] = myarray[i] * factors;
</code>```

I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.

答:
I am not sure if you find it useful, but you can achieve it by using MathNet.Numerics:

PM> Install-Package MathNet.Numerics

```<code>using MathNet.Numerics.LinearAlgebra.Double;
using System.Linq;

...

var myarray = new double[3, 4]
{
    { 1, 2, 3, 4},
    { 5, 6, 7, 8},
    { 9, 10, 11, 12}
};

var factors = new double[4] { 0.5, 0.4, 0, 0.8 };

var matrix1 = Matrix.Build
    .DenseOfArray(myarray);
var matrix2 = Matrix.Build
    .DenseOfRows(Enumerable.Repeat(factors, matrix1.RowCount));

var res = matrix1.PointwiseMultiply(matrix2).ToArray();
</code>```

Body:
I have a multidimensional array and I want to multiply each row of it by a single dimensional array containing factors to create a new multidimensional array. However, the number of rows in the multidimensional array will vary from one run to the next, so I'll need a way to loop the multiplication through each row of the multidimensional array until the last row is reached.

Here is a simple example, I have multidimensional array:
{ { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12} }

and I want to multiply each row by:
{0.5, 0.4, 0, 0.8}

to get:
{ { 1*0.5, 2*0.4, 3*0, 4*0.8}, { 5*0.5, 6*0.4, 7*0, 8*0.8}, { 9*0.5, 10*0.4, 11*0, 12*0.8} }

I've tried to use .Length within a for loop using the example code.

double [] factors = {0.5, 0.4, 0, 0.8};

int [,] myarray = new int [3,4] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12}
};

double [] output = new double[myarray.Length];
for(int i = 0; i < myarray.Length; ++i)
    output[i] = myarray[i] * factors;

I'm getting syntax errors that extension method 'Length' cannot be applied to type int, and also indexing with [] cannot be applied to type int.

Body:
I am not sure if you find it useful, but you can achieve it by using MathNet.Numerics:

PM> Install-Package MathNet.Numerics

using MathNet.Numerics.LinearAlgebra.Double;
using System.Linq;

...

var myarray = new double[3, 4]
{
    { 1, 2, 3, 4},
    { 5, 6, 7, 8},
    { 9, 10, 11, 12}
};

var factors = new double[4] { 0.5, 0.4, 0, 0.8 };

var matrix1 = Matrix.Build
    .DenseOfArray(myarray);
var matrix2 = Matrix.Build
    .DenseOfRows(Enumerable.Repeat(factors, matrix1.RowCount));

var res = matrix1.PointwiseMultiply(matrix2).ToArray();


问:
ListVIew doesn't scroll to the correct offset position after its built again
I want the listview to start with an offset. Which I am trying to achieve by using below code in the ListView.

controller: ScrollController(initialScrollOffset: 30 * ITEM_HEIGHT),

Initially on the first load the list is loaded with the correct offset.

When the list is built again by calling set state from the parent widget, the list gets updated but the scroll offset behaves weird.

There are two scenarios:

I don't scroll the list: After this if the set state is called everything works fine. List gets updated and is always at the correct offset.

I scroll the list: if I scroll the list and then the list is rebuilt,
the scroll offset is off by a few items. The list gets updated which is fine.

Is it because when I scroll it keeps the last scroll position and that offsets my calculation? Which I think should not happen as it is a state less widget.

```<code>class DaysManager extends StatelessWidget {
  final int daysBeforeFocusDate = 30;
  final int totalDaysToInit = 61;
  static final double ITEM_HEIGHT = 108.00;

  ScrollController scrollController;

  List<Day> days;

  DaysManager({DateTime focusDate}) {
      final DateTime startDate =
      focusDate.subtract(Duration(days: daysBeforeFocusDate));
      days = List.generate(totalDaysToInit, (int index) {
      return Day(
       date: startDate.add(
        Duration(days: index),
    ),
  );
});

scrollController = ScrollController(initialScrollOffset: 30 *ITEM_HEIGHT);
}

  @override
  Widget build(BuildContext context) {
   return _buildScrollView();
  }

  ListView _buildScrollView() {
    ListView listView = ListView.builder(
    cacheExtent: 0,
    controller: scrollController,
    itemCount: days.length,
    itemBuilder: (BuildContext context, int index) {
      return days[index];
     });

    return listView;
  }
 }
</code>```

答:
I reached out the the Flutter Slack community and got an answer that works. All credit to Loushou over there. Here's a copy of that conversation.

ScrollController saves it’s scroll position inside the PageStorage record of the list it is attached to… not of it’s own PageStorage. because of this, when the widget is recreated, since you do not specify a new key for the listview widget, it reuses the same key (one of the many optimizations internal to flutter for performance). you can solve this by adding two lines:

```<code>import 'dart:math';
...
ListView listView = ListView.builder(
  key: ValueKey<int>(Random(DateTime.now().millisecondsSinceEpoch).nextInt(4294967296)),
...
</code>```

You need to give the listview a new, random key every time you recreate it, so that it does not load up it’s PageStorage values.

here is the full, updated code for DaysManager from your example code:

```<code>class DaysManager extends StatelessWidget {
  final int daysBeforeFocusDate = 30;
  final int totalDaysToInit = 61;
  static final double ITEM_HEIGHT = 108.00;

  ScrollController scrollController;

  List<Day> days;

  DaysManager({
    DateTime focusDate,
  }) {
    final DateTime startDate = focusDate.subtract(Duration(days: daysBeforeFocusDate));
    days = List.generate(totalDaysToInit, (int index) {
      return Day(
        date: startDate.add(
          Duration(days: index),
        ),
      );
    });

    scrollController = ScrollController(
      initialScrollOffset: 30 *ITEM_HEIGHT,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildScrollView();
  }

  ListView _buildScrollView() {
    ListView listView = ListView.builder(
      key: ValueKey<int>(Random(DateTime.now().millisecondsSinceEpoch).nextInt(4294967296)),
      cacheExtent: 0,
      controller: scrollController,
      itemCount: days.length,
      itemBuilder: (BuildContext context, int index) {
        return days[index];
      });

    return listView;
  }
}
</code>```

Body:
I want the listview to start with an offset. Which I am trying to achieve by using below code in the ListView.

controller: ScrollController(initialScrollOffset: 30 * ITEM_HEIGHT),

Initially on the first load the list is loaded with the correct offset.

When the list is built again by calling set state from the parent widget, the list gets updated but the scroll offset behaves weird.

There are two scenarios:

I don't scroll the list: After this if the set state is called everything works fine. List gets updated and is always at the correct offset.

I scroll the list: if I scroll the list and then the list is rebuilt,
the scroll offset is off by a few items. The list gets updated which is fine.

Is it because when I scroll it keeps the last scroll position and that offsets my calculation? Which I think should not happen as it is a state less widget.

class DaysManager extends StatelessWidget {
  final int daysBeforeFocusDate = 30;
  final int totalDaysToInit = 61;
  static final double ITEM_HEIGHT = 108.00;

  ScrollController scrollController;

  List<Day> days;

  DaysManager({DateTime focusDate}) {
      final DateTime startDate =
      focusDate.subtract(Duration(days: daysBeforeFocusDate));
      days = List.generate(totalDaysToInit, (int index) {
      return Day(
       date: startDate.add(
        Duration(days: index),
    ),
  );
});

scrollController = ScrollController(initialScrollOffset: 30 *ITEM_HEIGHT);
}

  @override
  Widget build(BuildContext context) {
   return _buildScrollView();
  }

  ListView _buildScrollView() {
    ListView listView = ListView.builder(
    cacheExtent: 0,
    controller: scrollController,
    itemCount: days.length,
    itemBuilder: (BuildContext context, int index) {
      return days[index];
     });

    return listView;
  }
 }

Body:
I reached out the the Flutter Slack community and got an answer that works. All credit to Loushou over there. Here's a copy of that conversation.

ScrollController saves it’s scroll position inside the PageStorage record of the list it is attached to… not of it’s own PageStorage. because of this, when the widget is recreated, since you do not specify a new key for the listview widget, it reuses the same key (one of the many optimizations internal to flutter for performance). you can solve this by adding two lines:

import 'dart:math';
...
ListView listView = ListView.builder(
  key: ValueKey<int>(Random(DateTime.now().millisecondsSinceEpoch).nextInt(4294967296)),
...

You need to give the listview a new, random key every time you recreate it, so that it does not load up it’s PageStorage values.

here is the full, updated code for DaysManager from your example code:

class DaysManager extends StatelessWidget {
  final int daysBeforeFocusDate = 30;
  final int totalDaysToInit = 61;
  static final double ITEM_HEIGHT = 108.00;

  ScrollController scrollController;

  List<Day> days;

  DaysManager({
    DateTime focusDate,
  }) {
    final DateTime startDate = focusDate.subtract(Duration(days: daysBeforeFocusDate));
    days = List.generate(totalDaysToInit, (int index) {
      return Day(
        date: startDate.add(
          Duration(days: index),
        ),
      );
    });

    scrollController = ScrollController(
      initialScrollOffset: 30 *ITEM_HEIGHT,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildScrollView();
  }

  ListView _buildScrollView() {
    ListView listView = ListView.builder(
      key: ValueKey<int>(Random(DateTime.now().millisecondsSinceEpoch).nextInt(4294967296)),
      cacheExtent: 0,
      controller: scrollController,
      itemCount: days.length,
      itemBuilder: (BuildContext context, int index) {
        return days[index];
      });

    return listView;
  }
}


问:
Combining output of two java servlets
I'm making a hostel management system with backend in java. I made a header class that shows the menu and I want it to be included on every servlet of my project. I have tried using request dispatcher. like this:

```<code>RequestDispatcher rd1 = req.getRequestDispatcher("/header");
    rd1.include(req, res);
</code>```

When I put it on some servlet, the output of that servlet is removed(only that output which is placed after this include line) and only header servlet is displayed. I have overloaded both doGet() and doPost() methods in header servlet.

The Following picture shows that my header is working fine

An Example servlet is here in which I'm including header servlet.

```<code>import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class add extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
    PrintWriter out = res.getWriter();

    res.setContentType("text/html");
    out.println("<html><head><title>Add student</title></head>");
    RequestDispatcher rd1 = req.getRequestDispatcher("/header");
    rd1.include(req, res);           //I want to show the data after this line as well
    out.println("<form method='post' action='addtoDatabase'>");
    out.println("Roll Number : <input type='text' name='roll' placeholder='student Roll Number'><br>");
    out.println("Name : <input type='text' name='studentName' autofocus placeholder='student name'><br>");
    out.println("room number : <input type='text' name='roomNumber' placeholder='Room Number'><br>");
    out.println("Address : <input type='text' name='address' placeholder='Address'><br>");
    out.println("Phone : <input type='text' name='phone' placeholder='03001234567'><br>");
    out.println("<input type='submit' value='Add Student'> ");

    out.println("</form></body></html>");
    out.close();
}
}
</code>```

In the above code, the HTML form is not been displayed on the browser. Only the header is displayed as I have shown in the following screenshot.

Screenshot of remove page

How can I combine the output of both header and any other servlets on the browser?

答: there are Session Scope, also have Application Scope. I am wondering what are you achieving is share some data between different sessions. That is you need Application Scope. That is ServletContext , Please refer to Using application scope variables in java

Title: Combining output of two java servlets

Body:
I'm making a hostel management system with backend in java. I made a header class that shows the menu and I want it to be included on every servlet of my project. I have tried using request dispatcher. like this:

RequestDispatcher rd1 = req.getRequestDispatcher("/header");
    rd1.include(req, res);

When I put it on some servlet, the output of that servlet is removed(only that output which is placed after this include line) and only header servlet is displayed. I have overloaded both doGet() and doPost() methods in header servlet.

The Following picture shows that my header is working fine

An Example servlet is here in which I'm including header servlet.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class add extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
    PrintWriter out = res.getWriter();

    res.setContentType("text/html");
    out.println("<title>Add student</title>");
    RequestDispatcher rd1 = req.getRequestDispatcher("/header");
    rd1.include(req, res);           //I want to show the data after this line as well
    out.println("<form method='post' action='addtoDatabase'>");
    out.println("Roll Number : <input type='text' name='roll' placeholder='student Roll Number'>
");
    out.println("Name : <input type='text' name='studentName' autofocus placeholder='student name'>
");
    out.println("room number : <input type='text' name='roomNumber' placeholder='Room Number'>
");
    out.println("Address : <input type='text' name='address' placeholder='Address'>
");
    out.println("Phone : <input type='text' name='phone' placeholder='03001234567'>
");
    out.println("<input type='submit' value='Add Student'> ");

    out.println("</form>");
    out.close();
}
}

In the above code, the HTML form is not been displayed on the browser. Only the header is displayed as I have shown in the following screenshot.

Screenshot of remove page

How can I combine the output of both header and any other servlets on the browser?


问:
CakePHP and referential integrity
My DB server doesn't support innodb engine, so I can't use Foreign key
costraints at DB level.
How can I assure referential intergrity? Can I do this using cakephp model,
how?</p>

答:
I'm using myISAM engine on my tables with cakePHP, had no problems so far =).

foreign keys are defined in model like this:

```<code>// this is a property of Post Model

    var $belongsTo = array(
    'PostCategory' => array(
        'className' => 'PostCategory',
        'foreignKey' => 'post_category_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);
</code>```

this means that current model is associated with PostCategory model using post_category_id column as a foreign key.

Title: CakePHP and referential integrity

Body:
I'm using myISAM engine on my tables with cakePHP, had no problems so far =).

foreign keys are defined in model like this:

// this is a property of Post Model

    var $belongsTo = array(
    'PostCategory' => array(
        'className' => 'PostCategory',
        'foreignKey' => 'post_category_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

this means that current model is associated with PostCategory model using post_category_id column as a foreign key.


问:
Bypassing character limit on OPENQUERY failing use EXECUTE
I am currently using SQL Server Management Studio 17 to connect to an Oracle database instance and then extract some data and insert it into a SQL Server Table I have.

I have tried doing the following:

```<code>DROP TABLE IF EXISTS [jerry].[dbo].[purchases]
SELECT * INTO [jerry].[dbo].[purchases] FROM OPENQUERY(OLAP, '

    proprietary sql code

');
</code>```

However the SQL code is about 9500 characters and thus OPENQUERY fails, which is supported by MSDN articles

I referenced these sites:

- MSDN One  - MSDN Two

and learned that I can use EXEC to accomplish my goal.
I have tried to implement the following:

```<code>EXEC master.dbo.sp_serveroption @server=N'OLAP', @optname=N'rpc out', @optvalue=N'true'
DECLARE @sqlcode VARCHAR(MAX)
SET @sqlcode = 'sql code'

DROP TABLE IF EXISTS [jerry].[dbo].[purchases]
EXEC @sqlcode AT OLAP
</code>```

However, I am still getting an Invalid Syntax near OLAP error.
I have confirmed that OLAP is the correct name from our DBA and other OPENQUERY functions work just fine (with much shorter SQL statements).

I cannot edit the SQL query

I cannot edit the external OLAP's databases permissions (I am not the DBA nor am I in the security group)

Any assistance is greatly appreciated.

答:
EXEC without parentheses runs a stored procedure.

So try:

```<code>truncate table [jerry].[dbo].[purchases]

insert into [jerry].[dbo].[purchases]
exec ( @sqlcode ) at olap
</code>```

See execute

Body:
I am currently using SQL Server Management Studio 17 to connect to an Oracle database instance and then extract some data and insert it into a SQL Server Table I have.

I have tried doing the following:

DROP TABLE IF EXISTS [jerry].[dbo].[purchases]
SELECT * INTO [jerry].[dbo].[purchases] FROM OPENQUERY(OLAP, '

    proprietary sql code

');

However the SQL code is about 9500 characters and thus OPENQUERY fails, which is supported by MSDN articles

I referenced these sites:

- MSDN One  - MSDN Two

and learned that I can use EXEC to accomplish my goal.
I have tried to implement the following:

EXEC master.dbo.sp_serveroption @server=N'OLAP', @optname=N'rpc out', @optvalue=N'true'
DECLARE @sqlcode VARCHAR(MAX)
SET @sqlcode = 'sql code'

DROP TABLE IF EXISTS [jerry].[dbo].[purchases]
EXEC @sqlcode AT OLAP

However, I am still getting an Invalid Syntax near OLAP error.
I have confirmed that OLAP is the correct name from our DBA and other OPENQUERY functions work just fine (with much shorter SQL statements).

I cannot edit the SQL query

I cannot edit the external OLAP's databases permissions (I am not the DBA nor am I in the security group)

Any assistance is greatly appreciated.

Body:
EXEC without parentheses runs a stored procedure.

So try:

truncate table [jerry].[dbo].[purchases]

insert into [jerry].[dbo].[purchases]
exec ( @sqlcode ) at olap

See execute


问:
How to filter options in app maker's SuggestBox
I need to implement filtering for options in SuggestBox.
I've tried to do it differently, but none of my attempts worked out:

Using Model instead of Options/Value; Create calculated SQL model and pass the parameter for filtration:

Didn't work: suggestBox doesn't have event or anything to call before it loads data, so if you pass param for query before typing anything in -- it is not seen an you get an error:

```<code>Please provide value for the parameter ":Param" used in the query Error: Please provide value for the parameter ":Param" used in the query
Query for record suggest oracle: (Error) : Please provide value for the parameter ":Param" used in the query
Query for record suggest oracle failed.

</code>```

Using Options/Value

It seems that it is impossible to have different properties of an object when passing it to Suggest Box. For example, I want user to see an user-friendly field Name and work with a record or at least record's Id, but if you specify Name as an option and Id as a value, Name is being written to a SuggestBox and now we get a validation error because Name is a string and Id is a Number.

Please help me realize where I'm wrong or show me a workaround for this.
Thanks!

答:
I had the same issue as well. I gave up on the suggest box and created a pop up form. With a query builder model for the data source. The only thing i don't like is that it seems to be case sensitive.

something like:

```<code>YourFilterColumn startsWith? :Param
</code>```

Add a table view and then you can add a text box and set the oninputchange event to:

```<code>widget.datasource.query.parameters.Param = widget.value;
widget.datasource.load();
</code>```

Then you can start typing select the record you want and pass it back to your form with a button.

like this if it is a relational field:

```<code>app.pages.YourPage.children.YourForm.datasource.item.YourItem =
widget.datasource.item;
</code>```

or something like this if you just need a value (haven't tested this):

```<code>app.pages.YourPage.children.YourForm.datasource.item.YourItem =
widget.datasource.item.YourValue;
</code>```

Probably add a couple lines to clear the form out:

```<code>widget.root.descendants.TextBox1.value = "";
widget.datasource.query.parameters.Param = "";
widget.datasource.load();
</code>```

Body:
I need to implement filtering for options in SuggestBox.
I've tried to do it differently, but none of my attempts worked out:

Using Model instead of Options/Value; Create calculated SQL model and pass the parameter for filtration:

Didn't work: suggestBox doesn't have event or anything to call before it loads data, so if you pass param for query before typing anything in -- it is not seen an you get an error:

Please provide value for the parameter ":Param" used in the query Error: Please provide value for the parameter ":Param" used in the query
Query for record suggest oracle: (Error) : Please provide value for the parameter ":Param" used in the query
Query for record suggest oracle failed.

Using Options/Value

It seems that it is impossible to have different properties of an object when passing it to Suggest Box. For example, I want user to see an user-friendly field Name and work with a record or at least record's Id, but if you specify Name as an option and Id as a value, Name is being written to a SuggestBox and now we get a validation error because Name is a string and Id is a Number.

Please help me realize where I'm wrong or show me a workaround for this.
Thanks!

Body:
I had the same issue as well. I gave up on the suggest box and created a pop up form. With a query builder model for the data source. The only thing i don't like is that it seems to be case sensitive.

something like:

YourFilterColumn startsWith? :Param

Add a table view and then you can add a text box and set the oninputchange event to:

widget.datasource.query.parameters.Param = widget.value;
widget.datasource.load();

Then you can start typing select the record you want and pass it back to your form with a button.

like this if it is a relational field:

app.pages.YourPage.children.YourForm.datasource.item.YourItem =
widget.datasource.item;

or something like this if you just need a value (haven't tested this):

app.pages.YourPage.children.YourForm.datasource.item.YourItem =
widget.datasource.item.YourValue;

Probably add a couple lines to clear the form out:

widget.root.descendants.TextBox1.value = "";
widget.datasource.query.parameters.Param = "";
widget.datasource.load();


问:
AWS Elastic Beanstalk - Shared counter variable between instances
I have a Python Flask app running on Elastic Beanstalk with auto-scaling enabled. Now I would like to have a global counter variable that can be accessed and updated by all running instances in real-time.

I have looked at Redis with AWS ElastiCache but that seems overkill for my use-case since I have to store a single counter variable. I have also looked at the option of running Redis on one of the Beanstalk instances but that is not feasible because Beanstalk can shut off instances when down-scaling.

What is the best way to achieve this functionality? Any way to get away without using ElastiCache?

答:
Have you considered using an Amazon DynamoDB table?

It has Atomic Counters:

You can use the UpdateItem operation to implement an atomic counter—a numeric attribute that is incremented, unconditionally, without interfering with other write requests. (All write requests are applied in the order in which they were received.) With an atomic counter, the updates are not idempotent. In other words, the numeric value will increment each time you call UpdateItem.

You might use an atomic counter to keep track of the number of visitors to a website. In this case, your application would increment a numeric value, regardless of its current value.


问:
Ways to limit output of NN regression problem in certain limit(i.e. I want my NN to always predict output values only between -20 to +30)
I am training NN for the regression problem. So the output layer has a linear activation function. NN output is supposed to be between -20 to 30. My NN is performing good most of the time. However, sometimes it gives output more than 30 which is not desirable for my system. So does anyone know any activation function that can provide such kind of restriction on output or any suggestions on modifying linear activation function for my application?

I am using Keras with tenserflow backend for this application

答:
What you can do is to activate your last layer with a sigmoid, the result will be between 0 and 1 and then create a custom layer in order to get the desired range :

```<code>def get_range(input, maxx, minn):
    return (minn - maxx) * ((input - K.min(input, axis=1))/ (K.max(input, axis=1)*K.min(input, axis=1))) + maxx
</code>```

and then add this to your network :

```<code>out = layers.Lambda(get_range, arguments={'maxx': 30, 'minn': -20})(sigmoid_output)
</code>```

The output will be normalized between 'maxx' and 'minn'.

UPDATE

If you want to clip your data without normalizing all your outputs, do this instead :

```<code>def clip(input, maxx, minn):
    return K.clip(input, minn, maxx)

out = layers.Lambda(clip, arguments={'maxx': 30, 'minn': -20})(sigmoid_output)
</code>```

Body:
What you can do is to activate your last layer with a sigmoid, the result will be between 0 and 1 and then create a custom layer in order to get the desired range :

def get_range(input, maxx, minn):
    return (minn - maxx) * ((input - K.min(input, axis=1))/ (K.max(input, axis=1)*K.min(input, axis=1))) + maxx

and then add this to your network :

out = layers.Lambda(get_range, arguments={'maxx': 30, 'minn': -20})(sigmoid_output)

The output will be normalized between 'maxx' and 'minn'.

UPDATE

If you want to clip your data without normalizing all your outputs, do this instead :

def clip(input, maxx, minn):
    return K.clip(input, minn, maxx)

out = layers.Lambda(clip, arguments={'maxx': 30, 'minn': -20})(sigmoid_output)


问:
How to convert byte position in swift
How would I convert this properly? the value I need is byte number 0-1, has a format of uint16 and its units are in degrees.</p>

```<code>print("derived : \(characteristic.value!)")
print(String(bytes: characteristic.value!, encoding: .utf16))

derived : 20 bytes
Optional("\0{Ͽ⌜ƀ")
</code>```

答:
You just need to get the first two bytes of the Data as UInt16.

```<code>var result: UInt16 = 0
_ = withUnsafeMutableBytes(of: &result) {characteristic.value!.copyBytes(to: $0, from: 0...1)}
print("\(result) degrees")
</code>```

Assuming your format of uint16 is in Little-Endian as well as iOS, which is more often found in BLE characteristics.

(When you get the first value in Data, from: 0...1 is not needed, but you may want some data in other position.)

Title: How to convert byte position in swift

Body:
How would I convert this properly? the value I need is byte number 0-1, has a format of uint16 and its units are in degrees.

print("derived : \(characteristic.value!)")
print(String(bytes: characteristic.value!, encoding: .utf16))

derived : 20 bytes
Optional("\0{Ͽ⌜ƀ")

Body:
You just need to get the first two bytes of the Data as UInt16.

var result: UInt16 = 0
_ = withUnsafeMutableBytes(of: &result) {characteristic.value!.copyBytes(to: $0, from: 0...1)}
print("\(result) degrees")

Assuming your format of uint16 is in Little-Endian as well as iOS, which is more often found in BLE characteristics.

(When you get the first value in Data, from: 0...1 is not needed, but you may want some data in other position.)


问:
Visual themes and Delphi 7 on Windows 7
how I can enable using visual themes for Delphi 7 IDE on Windows 7? For Windows XP I made file delphi32.exe.manifest, but for Windows 7 it does not work.

I mean Delphi 7 enviroment and development. My programs are OK.

Thank you, Pavel

答:
This is an informed solution, though I haven't tested it (I don't use Delphi 7 anymore)...

You need to create a Package, and that package required DesignIDE. In your package, add a unit (doesn't matter what you call it)... now put the following code in your unit:

```<code>unit D7WithTheme;

interface

uses
  XPMan;

var
  D7Theme: TXPManifest;

implementation

initialization
  D7Theme := TXPManifest.Create(nil);
finalization
  D7Theme.Free;
</code>```

Save and install your package... you should now have OS theming when you load the IDE! Hope it helps!

ContentLicense: CC BY-SA 2.5

Title: Visual themes and Delphi 7 on Windows 7

Body:
This is an informed solution, though I haven't tested it (I don't use Delphi 7 anymore)...

You need to create a Package, and that package required DesignIDE. In your package, add a unit (doesn't matter what you call it)... now put the following code in your unit:

unit D7WithTheme;

interface

uses
  XPMan;

var
  D7Theme: TXPManifest;

implementation

initialization
  D7Theme := TXPManifest.Create(nil);
finalization
  D7Theme.Free;

Save and install your package... you should now have OS theming when you load the IDE! Hope it helps!