问:
Reading a line from a file and storing it in variables
I've got a file with 2-3 lines, and every line I want to store in a char* variable, then translate it and store it to other appropriate variables.

not in unix, just in c, there's a fscanf(%d,%s,%s, 1,2,3); and thats it, but in unix it is somewhat weird.

For example: a abc 12 12

Storing it in char msg[20], and then msg[20] will be stored in 4 variables, one char, one char* and two integers. How can It be done?

Here what I got so far:

```<code>int ret_in, in1,file;
char buffer1[BUF_SIZE];
int i =0;

    char fn[5] = "file";

      char msg[20];
     file = open(fn,O_WRONLY|O_CREAT,0644);
     //msg = "test";

    while(((ret_in = read (file, &buffer1, BUF_SIZE)) > 0))
      {
       for(i; i<ret_in; i++)
        {
         if(buffer1[i]!='\n')
          msg[i] = buffer1[i];
        }
    }
    printf("%s", msg); //TEST: check msg
    close(file);
</code>```

It stores it fine in the msg variable, but if it composed of 4 'items' i want to store in different variables, how can I do it efficiently?

答:
You can use fopen() to open a file and get a pointer to a file stream. This pointer can be passed to fgets() to retrieve lines from the file and store them in a buffer. This buffer can then be parsed by using sscanf().

Here is an example of how this might work. Note that here I am using arrays to store the components of the fields from each line; you may have different requirements.

```<code>#include <stdio.h>
#include <stdlib.h>

#define MAX_LINES  100

int main(void)
{
    FILE *fp = fopen("my_file.txt", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        exit(EXIT_FAILURE);
    }

    char buffer[1000];
    char id[MAX_LINES];
    char msg[MAX_LINES][10];
    int val_a[MAX_LINES];
    int val_b[MAX_LINES];
    size_t lines = 0;

    while (fgets(buffer, sizeof buffer, fp) != NULL) {
        if (sscanf(buffer, "%c%9s%d%d",
                   &id[lines], msg[lines], &val_a[lines], &val_b[lines]) == 4) {
            ++lines;
        }
    }

    for (size_t i = 0; i < lines; i++) {
        printf("Line %zu: %c -- %s -- %d -- %d\n",
               i+1, id[i], msg[i], val_a[i], val_b[i]);
    }

    fclose(fp);

    return 0;
}
</code>```

Using this text file as input:

```<code>A abc 12 34
B def 24 68
C ghi 35 79
</code>```

gives the following output:

```<code>Line 1: A -- abc -- 12 -- 34
Line 2: B -- def -- 24 -- 68
Line 3: C -- ghi -- 35 -- 79
</code>```

Body:
I've got a file with 2-3 lines, and every line I want to store in a char* variable, then translate it and store it to other appropriate variables.

not in unix, just in c, there's a fscanf(%d,%s,%s, 1,2,3); and thats it, but in unix it is somewhat weird.

For example: a abc 12 12

Storing it in char msg[20], and then msg[20] will be stored in 4 variables, one char, one char* and two integers. How can It be done?

Here what I got so far:

int ret_in, in1,file;
char buffer1[BUF_SIZE];
int i =0;

    char fn[5] = "file";

      char msg[20];
     file = open(fn,O_WRONLY|O_CREAT,0644);
     //msg = "test";

    while(((ret_in = read (file, &buffer1, BUF_SIZE)) > 0))
      {
       for(i; i<ret_in; i++)
        {
         if(buffer1[i]!='\n')
          msg[i] = buffer1[i];
        }
    }
    printf("%s", msg); //TEST: check msg
    close(file);

It stores it fine in the msg variable, but if it composed of 4 'items' i want to store in different variables, how can I do it efficiently?

Body:
You can use fopen() to open a file and get a pointer to a file stream. This pointer can be passed to fgets() to retrieve lines from the file and store them in a buffer. This buffer can then be parsed by using sscanf().

Here is an example of how this might work. Note that here I am using arrays to store the components of the fields from each line; you may have different requirements.

#include <stdio.h>
#include <stdlib.h>

#define MAX_LINES  100

int main(void)
{
    FILE *fp = fopen("my_file.txt", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        exit(EXIT_FAILURE);
    }

    char buffer[1000];
    char id[MAX_LINES];
    char msg[MAX_LINES][10];
    int val_a[MAX_LINES];
    int val_b[MAX_LINES];
    size_t lines = 0;

    while (fgets(buffer, sizeof buffer, fp) != NULL) {
        if (sscanf(buffer, "%c%9s%d%d",
                   &id[lines], msg[lines], &val_a[lines], &val_b[lines]) == 4) {
            ++lines;
        }
    }

    for (size_t i = 0; i < lines; i++) {
        printf("Line %zu: %c -- %s -- %d -- %d\n",
               i+1, id[i], msg[i], val_a[i], val_b[i]);
    }

    fclose(fp);

    return 0;
}

Using this text file as input:

A abc 12 34
B def 24 68
C ghi 35 79

gives the following output:

Line 1: A -- abc -- 12 -- 34
Line 2: B -- def -- 24 -- 68
Line 3: C -- ghi -- 35 -- 79


来源: stackexchange

问:
How to create a list from another list according to a function?
I would like to create a list which has values which correspond to another list.
For example if I had:

```<code>listA = [1, 2, 3, 4, 5,...]
</code>```

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

```<code>listB = [1, 4, 9, 16,25, ...]
</code>```

I have already tried to do this by doing a while loop:

```<code>listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB
</code>```

But it just spits out an error message:

```<code>Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range
</code>```

Any advice?
Thanks

答:
You can use the numpy library with a function called power

```<code>import numpy as np

listA = [1,2,3,4]

new_li = np.power(listA, 2)

print new_li

>>> [ 1  4  9 16]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to create a list which has values which correspond to another list.
For example if I had:

listA = [1, 2, 3, 4, 5,...]

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

listB = [1, 4, 9, 16,25, ...]

I have already tried to do this by doing a while loop:

listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB

But it just spits out an error message:

Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range

Any advice?
Thanks

Body:
You can use the numpy library with a function called power

import numpy as np

listA = [1,2,3,4]

new_li = np.power(listA, 2)

print new_li

>>> [ 1  4  9 16]


问:
Javafx: Reusable collections using FXML
I'd like to bind a single collection to multiple ChoiceBox's in FXML.
However the only way I know how is using:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
    <items>
        <FXCollections fx:id="test" fx:factory="observableArrayList">
            <String fx:value="1" />
            <String fx:value="2" />
            <String fx:value="3" />
            <String fx:value="4" />
            <String fx:value="5" />
            <String fx:value="6" />
            <String fx:value="7" />
            <String fx:value="8" />
            <String fx:value="9" />
        </FXCollections>
    </items>
</ChoiceBox>
```

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

答:
It can be in the controller or any other class like (the example is for a combobox. The same can be applied to a choicebox):

combo.fxml

```<code><?import javafx.scene.control.ComboBox?>
<ComboBox  fx:id="combo1" items="${itemLoader.items}"  prefWidth="150.0"
xmlns:fx="http://javafx.com/fxml/1" >
</ComboBox>
</code>```

Loader class

```<code>public class ComboLoader {

    private ObservableList<String> obsStrings;

    public ComboLoader() {

        obsStrings = FXCollections.observableArrayList(createStrings());
    }

    private List<String> createStrings() {
            return IntStream.rangeClosed(0, 5)
                    .mapToObj(i -> "String "+i)
                    .map(String::new)
                    .collect(Collectors.toList());
    }
    //name of this method corresponds to itemLoader.items in xml.
    //if xml name was itemLoader.a this method should have been
    //getA(). A bit odd
    public ObservableList<String> getItems(){

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

test it with:

```<code>public class ComboTest extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        primaryStage.setTitle("Populate combo from custom builder");

        Group group = new Group();
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(25, 25, 25, 25));
        group.getChildren().add(grid);

        FXMLLoader loader = new FXMLLoader(getClass().getResource("combo.fxml"));
        loader.getNamespace().put("itemLoader", new ComboLoader());
        ComboBox<String>combo = loader.load();
        grid.add(combo, 0, 0);

        Scene scene = new Scene(group, 450, 175);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Title: Javafx: Reusable collections using FXML

Body:
I'd like to bind a single collection to multiple ChoiceBox's in FXML.
However the only way I know how is using:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
    <items>
        <FXCollections fx:id="test" fx:factory="observableArrayList">
            <String fx:value="1" />
            <String fx:value="2" />
            <String fx:value="3" />
            <String fx:value="4" />
            <String fx:value="5" />
            <String fx:value="6" />
            <String fx:value="7" />
            <String fx:value="8" />
            <String fx:value="9" />
        </FXCollections>
    </items>
</ChoiceBox>

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

Body:
It can be in the controller or any other class like (the example is for a combobox. The same can be applied to a choicebox):

combo.fxml

<?import javafx.scene.control.ComboBox?>
<ComboBox  fx:id="combo1" items="${itemLoader.items}"  prefWidth="150.0"
xmlns:fx="http://javafx.com/fxml/1" >
</ComboBox>

Loader class

public class ComboLoader {

    private ObservableList<String> obsStrings;

    public ComboLoader() {

        obsStrings = FXCollections.observableArrayList(createStrings());
    }

    private List<String> createStrings() {
            return IntStream.rangeClosed(0, 5)
                    .mapToObj(i -> "String "+i)
                    .map(String::new)
                    .collect(Collectors.toList());
    }
    //name of this method corresponds to itemLoader.items in xml.
    //if xml name was itemLoader.a this method should have been
    //getA(). A bit odd
    public ObservableList<String> getItems(){

        return obsStrings;
    }
}

test it with:

public class ComboTest extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        primaryStage.setTitle("Populate combo from custom builder");

        Group group = new Group();
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(25, 25, 25, 25));
        group.getChildren().add(grid);

        FXMLLoader loader = new FXMLLoader(getClass().getResource("combo.fxml"));
        loader.getNamespace().put("itemLoader", new ComboLoader());
        ComboBox<String>combo = loader.load();
        grid.add(combo, 0, 0);

        Scene scene = new Scene(group, 450, 175);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

ContentLicense: CC BY-SA 4.0


问:
CSS: wrapping around text inside a drawn circle using CSS
I am using this CSS code to draw circles:

```<code>circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 100px;
    margin:5px;
}
</code>```

Using this in html I can draw 3 circles side-by-side with text inside them:

```<code> <circle>Text1</circle>
 <circle>Text2</circle>
 <circle>Text3</circle>
</code>```

which looks like this:

Now if I want to add more text in side the middle circle this is what happens:

```<code><circle>Text1</circle>
<circle>Text2 and more</circle>
<circle>Text3</circle>
</code>```

whoever, I want 'Text2 and more` to stay inside the second circle and just wraps around. How can I achieve that?

NOTE: I don't want to use display: table-cell as it doesn't work nicely on responsive sites and does not let circles wrap around and stay on top of each other if the view page is very narrow.

答:
Right now, the line-height causes the wierd offset. You could use flexbox to center the text within the circle.

```<code><div class="circles">
    <circle>Text1</circle>
    <circle>Text2 has more text</circle>
    <circle>Text3</circle>
</div>
</code>```

```<code>.circles{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
circle {
    display: flex;
    margin:5px;
    justify-content: center;
    align-items: center;
    background: #f00;
    width: 100px;
    height: 100px;
    flex-shrink: 0;
    border-radius: 50%;
    text-align: center;
}
</code>```

Body:
I am using this CSS code to draw circles:

circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 100px;
    margin:5px;
}

Using this in html I can draw 3 circles side-by-side with text inside them:

 <circle>Text1</circle>
 <circle>Text2</circle>
 <circle>Text3</circle>

which looks like this:

Now if I want to add more text in side the middle circle this is what happens:

<circle>Text1</circle>
<circle>Text2 and more</circle>
<circle>Text3</circle>

whoever, I want 'Text2 and more` to stay inside the second circle and just wraps around. How can I achieve that?

NOTE: I don't want to use display: table-cell as it doesn't work nicely on responsive sites and does not let circles wrap around and stay on top of each other if the view page is very narrow.

Body:
Right now, the line-height causes the wierd offset. You could use flexbox to center the text within the circle.

<div class="circles">
    <circle>Text1</circle>
    <circle>Text2 has more text</circle>
    <circle>Text3</circle>
</div>

.circles{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
circle {
    display: flex;
    margin:5px;
    justify-content: center;
    align-items: center;
    background: #f00;
    width: 100px;
    height: 100px;
    flex-shrink: 0;
    border-radius: 50%;
    text-align: center;
}


问:
Libgdx : Exported desktop jar file link to external path instead jar root
I'm trying to deploy my libgdx app into a jar desktop file. I use Intellij so i builded the desktop module, then executed  ./gradlew desktop:dist to produce the jar and everything gone well ! I use an Asset manager to load my assets. Now when i execute the jar, the asset manager try to get the assets in the directory of the jar and not directly in the jar file.

My asset manager :

```<code>package com.com8.game.Utils;

import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.SkinLoader;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;

public class Assets {

public AssetManager manager = new AssetManager();

public static final AssetDescriptor<Texture> logo =
        new AssetDescriptor<Texture>("logo.png", Texture.class);

public static final AssetDescriptor<Texture> tableBack =
        new AssetDescriptor<Texture>("back.png", Texture.class);

public static final AssetDescriptor<Texture> frontBackground =
        new AssetDescriptor<Texture>("frontBackground.png", Texture.class);

public static final AssetDescriptor<Texture> backBackground =
        new AssetDescriptor<Texture>("backBackground.png", Texture.class);

public static final AssetDescriptor<TextureAtlas> uiAtlas =
        new AssetDescriptor<TextureAtlas>("UI/uiskin.atlas", TextureAtlas.class);

public static final AssetDescriptor<Skin> uiSkin =
        new AssetDescriptor<Skin>("UI/uiskin.json", Skin.class,
                new SkinLoader.SkinParameter("UI/uiskin.atlas"));

public static final AssetDescriptor<TextureAtlas> gameAtlas =
        new AssetDescriptor<TextureAtlas>("Atlas/gameImages.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> flamesAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/flamesAnimation.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> hitAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/hitAnimation.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> shipExplosionAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/shipExplosionAnimation.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> dustAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/dustAnimation.atlas", TextureAtlas.class);

public void load()
{
    manager.load(logo);
    manager.load(tableBack);
    manager.load(frontBackground);
    manager.load(backBackground);
    manager.load(uiAtlas);
    manager.load(uiSkin);
    manager.load(gameAtlas);
    manager.load(flamesAnimation);
    manager.load(hitAnimation);
    manager.load(shipExplosionAnimation);
    manager.load(dustAnimation);
}

public void dispose() {
    manager.dispose();
}
}
</code>```

My build.gradle of the desktopLauncher :
    apply plugin: "java"

```<code>sourceCompatibility = 1.6
sourceSets.main.java.srcDirs = [ "src/" ]

project.ext.mainClassName = "com.com8.game.desktop.DesktopLauncher"
project.ext.assetsDir = new File("../core/assets");

task run(dependsOn: classes, type: JavaExec) {
    main = project.mainClassName
    classpath = sourceSets.main.runtimeClasspath
    standardInput = System.in
    workingDir = project.assetsDir
    ignoreExitValue = true
}

task debug(dependsOn: classes, type: JavaExec) {
    main = project.mainClassName
    classpath = sourceSets.main.runtimeClasspath
    standardInput = System.in
    workingDir = project.assetsDir
    ignoreExitValue = true
    debug = true
}

task dist(type: Jar) {
    from files(sourceSets.main.output.classesDir)
    from files(sourceSets.main.output.resourcesDir)
    from {configurations.compile.collect {zipTree(it)}}
    from files(project.assetsDir);

    manifest {
        attributes 'Main-Class': project.mainClassName
    }
}

dist.dependsOn classes

eclipse {
    project {
        name = appName + "-desktop"
        linkedResource name: 'assets', type: '2', location: 'PARENT-1-PROJECT_LOC/core/assets'
    }
}

task afterEclipseImport(description: "Post processing after project
generation", group: "IDE") {
  doLast {
    def classpath = new XmlParser().parse(file(".classpath"))
    new Node(classpath, "classpathentry", [ kind: 'src', path: 'assets' ]);
    def writer = new FileWriter(file(".classpath"))
    def printer = new XmlNodePrinter(new PrintWriter(writer))
    printer.setPreserveWhitespace(true)
    printer.print(classpath)
  }
}
</code>```

Can someone please help me ? :) Thanks

EDIT :
I just added a "/" in front of each path name and it seems to be better !
now i have this, the file logo.png is in the root of the jar file.

And here is how i use Assets class :

```<code>// Assets
private AssetManager manager;
private Stage stage;
private Skin skin;

// UI
private TextField userIDRegistered;
private TextField userPwd;
private TextField userIDGuest;
private Label authentificationResponse;
private Label socketConnectedMessage;

// Socket
private Socket socket;

public ConnexionScreen(Com8 game) {
    this.game = game;
    this.socket = game.getSocket();
    this.manager = game.assets.manager;

    skin = game.skin;

    stage = game.stage;
    stage.clear();

    configSocketEvents();
}

@Override
public void show() {
    //Create Table
    Table mainTable = new Table();

    //Set table position properties
    mainTable.align(Align.center|Align.center);
    mainTable.setFillParent(true);

    //Create image
    Texture logoTexture = manager.get("/logo.png", Texture.class);
    Image logoImage = new Image(logoTexture);
</code>```

答:
I find the problem, thanks to @Abhishek Aryan !
My Assets Descriptors was static, when dealing with assets Manager it seems that nothing can be static. I change my Assets class like this :

```<code>public class Assets {

public AssetManager manager;

public AssetDescriptor<Texture> logo;

public AssetDescriptor<Texture> tableBack;
public AssetDescriptor<Texture> frontBackground;

public AssetDescriptor<Texture> backBackground;

public AssetDescriptor<TextureAtlas> uiAtlas;

public AssetDescriptor<Skin> uiSkin;

public AssetDescriptor<TextureAtlas> gameAtlas;

public AssetDescriptor<TextureAtlas> flamesAnimation;

public AssetDescriptor<TextureAtlas> hitAnimation;

public AssetDescriptor<TextureAtlas> shipExplosionAnimation;

public AssetDescriptor<TextureAtlas> dustAnimation;

public Assets(){
    manager = new AssetManager();
    logo = new AssetDescriptor<Texture>("logo.png", Texture.class);
    tableBack = new AssetDescriptor<Texture>("back.png", Texture.class);
    frontBackground = new AssetDescriptor<Texture>("frontBackground.png", Texture.class);
    backBackground = new AssetDescriptor<Texture>("backBackground.png", Texture.class);
    uiAtlas = new AssetDescriptor<TextureAtlas>("UI/uiskin.atlas", TextureAtlas.class);
    uiSkin = new AssetDescriptor<Skin>("UI/uiskin.json", Skin.class,
            new SkinLoader.SkinParameter("UI/uiskin.atlas"));
    gameAtlas = new AssetDescriptor<TextureAtlas>("Atlas/gameImages.atlas", TextureAtlas.class);
    flamesAnimation = new AssetDescriptor<TextureAtlas>("Atlas/flamesAnimation.atlas", TextureAtlas.class);
    hitAnimation = new AssetDescriptor<TextureAtlas>("Atlas/hitAnimation.atlas", TextureAtlas.class);
    shipExplosionAnimation = new AssetDescriptor<TextureAtlas>("Atlas/shipExplosionAnimation.atlas", TextureAtlas.class);
    dustAnimation = new AssetDescriptor<TextureAtlas>("Atlas/dustAnimation.atlas", TextureAtlas.class);
}

public void load()
{
    manager.load(logo);
    manager.load(tableBack);
    manager.load(frontBackground);
    manager.load(backBackground);
    manager.load(uiAtlas);
    manager.load(uiSkin);
    manager.load(gameAtlas);
    manager.load(flamesAnimation);
    manager.load(hitAnimation);
    manager.load(shipExplosionAnimation);
    manager.load(dustAnimation);
}

public void dispose() {
    manager.dispose();
}
}
</code>```

Everything is working well now :)

Body:
I'm trying to deploy my libgdx app into a jar desktop file. I use Intellij so i builded the desktop module, then executed  ./gradlew desktop:dist to produce the jar and everything gone well ! I use an Asset manager to load my assets. Now when i execute the jar, the asset manager try to get the assets in the directory of the jar and not directly in the jar file.

My asset manager :

package com.com8.game.Utils;

import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.SkinLoader;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;

public class Assets {

public AssetManager manager = new AssetManager();

public static final AssetDescriptor<Texture> logo =
        new AssetDescriptor<Texture>("logo.png", Texture.class);

public static final AssetDescriptor<Texture> tableBack =
        new AssetDescriptor<Texture>("back.png", Texture.class);

public static final AssetDescriptor<Texture> frontBackground =
        new AssetDescriptor<Texture>("frontBackground.png", Texture.class);

public static final AssetDescriptor<Texture> backBackground =
        new AssetDescriptor<Texture>("backBackground.png", Texture.class);

public static final AssetDescriptor<TextureAtlas> uiAtlas =
        new AssetDescriptor<TextureAtlas>("UI/uiskin.atlas", TextureAtlas.class);

public static final AssetDescriptor<Skin> uiSkin =
        new AssetDescriptor<Skin>("UI/uiskin.json", Skin.class,
                new SkinLoader.SkinParameter("UI/uiskin.atlas"));

public static final AssetDescriptor<TextureAtlas> gameAtlas =
        new AssetDescriptor<TextureAtlas>("Atlas/gameImages.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> flamesAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/flamesAnimation.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> hitAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/hitAnimation.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> shipExplosionAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/shipExplosionAnimation.atlas", TextureAtlas.class);

public static final AssetDescriptor<TextureAtlas> dustAnimation =
        new AssetDescriptor<TextureAtlas>("Atlas/dustAnimation.atlas", TextureAtlas.class);

public void load()
{
    manager.load(logo);
    manager.load(tableBack);
    manager.load(frontBackground);
    manager.load(backBackground);
    manager.load(uiAtlas);
    manager.load(uiSkin);
    manager.load(gameAtlas);
    manager.load(flamesAnimation);
    manager.load(hitAnimation);
    manager.load(shipExplosionAnimation);
    manager.load(dustAnimation);
}

public void dispose() {
    manager.dispose();
}
}

My build.gradle of the desktopLauncher :
    apply plugin: "java"

sourceCompatibility = 1.6
sourceSets.main.java.srcDirs = [ "src/" ]

project.ext.mainClassName = "com.com8.game.desktop.DesktopLauncher"
project.ext.assetsDir = new File("../core/assets");

task run(dependsOn: classes, type: JavaExec) {
    main = project.mainClassName
    classpath = sourceSets.main.runtimeClasspath
    standardInput = System.in
    workingDir = project.assetsDir
    ignoreExitValue = true
}

task debug(dependsOn: classes, type: JavaExec) {
    main = project.mainClassName
    classpath = sourceSets.main.runtimeClasspath
    standardInput = System.in
    workingDir = project.assetsDir
    ignoreExitValue = true
    debug = true
}

task dist(type: Jar) {
    from files(sourceSets.main.output.classesDir)
    from files(sourceSets.main.output.resourcesDir)
    from {configurations.compile.collect {zipTree(it)}}
    from files(project.assetsDir);

    manifest {
        attributes 'Main-Class': project.mainClassName
    }
}

dist.dependsOn classes

eclipse {
    project {
        name = appName + "-desktop"
        linkedResource name: 'assets', type: '2', location: 'PARENT-1-PROJECT_LOC/core/assets'
    }
}

task afterEclipseImport(description: "Post processing after project
generation", group: "IDE") {
  doLast {
    def classpath = new XmlParser().parse(file(".classpath"))
    new Node(classpath, "classpathentry", [ kind: 'src', path: 'assets' ]);
    def writer = new FileWriter(file(".classpath"))
    def printer = new XmlNodePrinter(new PrintWriter(writer))
    printer.setPreserveWhitespace(true)
    printer.print(classpath)
  }
}

Can someone please help me ? :) Thanks

EDIT :
I just added a "/" in front of each path name and it seems to be better !
now i have this, the file logo.png is in the root of the jar file.

And here is how i use Assets class :

// Assets
private AssetManager manager;
private Stage stage;
private Skin skin;

// UI
private TextField userIDRegistered;
private TextField userPwd;
private TextField userIDGuest;
private Label authentificationResponse;
private Label socketConnectedMessage;

// Socket
private Socket socket;

public ConnexionScreen(Com8 game) {
    this.game = game;
    this.socket = game.getSocket();
    this.manager = game.assets.manager;

    skin = game.skin;

    stage = game.stage;
    stage.clear();

    configSocketEvents();
}

@Override
public void show() {
    //Create Table
    Table mainTable = new Table();

    //Set table position properties
    mainTable.align(Align.center|Align.center);
    mainTable.setFillParent(true);

    //Create image
    Texture logoTexture = manager.get("/logo.png", Texture.class);
    Image logoImage = new Image(logoTexture);

Body:
I find the problem, thanks to @Abhishek Aryan !
My Assets Descriptors was static, when dealing with assets Manager it seems that nothing can be static. I change my Assets class like this :

public class Assets {

public AssetManager manager;

public AssetDescriptor<Texture> logo;

public AssetDescriptor<Texture> tableBack;
public AssetDescriptor<Texture> frontBackground;

public AssetDescriptor<Texture> backBackground;

public AssetDescriptor<TextureAtlas> uiAtlas;

public AssetDescriptor<Skin> uiSkin;

public AssetDescriptor<TextureAtlas> gameAtlas;

public AssetDescriptor<TextureAtlas> flamesAnimation;

public AssetDescriptor<TextureAtlas> hitAnimation;

public AssetDescriptor<TextureAtlas> shipExplosionAnimation;

public AssetDescriptor<TextureAtlas> dustAnimation;

public Assets(){
    manager = new AssetManager();
    logo = new AssetDescriptor<Texture>("logo.png", Texture.class);
    tableBack = new AssetDescriptor<Texture>("back.png", Texture.class);
    frontBackground = new AssetDescriptor<Texture>("frontBackground.png", Texture.class);
    backBackground = new AssetDescriptor<Texture>("backBackground.png", Texture.class);
    uiAtlas = new AssetDescriptor<TextureAtlas>("UI/uiskin.atlas", TextureAtlas.class);
    uiSkin = new AssetDescriptor<Skin>("UI/uiskin.json", Skin.class,
            new SkinLoader.SkinParameter("UI/uiskin.atlas"));
    gameAtlas = new AssetDescriptor<TextureAtlas>("Atlas/gameImages.atlas", TextureAtlas.class);
    flamesAnimation = new AssetDescriptor<TextureAtlas>("Atlas/flamesAnimation.atlas", TextureAtlas.class);
    hitAnimation = new AssetDescriptor<TextureAtlas>("Atlas/hitAnimation.atlas", TextureAtlas.class);
    shipExplosionAnimation = new AssetDescriptor<TextureAtlas>("Atlas/shipExplosionAnimation.atlas", TextureAtlas.class);
    dustAnimation = new AssetDescriptor<TextureAtlas>("Atlas/dustAnimation.atlas", TextureAtlas.class);
}

public void load()
{
    manager.load(logo);
    manager.load(tableBack);
    manager.load(frontBackground);
    manager.load(backBackground);
    manager.load(uiAtlas);
    manager.load(uiSkin);
    manager.load(gameAtlas);
    manager.load(flamesAnimation);
    manager.load(hitAnimation);
    manager.load(shipExplosionAnimation);
    manager.load(dustAnimation);
}

public void dispose() {
    manager.dispose();
}
}

Everything is working well now :)


问:
How to run service repeatedly even the app is closed so that it can notify the user about something through notification?
I'm making an app which shows us that which subject is being taught in classroom. I want to make a service which will run forever in background so that it can notify the user through notification even the app is closed. I tried with started activity but the service was killed after app was closed. </p>

答:
You need to start a sticky service. Here is an example. What you need is the return START_STICKY;.

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}
</code>```

This service will restart when the app is closed. Meaning it will run forever.

Body:
You need to start a sticky service. Here is an example. What you need is the return START_STICKY;.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}

This service will restart when the app is closed. Meaning it will run forever.


问:
Longest sequence of consecutive letters
Suppose I have a string of lower case letters, e.g.

```<code>'ablccmdnneofffpg'
</code>```

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

```<code>'abcdefg'
</code>```

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

```<code>longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1
</code>```

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

答:
You could keep track of all subsequences of consecutive characters as seen in the string using a dictionary, and then take the one with the largest length.

Each subsequence is keyed by the next candidate in the alphabet so that once the anticipated candidate is reached in the string, it is used to update the value of the corresponding subsequence in the dictionary and added as a new dictionary value keyed by the next alphabet:

```<code>def longest_sequence(s):
    d = {}
    for x in s:
       if x in d:
           d[chr(ord(x)+1)] = d[x] + x
       else:
           d[chr(ord(x)+1)] = x
    return max(d.values(), key=len)

print(longest_sequence('ablccmdnneofffpg'))
# abcdefg
print(longest_sequence('ba'))
# b
print(longest_sequence('sblccmtdnneofffpgtuyvgmmwwwtxjyuuz'))
# stuvwxyz
</code>```

Title: Longest sequence of consecutive letters

Body:
Suppose I have a string of lower case letters, e.g.

'ablccmdnneofffpg'

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

'abcdefg'

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

Body:
You could keep track of all subsequences of consecutive characters as seen in the string using a dictionary, and then take the one with the largest length.

Each subsequence is keyed by the next candidate in the alphabet so that once the anticipated candidate is reached in the string, it is used to update the value of the corresponding subsequence in the dictionary and added as a new dictionary value keyed by the next alphabet:

def longest_sequence(s):
    d = {}
    for x in s:
       if x in d:
           d[chr(ord(x)+1)] = d[x] + x
       else:
           d[chr(ord(x)+1)] = x
    return max(d.values(), key=len)

print(longest_sequence('ablccmdnneofffpg'))
# abcdefg
print(longest_sequence('ba'))
# b
print(longest_sequence('sblccmtdnneofffpgtuyvgmmwwwtxjyuuz'))
# stuvwxyz


问:
How to multiply each key by another key in dictionaries?
I'm doing course in codeacademy and i'm on lession Something of Value
In my final task i have to For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total.

My code:

```<code>for cena in prices:
    total = prices[cena]*stock[cena]
print total
</code>```

It's printing 0.

I also tried this:

```<code>for cena in prices:
    for ilosc in stock:
        total = prices[cena]*stock[ilosc]
print total
</code>```

It's also returning 0.

EDIT: Whole code:

```<code>prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
total = 0
for cena in prices:
    for ilosc in stock:
        total = prices[cena]*stock[ilosc]
print total
</code>```

答:
This worked for me</p>

```<code>prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]

total = 0

for key in prices:
    price_of_stock =  prices[key] * stock[key]
    print price_of_stock
    total = total + price_of_stock

print total
</code>```

Body:
I'm doing course in codeacademy and i'm on lession Something of Value
In my final task i have to For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total.

My code:

for cena in prices:
    total = prices[cena]*stock[cena]
print total

It's printing 0.

I also tried this:

for cena in prices:
    for ilosc in stock:
        total = prices[cena]*stock[ilosc]
print total

It's also returning 0.

EDIT: Whole code:

prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
total = 0
for cena in prices:
    for ilosc in stock:
        total = prices[cena]*stock[ilosc]
print total

Body:
This worked for me

prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]

total = 0

for key in prices:
    price_of_stock =  prices[key] * stock[key]
    print price_of_stock
    total = total + price_of_stock

print total


问:
How to implement std::when_any without polling?
Consider http://en.cppreference.com/w/cpp/experimental/when_any. The following is just a naive and simplified implementation:

```<code>#include <future>

template<typename Iterator>
auto when_any(Iterator first, Iterator last)
{
    while (true)
    {
        for (auto pos = first; pos != last; ++pos)
        {
            if (pos->is_ready())
            {
                return std::move(*pos);
            }
        }
    }
}
</code>```

I am not satisfied because it is a busy polling in an infinite loop.

Is there a way to avoid busy polling?

答:
Not really, futures without continuations are of very limited usefulness.

If you are forced to do this and to use std::future, I suggest smarter polling via .wait_for() with increasing timeouts.

Body:
Consider http://en.cppreference.com/w/cpp/experimental/when_any. The following is just a naive and simplified implementation:

#include <future>

template<typename Iterator>
auto when_any(Iterator first, Iterator last)
{
    while (true)
    {
        for (auto pos = first; pos != last; ++pos)
        {
            if (pos->is_ready())
            {
                return std::move(*pos);
            }
        }
    }
}

I am not satisfied because it is a busy polling in an infinite loop.

Is there a way to avoid busy polling?


问:
fatal when unwrapping UIImage from ImagePicker to Firebase.Storage
Trying to create an image stored in Firebase from UIImagePicker, throws a fatal upon receiving as ImageData is nil. How can the image picker return nil? </p>

```<code>func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [String : Any]) {
    picker.dismiss(animated: true, completion:nil)
    guard let uid = Auth.auth().currentUser?.uid else { return }

        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
        let imageData = UIImageJPEGRepresentation(image, 0.8)
        let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"
        self.storageRef.child(imagePath)
            .putData(imageData!, metadata: metadata) { [weak self] (metadata, error) in
                if let error = error {
                    print("Error uploading: \(error)")
                    return
                }

    }
</code>```

答:
Could you remove this line,

```<code>    picker.dismiss(animated: true, completion:nil)
</code>```

and put it right at the end of your imagePickerController method instead of at the beginning. It seems you are dismissing the picker too early and the image becomes nil as a result.

Body:
Trying to create an image stored in Firebase from UIImagePicker, throws a fatal upon receiving as ImageData is nil. How can the image picker return nil?

func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [String : Any]) {
    picker.dismiss(animated: true, completion:nil)
    guard let uid = Auth.auth().currentUser?.uid else { return }

        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
        let imageData = UIImageJPEGRepresentation(image, 0.8)
        let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
        let metadata = StorageMetadata()
        metadata.contentType = "image/jpeg"
        self.storageRef.child(imagePath)
            .putData(imageData!, metadata: metadata) { [weak self] (metadata, error) in
                if let error = error {
                    print("Error uploading: \(error)")
                    return
                }

    }

Body:
Could you remove this line,

    picker.dismiss(animated: true, completion:nil)

and put it right at the end of your imagePickerController method instead of at the beginning. It seems you are dismissing the picker too early and the image becomes nil as a result.


问:
How do I rewrite URLs without access to IIS using C# and ASP.NET?
I am looking for a solution to rewrite URLs that have query strings so that the query string creates permanent link. For example: the query string ?u=test would become http://www.website.com/profile/test

I am new to URL rewriting, but am open to any suggestions you may have. I don't have access to IIS as I'm using shared virtual hosting.

答:
You cant have extension-less URL without configuring it in the IIS as ISAPI wouldn't know how to handle that request.

Scott Gu has an excellent post with various approaches to URL rewrite.

ContentLicense: CC BY-SA 2.5


问:
PHP simple_html_dom get element by contents
I'm trying to use simple_html_dom to get an element by it's contents. The reason for this is that I'm scraping a page that has contents like:

```<code><dl>
    <dt>Variable: </dt>
    <dd>Value</dd>
    <dt>Another variable> </dt>
    <dd>Value</dd>
</dl>
</code>```

Now I want to parse certain variables and their values, so I need to do a

```<code>$html->find(dt[contains=Variable: ])
</code>```

Or something like that, if you know what I mean. Is this possible?

答:
Thanks to @Kazz, I got the idea to just loop through all dt and put them all in an associative array together with the values from the dds. Thanks!

```<code>foreach($html->find('dt') as $prop){
    $array[$prop->plaintext]= $prop->next_sibling()->plaintext;
}
</code>```

Body:
I'm trying to use simple_html_dom to get an element by it's contents. The reason for this is that I'm scraping a page that has contents like:

Variable:

Value

Another variable>

Value

Now I want to parse certain variables and their values, so I need to do a

$html->find(dt[contains=Variable: ])

Or something like that, if you know what I mean. Is this possible?

Body:
Thanks to @Kazz, I got the idea to just loop through all dt and put them all in an associative array together with the values from the dds. Thanks!

foreach($html->find('dt') as $prop){
    $array[$prop->plaintext]= $prop->next_sibling()->plaintext;
}


问:
Is http_x_forwarded_for safe for check IP
is http_x_forwarded_for safe?

In requests, is it able to modify the http_x_forwarded_for with fake ip?

Can hackers do that?

答:
Due to the way IP networks work, there is no way to tell the actual IP address of a client connecting to your server. The question even doesn't make sense. If NAT is used on the network, which IP would you want to see as client IP, the internal (local) one on the NATed network, or the first public IP? What would you gain from the latter, when whole internet provider companies work with client networks behind a nat (although this is getting less common)?

You need to acknowledge that in an IP network, traffic passes through many nodes, some of which may change the apparent IP address of a request. These include NAT servers and proxies of different sorts, and you have no way to tell what happened to a packet before reaching your server.

Also in HTTP, any request header can be forged. This includes about any variable that starts with SERVER_ in your favourite language. These cannot be trusted, a user can send whatever he wants.

The only exception is the actual apparent client IP, which is much harder to forge, but only gives you the last hop (the last proxy, or the last nat server).

Also most of the times if you need to know the client IP that precisely, something elae is wrong on the logic. You have to accept for example that a client IP is in no way an identifier of a user (a person).


问:
How can I set up a quick "dummy" server on my machine? (Phonegap accessible)
I'm trying to create a simple PhoneGap application that can request some data from a server. I'm very new to server-side code and my goal is merely to assess the viability of using phonegap with an external server.

My application is already phonegap-ready (written using Javascript, and i'm using PhoneGap Build and have an AVD to test the application), but the only persistence methods I can find deal with local storage. So to break down my issue into more clear components:

Is there a "quick and dirty" way to set up a simple server that may be accessible from my phonegap application?

What is might be the preferred request method? I've been looking into Ajax/REST/jQuery, but if i'm honest, i'm struggling to understand where these types of requests 'live' in my application (or on the server side?)

I am using eclipse keplar and would prefer approaches that avoid using the command prompt.

答:
You can try this code -

```<code>var express = require("express");

var app = express();

app.get("/", function(req, res){
    res.send("Get methods");

});

app.use(express.static("public")); // put the static data folder name here which contain your UI code.

var server = app.listen(8081, function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log(host +" : "+port);

});
</code>```

follow the instruction given in https://jsrach.wordpress.com/

Body:
You can try this code -

var express = require("express");

var app = express();

app.get("/", function(req, res){
    res.send("Get methods");

});

app.use(express.static("public")); // put the static data folder name here which contain your UI code.

var server = app.listen(8081, function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log(host +" : "+port);

});

follow the instruction given in https://jsrach.wordpress.com/


问:
How to add folder of property files in eclipse
I shifted my project from tomcat to eclipse. All files are working fine but the folder containing property files are not working.

What I did so far:

Added folder in project -> build

created a source folder in project/src root and moved all

Set the classpath environment variables

Changed path with //, first folder without / etc.

but nothing worked for me. Here is screen shot:

Please advise where I am making mistake?
My OS is windows 8 but I have to deploy on CentOS
IDE: eclipse neon 3.0

thanks in anticipation

答:
You can try with this:

```<code>ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("/lang/global/settings.properties");
</code>```

If this doesn't works, you can check it out these links: mkyong, crunchify

Body:
You can try with this:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("/lang/global/settings.properties");

If this doesn't works, you can check it out these links: mkyong, crunchify


问:
How to compare two hash sets in java?
How can I compare two hash sets in java ? My first hash sets looks like below.

```<code>static Set<String> nounPhrases = new HashSet<>();
</code>```

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

```<code>static Set<String> nounPhrases2 = new HashSet<>();
</code>```

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

答:
So you mean like this?

```<code>public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    // Checking for every element in first set
    for (final String element : nounPhrases) {

        // if second set has the current element
        if (nounPhrases2.contains(element)) {
            System.out.println("They have " + element);
        }
    }
}
</code>```

My output:

```<code>They have java
They have book
</code>```

Edit:
Based on your comment, if i understand correctly, if you want to get the common elements in both sets, just store the values and return them:

```<code>public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    System.out.println(getCommon(nounPhrases, nounPhrases2));
}

public final static Set<String> getCommon(Set<String> setA, Set<String> setB) {

    final Set<String> result = new HashSet<>();
    for (final String element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}
</code>```

You could use generics to make the method work for other elements than strings:

```<code>public final static <T> Set<T> getCommon(Set<T> setA, Set<T> setB) {

    final Set<T> result = new HashSet<>();
    for (final T element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}
</code>```

If performance is important, you should check sizes first and only iterate over the elements of the smaller set. If you have one set with 1 elements, and one set with 100, starting with the smaller will leve you with one iteration whereas starting with the bigger will leave you with 100 checks where only 1 could have been in both sets.

Title: How to compare two hash sets in java?

Body:
How can I compare two hash sets in java ? My first hash sets looks like below.

static Set<String> nounPhrases = new HashSet<>();

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

static Set<String> nounPhrases2 = new HashSet<>();

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

Body:
So you mean like this?

public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    // Checking for every element in first set
    for (final String element : nounPhrases) {

        // if second set has the current element
        if (nounPhrases2.contains(element)) {
            System.out.println("They have " + element);
        }
    }
}

My output:

They have java
They have book

Edit:
Based on your comment, if i understand correctly, if you want to get the common elements in both sets, just store the values and return them:

public static void main(String[] args) {

    final Set<String> nounPhrases = new HashSet<>();
    nounPhrases.add("java");
    nounPhrases.add("jsp");
    nounPhrases.add("book");

    final Set<String> nounPhrases2 = new HashSet<>();
    nounPhrases2.add("web");
    nounPhrases2.add("php");
    nounPhrases2.add("java");
    nounPhrases2.add("book");

    System.out.println(getCommon(nounPhrases, nounPhrases2));
}

public final static Set<String> getCommon(Set<String> setA, Set<String> setB) {

    final Set<String> result = new HashSet<>();
    for (final String element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}

You could use generics to make the method work for other elements than strings:

public final static <T> Set<T> getCommon(Set<T> setA, Set<T> setB) {

    final Set<T> result = new HashSet<>();
    for (final T element : setA) {
        if (setB.contains(element)) {
            result.add(element);
        }
    }
    return result;
}

If performance is important, you should check sizes first and only iterate over the elements of the smaller set. If you have one set with 1 elements, and one set with 100, starting with the smaller will leve you with one iteration whereas starting with the bigger will leave you with 100 checks where only 1 could have been in both sets.


问:
Default selected value in mvc5 dropdown
I have a linq query that is binded to a @Html.dropdownfor. If I assign a value to the user's account and leave the page. When I go back to the page, It's default value or preselected value is "Choose a schedule" even when I have a value assigned to it from before. I need it to preselect to the value already stored in the database. It was preselecting correctly with this

```<code> ScheduleBuilderList = _context.ScheduleBuilder.ToList()
</code>```

until I binded LINQ query.
How can I get the database value to the be default value selected in dropdown without messing up the LINQ?

```<code>   @Html.DropDownListFor(m => m.ApplicationUser.ScheduleSum, new SelectList(Model.ScheduleBuilderList, "ScheduleSummary", "ScheduleSummary"), "Choose a schedule", new {@class = "form-control", id="dropdown"})
</code>```

LINQ

```<code>ScheduleBuilderList = _context.ScheduleBuilder.Where(s => s.IsScheduleAssigned == false).ToList()
</code>```

Full Actionresult code with recommended change below

```<code> public ActionResult  EmployeeDetails(string id, ScheduleBuilder scheduleBuilder, ApplicationUser applicationUser)
{
    var user = _context.Users.SingleOrDefault(e => e.Id == id);

    if (user == null)
    {
        return HttpNotFound();
    }

    var viewModel = new TierViewModel()
    {
        ApplicationUser = user,
        TierLevel = _context.Tier.ToList(),
        ScheduleBuilderList = _context.ScheduleBuilder
            .Where(s => s.IsScheduleAssigned == false)
            .Select(item => new SelectListItem
            {
                Text = item.ScheduleSummary,
                Value = item.ScheduleSummary,
                Selected = item.ScheduleSummary == user.ScheduleSum
            })

    };

    var user1 = _context.Users.ToList();

    var schedule1 = _context.ScheduleBuilder.ToList();

    return View("EmployeeDetails", viewModel);
}
</code>```

答:
You could try something like this:

```<code>var ScheduleBuilderList = _context.ScheduleBuilder
                                  .Where(s => s.IsScheduleAssigned == false)
                                  .Select(item => new SelectListItem
                                  {
                                      Text = item.ScheduleSummary,
                                      Value = item.ScheduleSummary,
                                      Selected = item.ScheduleSummary == "usersvalue"
                                  });
</code>```

Where the literal "usersvalue" should be replaced the value of ApplicationUser.ScheduleSum for which you are interested in. Then you should change a bit also your View, like below:

```<code>@Html.DropDownListFor(m => m.ApplicationUser.ScheduleSum,
                      Model.ScheduleBuilderList,
                      "Choose a schedule",
                      new {@class = "form-control", id="dropdown"})
</code>```

and your Model should replace the type of ScheduleBuilderList with the following type:

```<code>IEnumerable<SelectListItem>
</code>```

Title: Default selected value in mvc5 dropdown

Body:
I have a linq query that is binded to a @Html.dropdownfor. If I assign a value to the user's account and leave the page. When I go back to the page, It's default value or preselected value is "Choose a schedule" even when I have a value assigned to it from before. I need it to preselect to the value already stored in the database. It was preselecting correctly with this

 ScheduleBuilderList = _context.ScheduleBuilder.ToList()

until I binded LINQ query.
How can I get the database value to the be default value selected in dropdown without messing up the LINQ?

   @Html.DropDownListFor(m => m.ApplicationUser.ScheduleSum, new SelectList(Model.ScheduleBuilderList, "ScheduleSummary", "ScheduleSummary"), "Choose a schedule", new {@class = "form-control", id="dropdown"})

LINQ

ScheduleBuilderList = _context.ScheduleBuilder.Where(s => s.IsScheduleAssigned == false).ToList()

Full Actionresult code with recommended change below

 public ActionResult  EmployeeDetails(string id, ScheduleBuilder scheduleBuilder, ApplicationUser applicationUser)
{
    var user = _context.Users.SingleOrDefault(e => e.Id == id);

    if (user == null)
    {
        return HttpNotFound();
    }

    var viewModel = new TierViewModel()
    {
        ApplicationUser = user,
        TierLevel = _context.Tier.ToList(),
        ScheduleBuilderList = _context.ScheduleBuilder
            .Where(s => s.IsScheduleAssigned == false)
            .Select(item => new SelectListItem
            {
                Text = item.ScheduleSummary,
                Value = item.ScheduleSummary,
                Selected = item.ScheduleSummary == user.ScheduleSum
            })

    };

    var user1 = _context.Users.ToList();

    var schedule1 = _context.ScheduleBuilder.ToList();

    return View("EmployeeDetails", viewModel);
}

Body:
You could try something like this:

var ScheduleBuilderList = _context.ScheduleBuilder
                                  .Where(s => s.IsScheduleAssigned == false)
                                  .Select(item => new SelectListItem
                                  {
                                      Text = item.ScheduleSummary,
                                      Value = item.ScheduleSummary,
                                      Selected = item.ScheduleSummary == "usersvalue"
                                  });

Where the literal "usersvalue" should be replaced the value of ApplicationUser.ScheduleSum for which you are interested in. Then you should change a bit also your View, like below:

@Html.DropDownListFor(m => m.ApplicationUser.ScheduleSum,
                      Model.ScheduleBuilderList,
                      "Choose a schedule",
                      new {@class = "form-control", id="dropdown"})

and your Model should replace the type of ScheduleBuilderList with the following type:

IEnumerable<SelectListItem>


问:
RxJS: Treat first case specially, but continue streaming the rest
Say I wanted to separately handle the first event emitted by an Observable, but then continue my subscription.

For example, if I had the following chain:

```<code>observable.throttleTime(2000)
      .takeFirst(() => console.log('potato'))
      .switchMap((event:MouseEvent) => {
        const element:Element = event.target as Element;
        return this.innerObservable(('tomato'));
      })
      .subscribe(({result}) => console.log(result))
</code>```

That fails, but how would I go about making such behaviour work?

答:
You can create an operator that subscribes to the source observable, processes the first element and then removes itself from the chain. Let's call it onFirst because takeFirst is an existing operator in Java. Rxjs 5 example:

```<code>Observable.prototype.onFirst = function(callback) {
  return Observable.create(observer => {
    let source = this.publish()
    let subs = source.subscribe({
      next(v) {
        subs.unsubscribe()
        source.subscribe(observer)
        callback(v)
      },
      error(e) { observer.error(e) },
      complete() { observer.complete() }
    })
    source.connect()
  })
}

// This prints
// first: 1
// 2
// 3
Observable.of(1, 2, 3)
  .onFirst(v => console.log("first: " + v))
  .subscribe(console.log)
</code>```

Body:
Say I wanted to separately handle the first event emitted by an Observable, but then continue my subscription.

For example, if I had the following chain:

observable.throttleTime(2000)
      .takeFirst(() => console.log('potato'))
      .switchMap((event:MouseEvent) => {
        const element:Element = event.target as Element;
        return this.innerObservable(('tomato'));
      })
      .subscribe(({result}) => console.log(result))

That fails, but how would I go about making such behaviour work?

Body:
You can create an operator that subscribes to the source observable, processes the first element and then removes itself from the chain. Let's call it onFirst because takeFirst is an existing operator in Java. Rxjs 5 example:

Observable.prototype.onFirst = function(callback) {
  return Observable.create(observer => {
    let source = this.publish()
    let subs = source.subscribe({
      next(v) {
        subs.unsubscribe()
        source.subscribe(observer)
        callback(v)
      },
      error(e) { observer.error(e) },
      complete() { observer.complete() }
    })
    source.connect()
  })
}

// This prints
// first: 1
// 2
// 3
Observable.of(1, 2, 3)
  .onFirst(v => console.log("first: " + v))
  .subscribe(console.log)


问:
How to use Promise inside controller in angularjs?
I'm learning angularjs and trying to append a greeting to h3 tag using Promise. But it doesn't work (no error log).

angular.module('app', []).controller('test', function ($scope) {
  $scope.greeting = 'Hello world!';

  let p1 = new Promise(r => r('Hi'));
  let p2 = new Promise(r => r('Im Gosu'));

  Promise.all([p1, p2]).then(p => {
    $scope.greeting = `${p[0]} ${p[1]}`;

    console.log(p[0]);
    console.log(p[1]);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
  <h3 ng-bind="greeting"></h3>
</div></code>```

What am I missing?

答:
Angular needs to know that your promise has been resolved to trigger a change detection cycle, reevaluate the expression greetingused in the view, detect that it has changed, and update the DOM.

If you use the angular $q service, that's automatic, because every time a $q promise is resolved, the $q angular service triggers the change detection. By using native promises, you're changing the state of your model behind the back of angular.

So, either use $q, or understand what you're doing and add $scope.$apply() at the end of your callback function, to inform angular that you have changed the model.

Body:
I'm learning angularjs and trying to append a greeting to h3 tag using Promise. But it doesn't work (no error log).

angular.module('app', []).controller('test', function ($scope) {
  $scope.greeting = 'Hello world!';

  let p1 = new Promise(r => r('Hi'));
  let p2 = new Promise(r => r('Im Gosu'));

  Promise.all([p1, p2]).then(p => {
    $scope.greeting = `${p[0]} ${p[1]}`;

    console.log(p[0]);
    console.log(p[1]);
  });
});

What am I missing?


问:
How to detect which dynamically created button inside a Fragment was clicked, from Activity?
I have a Fragment class that dynamically creates a grid of Buttons. An instance of that fragment is then created within the main activity which displays the grid. Here is my code:

Grid.java

```<code>public class Grid extends Fragment {

    LinearLayout myLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLayout = new LinearLayout(getActivity());
        LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        myLayout.setLayoutParams(lparams);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        for (int i = 0; i < 4; i++) {
            LinearLayout row = new LinearLayout(getActivity());
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btnTag = new Button(getActivity());
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btnTag.setLayoutParams(btnParams);
                btnTag.setText(" " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            myLayout.addView(row);
        }
        return myLayout;
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }
}
</code>```

And in addition here is my content_mainactivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_mainactivity"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.owner.tables.MainActivity"
    tools:showIn="@layout/activity_mainactivity">

    <FrameLayout
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:id="@+id/grid"
        android:layout_centerHorizontal="true">
    </FrameLayout>

</RelativeLayout>
</code>```

So my question is, how can I detect if and which button was clicked in fragment from the Activity? Or if I can do this in the fragment, how to pass on the information to the activity?

答:
Create an interface:

```<code>public interface MyGridInterface  {
    void myAction(<Params...>);
}
</code>```

Set Listener in Fragment:

```<code>MainActivity mActivity = new MainActivity();
setEleListener(mActivity);

public void setMyListener(MyGridInterface listener) {
        this.gListener = listener;
    }
</code>```

Implement the Listener in MainActivity

```<code>public class MainActivity extends AppCompatActivity implements MyGridInterface{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }

  @Override
    public void myAction(<Params..>) {

        //Here do whatever you want
    }

}
</code>```

Body:
I have a Fragment class that dynamically creates a grid of Buttons. An instance of that fragment is then created within the main activity which displays the grid. Here is my code:

Grid.java

public class Grid extends Fragment {

    LinearLayout myLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLayout = new LinearLayout(getActivity());
        LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        myLayout.setLayoutParams(lparams);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        for (int i = 0; i < 4; i++) {
            LinearLayout row = new LinearLayout(getActivity());
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btnTag = new Button(getActivity());
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btnTag.setLayoutParams(btnParams);
                btnTag.setText(" " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            myLayout.addView(row);
        }
        return myLayout;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }
}

And in addition here is my content_mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_mainactivity"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.owner.tables.MainActivity"
    tools:showIn="@layout/activity_mainactivity">

    <FrameLayout
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:id="@+id/grid"
        android:layout_centerHorizontal="true">
    </FrameLayout>

</RelativeLayout>

So my question is, how can I detect if and which button was clicked in fragment from the Activity? Or if I can do this in the fragment, how to pass on the information to the activity?

Body:
Create an interface:

public interface MyGridInterface  {
    void myAction(<Params...>);
}

Set Listener in Fragment:

MainActivity mActivity = new MainActivity();
setEleListener(mActivity);

public void setMyListener(MyGridInterface listener) {
        this.gListener = listener;
    }

Implement the Listener in MainActivity

public class MainActivity extends AppCompatActivity implements MyGridInterface{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }

  @Override
    public void myAction(<Params..>) {

        //Here do whatever you want
    }

}


问:
C++ I/O copy txt file of different types
i am learning how to read/write files using C++ and ran into a problem copying the first line of a txt file. I pasted the txt file below. As you can see, the first line has two strings while the rows below are of different types. How would I declare the type for column 2 since it is a string on row 1 and an integer after that? While I can copy the file's contents to output.txt by declaring everything as a string, I was curious how to deal with different types. Your help is much appreciated.

input.txt file:

```<code>firstname value
Jack 1
Jacob 3
Jerry 2
Jeremy 3
Joseph 3
Jim 3
</code>```

I am getting a blank output.txt file because of type conflict I think.

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string fname;
int value;

using namespace std;

int main() {
    ifstream in_file; //variable name
    in_file.open("input.txt");
    if (in_file.fail()){
        cout << " The file is not found " << endl;
        return 1;
    }

    ofstream out_file;
    out_file.open("output.txt");
    while (in_file >> fname >> value){
    out_file << fname << " " << value <<  endl;
    };

}
</code>```

答:
Thanks @ForceBru This worked for me, though please let me know if there's a more efficient way to accomplish this: </p>

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string fname;
string col2;
int lname;

using namespace std;

int main() {
    int count=0;
    ifstream in_file; //variable name
    in_file.open("input.txt");
    if (in_file.fail()){
        cout << " The file is not found " << endl;
        return 1;
    }

    ofstream out_file;
    out_file.open("output.txt");

    if (count==0){
        in_file >> fname >> col2;
        out_file << fname << " " << col2 << endl;
        count++;
    }

    while (in_file >> fname >> lname){
        out_file << fname << " " << lname <<  endl;
    };

}
</code>```

Body:
i am learning how to read/write files using C++ and ran into a problem copying the first line of a txt file. I pasted the txt file below. As you can see, the first line has two strings while the rows below are of different types. How would I declare the type for column 2 since it is a string on row 1 and an integer after that? While I can copy the file's contents to output.txt by declaring everything as a string, I was curious how to deal with different types. Your help is much appreciated.

input.txt file:

firstname value
Jack 1
Jacob 3
Jerry 2
Jeremy 3
Joseph 3
Jim 3

I am getting a blank output.txt file because of type conflict I think.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string fname;
int value;

using namespace std;

int main() {
    ifstream in_file; //variable name
    in_file.open("input.txt");
    if (in_file.fail()){
        cout << " The file is not found " << endl;
        return 1;
    }

    ofstream out_file;
    out_file.open("output.txt");
    while (in_file >> fname >> value){
    out_file << fname << " " << value <<  endl;
    };

}

Body:
Thanks @ForceBru This worked for me, though please let me know if there's a more efficient way to accomplish this:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string fname;
string col2;
int lname;

using namespace std;

int main() {
    int count=0;
    ifstream in_file; //variable name
    in_file.open("input.txt");
    if (in_file.fail()){
        cout << " The file is not found " << endl;
        return 1;
    }

    ofstream out_file;
    out_file.open("output.txt");

    if (count==0){
        in_file >> fname >> col2;
        out_file << fname << " " << col2 << endl;
        count++;
    }

    while (in_file >> fname >> lname){
        out_file << fname << " " << lname <<  endl;
    };

}


问:
Should I use Google Maps degug or release key whenever setting up a beta/alpha test
So I will be setting up my first alpha test. Do I need to use the release key or debug key that created for the Google Maps API?

Thanks

答:
Use a release key for that. Since this is an alpha RELEASE of your app. Meaning it will be used by others.

You can configure it in build.gradle in a very elegant way.


问:
how to set session variable and validation both together on same button in php
I'm a newbie in php. I want to validate a form and set the form data to the session variables so as to use them onto next page.
here is the code,

```<code><?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function val(){
    var n=document.f.cname.value;
    if(n==""||n==null){
        alert("Please enter name field.");
        return false;
    }
}
</script>
</head>
<body>
<form method="post" action="<?php $_Php_SELF?>" onsubmit="return val()">
name : <input type="text" name="cname" />
<input type="Submit" name="submit" value="Sub"/>
</form>
<?php
if(isset($_POST['submit'])){
    $_SESSION['caname']=$_POST['cname'];
    header("location:sessiontest2.php");
}
?>
</body>
</html>
</code>```

The second page just echos the session variable.
Without validation it works fine.

答:
Handle your redirection before the html part. Also fixed your code.</p>

```<code><?php
session_start();

if(isset($_POST['submit'])){
    $_SESSION['caname'] = $_POST['cname'];
    header("location:sessiontest2.php");
}
?>
<html>
<body>
<form name="myForm" method="post" action="<?= $_SERVER['PHP_SELF']?>" onsubmit="return validate()">
    Name : <input type="text" name="cname"/>
    <input type="Submit" name="submit" value="Sub"/>
</form>
<script type="text/javascript">
    function validate() {
        var name = document.forms["myForm"]["cname"].value;

        if(name.length === 0){
            alert("Please enter the name");
            return false;
        }
    }
</script>
</body>
</html>
</code>```

Body:
I'm a newbie in php. I want to validate a form and set the form data to the session variables so as to use them onto next page.
here is the code,

<?php
session_start();
?>

<form method="post" action="<?php $_Php_SELF?>" onsubmit="return val()">
name : <input type="text" name="cname" />
<input type="Submit" name="submit" value="Sub"/>
</form>
<?php
if(isset($_POST['submit'])){
    $_SESSION['caname']=$_POST['cname'];
    header("location:sessiontest2.php");
}
?>

The second page just echos the session variable.
Without validation it works fine.

Body:
Handle your redirection before the html part. Also fixed your code.

<?php
session_start();

if(isset($_POST['submit'])){
    $_SESSION['caname'] = $_POST['cname'];
    header("location:sessiontest2.php");
}
?>
<html>
<body>
<form name="myForm" method="post" action="<?= $_SERVER['PHP_SELF']?>" onsubmit="return validate()">
    Name : <input type="text" name="cname"/>
    <input type="Submit" name="submit" value="Sub"/>
</form>
<script type="text/javascript">
    function validate() {
        var name = document.forms["myForm"]["cname"].value;

        if(name.length === 0){
            alert("Please enter the name");
            return false;
        }
    }
</script>
</body>
</html>


问:
How can I create a seaborn regression plot with multiindex dataframe?
I have time series data which are multi-indexed on (Year, Month) as seen here:

```<code>print(df.index)
print(df)
</code>```

```<code>MultiIndex(levels=[[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0], [2, 3, 4, 5, 6, 7, 8, 9]],
           names=['Year', 'Month'])
            Value
Year Month
2016 3       65.018150
     4       63.130035
     5       71.071254
     6       72.127967
     7       67.357795
     8       66.639228
     9       64.815232
     10      68.387698
</code>```

I want to do very basic linear regression on these time series data. Because pandas.DataFrame.plot does not do any regression, I intend to use Seaborn to do my plotting.

I attempted to do this by using lmplot:

```<code>sns.lmplot(x=("Year", "Month"), y="Value", data=df, fit_reg=True)
</code>```

but I get an error:

```<code>TypeError: '>' not supported between instances of 'str' and 'tuple'
</code>```

This is particularly interesting to me because all elements in df.index.levels[:] are of type numpy.int64, all elements in df.index.labels[:] are of type numpy.int8.

Why am I receiving this error? How can I resolve it?

答:
Consider the following approach:

```<code>df['x'] = df.index.get_level_values(0) + df.index.get_level_values(1)/100
</code>```

yields:

```<code>In [49]: df
Out[49]:
                Value        x
Year Month
2016 3      65.018150  2016.03
     4      63.130035  2016.04
     5      71.071254  2016.05
     6      72.127967  2016.06
     7      67.357795  2016.07
     8      66.639228  2016.08
     9      64.815232  2016.09
     10     68.387698  2016.10
</code>```

let's prepare X-ticks labels:

```<code>labels = df.index.get_level_values(0).astype(str) + '-' + \
         df.index.get_level_values(1).astype(str).str.zfill(2)

sns.lmplot(x='x', y='Value', data=df, fit_reg=True)
ax = plt.gca()
ax.set_xticklabels(labels)
</code>```

Result:

Body:
I have time series data which are multi-indexed on (Year, Month) as seen here:

print(df.index)
print(df)

MultiIndex(levels=[[2016, 2017], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0], [2, 3, 4, 5, 6, 7, 8, 9]],
           names=['Year', 'Month'])
            Value
Year Month
2016 3       65.018150
     4       63.130035
     5       71.071254
     6       72.127967
     7       67.357795
     8       66.639228
     9       64.815232
     10      68.387698

I want to do very basic linear regression on these time series data. Because pandas.DataFrame.plot does not do any regression, I intend to use Seaborn to do my plotting.

I attempted to do this by using lmplot:

sns.lmplot(x=("Year", "Month"), y="Value", data=df, fit_reg=True)

but I get an error:

TypeError: '>' not supported between instances of 'str' and 'tuple'

This is particularly interesting to me because all elements in df.index.levels[:] are of type numpy.int64, all elements in df.index.labels[:] are of type numpy.int8.

Why am I receiving this error? How can I resolve it?

Body:
Consider the following approach:

df['x'] = df.index.get_level_values(0) + df.index.get_level_values(1)/100

yields:

In [49]: df
Out[49]:
                Value        x
Year Month
2016 3      65.018150  2016.03
     4      63.130035  2016.04
     5      71.071254  2016.05
     6      72.127967  2016.06
     7      67.357795  2016.07
     8      66.639228  2016.08
     9      64.815232  2016.09
     10     68.387698  2016.10

let's prepare X-ticks labels:

labels = df.index.get_level_values(0).astype(str) + '-' + \
         df.index.get_level_values(1).astype(str).str.zfill(2)

sns.lmplot(x='x', y='Value', data=df, fit_reg=True)
ax = plt.gca()
ax.set_xticklabels(labels)

Result:


问:
Windows Service SQL Server error - "Login failed for user"
I have a Windows Service written in C# being run on a Windows Server 2012 R2 machine which connects to a remote SQL Server 2012 instance also on a Windows Server 2012 R2 Server.

The SQL Connection String is defined in the App Config as follows:

```<code><connectionStrings>
    <add name="destinationConnectionString" providerName="System.Data.SqlClient"
    connectionString="Server=10.42.42.10;Database=mydb;User ID=myuser;Password=mypass" />
</connectionStrings>
</code>```

When running the service, the output error log shows:

System.Data.SqlClient.SqlException (0x80131904): Login failed for user
  'myuser'.

Error Number:18456, State:1, Class:14

So I check the SQL Server Logs to find out more information about the error and find this

Login failed for user myuser Reason: Password did not match for the
  login provided"

Source: Logon  Message: Error: 18456, Severity: 14, State: 8.

The problem is I know these credentials are correct. I've checked and double checked.

I am able to prove the credentials work by opening SQL Server Management Studio on the source machine, and connecting to the remote SQL Server using the exact same Server, User ID and Password with "SQL Server Authentication" authentication mode.

In fact I have 2 different users that I'm able to connect with using SSMS, but that fail using the Windows service. If I am able to connect to the remote machine using mixed mode auth directly in SSMS. Why not in my Windows service?

I'm at a loss here, could anyone suggest what the issue might be?

Edit: I can even successfully connect to the remote machine using the following command:

```<code>sqlcmd -S 10.42.42.10 -U myuser -P mypass -d mydb
</code>```

答:
I had the same problem and here is my solution:

I found out that I was using named instance of an SQL server and changed Server of my connection string from Server=localhost to Server=localhost\SQLEXPRESS and everything worked just fine for me! :)

Body:
I have a Windows Service written in C# being run on a Windows Server 2012 R2 machine which connects to a remote SQL Server 2012 instance also on a Windows Server 2012 R2 Server.

The SQL Connection String is defined in the App Config as follows:

<connectionStrings>
    <add name="destinationConnectionString" providerName="System.Data.SqlClient"
    connectionString="Server=10.42.42.10;Database=mydb;User ID=myuser;Password=mypass" />
</connectionStrings>

When running the service, the output error log shows:

System.Data.SqlClient.SqlException (0x80131904): Login failed for user
  'myuser'.

Error Number:18456, State:1, Class:14

So I check the SQL Server Logs to find out more information about the error and find this

Login failed for user myuser Reason: Password did not match for the
  login provided"

Source: Logon  Message: Error: 18456, Severity: 14, State: 8.

The problem is I know these credentials are correct. I've checked and double checked.

I am able to prove the credentials work by opening SQL Server Management Studio on the source machine, and connecting to the remote SQL Server using the exact same Server, User ID and Password with "SQL Server Authentication" authentication mode.

In fact I have 2 different users that I'm able to connect with using SSMS, but that fail using the Windows service. If I am able to connect to the remote machine using mixed mode auth directly in SSMS. Why not in my Windows service?

I'm at a loss here, could anyone suggest what the issue might be?

Edit: I can even successfully connect to the remote machine using the following command:

sqlcmd -S 10.42.42.10 -U myuser -P mypass -d mydb


问:
Change node.name inside of touch without running again?
I want to click on a certain spritenode and change the value of that spritenode. Here is the problem. When i do that, and set a if statement it knows to go to that if statement. However, i don't want it to run until next time the button is clicked.

Example:

```<code>apple.name = "apple"

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let node : SKNode = self.atPoint(location)
        if node.name == "apple" {
            appple.name = "orange"
            print("Hello")
        }
        if node.name = "orange" {
        //do this
}

    }
}
</code>```

Is there a way to do this?

答:
first of all in your second if statement you are not checking the value "==" your are assigning a value "=" to it.

anyway a simple solution to your problem is to add an else if statement.

```<code>if node.name == "apple" {
        appple.name = "orange"
        print("Hello")
    }else if node.name == "orange" {
    //do this
}
</code>```

Body:
I want to click on a certain spritenode and change the value of that spritenode. Here is the problem. When i do that, and set a if statement it knows to go to that if statement. However, i don't want it to run until next time the button is clicked.

Example:

apple.name = "apple"

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let node : SKNode = self.atPoint(location)
        if node.name == "apple" {
            appple.name = "orange"
            print("Hello")
        }
        if node.name = "orange" {
        //do this
}

    }
}

Is there a way to do this?

Body:
first of all in your second if statement you are not checking the value "==" your are assigning a value "=" to it.

anyway a simple solution to your problem is to add an else if statement.

if node.name == "apple" {
        appple.name = "orange"
        print("Hello")
    }else if node.name == "orange" {
    //do this
}


问:
Injecting viewmodel to view with MEF - Binding from source not working - WPF
I'm injecting my viewmodel to my view using the MEF container like below:

```<code>    [ImportingConstructor]
    public MainView(IRepository repository, MainViewModel viewModel)
    {
        InitializeComponent();
        mMainViewModel = viewModel;
        DataContext = viewModel;
        viewModel.PropertyChanged += OnViewModelPropertyChanged;
    }
</code>```

Everything works fine. I have the export attribute on both the view and viewmodel.

The problem is that when a value\property is updated on the ViewModel by some method, it does not reflect on the UI. I even tried to set Mode to Two way - still not working. I have OnPropertyChanged called for all property setters, but not working. HOWEVER, in the code behind for the view though, if I attach a propertychanged event method to the viewmodel, I get the event notifications and that is the only way I'm able to update the view using their but that should not be necessary. I just don't know why my view is not responding to propertychanged notifications directly on the bound elements.

What could I be doing wrong?

答: Found the issue. Turned out that in my abstract ViewModelBase class, I had the functions for notifypropertychanged...But I didn't have the INotifyPropertyChanged on the class name although I implemented the method..stupid mistake. Must have missed it. Brings up another question...why must we have the interface definition on the class for it to work?...well, all is good now. works fine now. </p>

Body:
I'm injecting my viewmodel to my view using the MEF container like below:

    [ImportingConstructor]
    public MainView(IRepository repository, MainViewModel viewModel)
    {
        InitializeComponent();
        mMainViewModel = viewModel;
        DataContext = viewModel;
        viewModel.PropertyChanged += OnViewModelPropertyChanged;
    }

Everything works fine. I have the export attribute on both the view and viewmodel.

The problem is that when a value\property is updated on the ViewModel by some method, it does not reflect on the UI. I even tried to set Mode to Two way - still not working. I have OnPropertyChanged called for all property setters, but not working. HOWEVER, in the code behind for the view though, if I attach a propertychanged event method to the viewmodel, I get the event notifications and that is the only way I'm able to update the view using their but that should not be necessary. I just don't know why my view is not responding to propertychanged notifications directly on the bound elements.

What could I be doing wrong?


问:
Get ViewGroup(Layout) of custom view
I made a custom View, called ColorPicker. I create my ColorPicker in my xml.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearlayout_settings">

    <visuals.customview.ColorPicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

In the ColorPicker's Constr i need a ref to my LinearLayout, but i can't find any answer here.

```<code>public ColorPicker(Context context, AttributeSet attrs) {
    super(context, attrs);

    //LinearLayout layout = ???;
}
</code>```

I tried following solutions which i read on similar questions:

```<code>getParent();
</code>```

returns null

```<code>getRootView();
</code>```

returns the ColorPicker itself

```<code>findViewByID(R.id.linearlayout_settings);
</code>```

returns null

Thank's in advance

答:
Use The Color Dialog Box
This Better For pick color on Activity
  colorDialog.setPickerColor(YourActivity.this, 2, color);

OR

```<code><visuals.customview.ColorPicker
    android:layout_width="wrap_content"
    android:id="@+id/vis1"
    android:layout_height="wrap_content" />
</code>```

Create Object in Java File
find object in java file

Try it.

Title: Get ViewGroup(Layout) of custom view

Body:
I made a custom View, called ColorPicker. I create my ColorPicker in my xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearlayout_settings">

    <visuals.customview.ColorPicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

In the ColorPicker's Constr i need a ref to my LinearLayout, but i can't find any answer here.

public ColorPicker(Context context, AttributeSet attrs) {
    super(context, attrs);

    //LinearLayout layout = ???;
}

I tried following solutions which i read on similar questions:

getParent();

returns null

getRootView();

returns the ColorPicker itself

findViewByID(R.id.linearlayout_settings);

returns null

Thank's in advance

Body:
Use The Color Dialog Box
This Better For pick color on Activity
  colorDialog.setPickerColor(YourActivity.this, 2, color);

OR

<visuals.customview.ColorPicker
    android:layout_width="wrap_content"
    android:id="@+id/vis1"
    android:layout_height="wrap_content" />

Create Object in Java File
find object in java file

Try it.


问:
Python - SqlAlchemy: convert lists of tuples to list of atomic values
while working on my Python project (my first app), I ran into an issue when running a query against the database:
I get as a result a list of tuples containing a single value, like:
[(value1, ), (value2, )]
The tables involved have a Many to Many relationships, the ORM is SQLAlchemy.

My solution is to use a foreach loop:

```<code>def get_user_roles(user_id):

    the_roles = db.session.query(Role.role).filter(Role.users.any(id=user_id)).all()
    response = []
    length = len(the_roles)
    for key in range(length):
        the_roles[key] = list(the_roles[key])
        response.append(the_roles[key][0])

    return response
</code>```

For a better understanding, you can have a look here:
https://github.com/Deviad/adhesive/blob/master/theroot/users_bundle/helpers/users_and_roles.py

I am looking for a better approach as I know that foreach loops are time-consuming.

Thank you.

答:
Assuming the_roles is the list of tuples with one element (in your example you obtain it from database, but it doesn't matter for response object generating) like

```<code>>>>the_roles = [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]
</code>```

then we can generate response object using list comprehension and tuple unpacking

```<code>>>>response = [value for (value,) in the_roles]
>>>response
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

Finally your get_user_role can be rewritten like

```<code>def get_user_roles(user_id):
    the_roles = db.session.query(Role.role).filter(Role.users.any(id=user_id)).all()
    return [value for (value,) in the_roles]
</code>```

Body:
while working on my Python project (my first app), I ran into an issue when running a query against the database:
I get as a result a list of tuples containing a single value, like:
[(value1, ), (value2, )]
The tables involved have a Many to Many relationships, the ORM is SQLAlchemy.

My solution is to use a foreach loop:

def get_user_roles(user_id):

    the_roles = db.session.query(Role.role).filter(Role.users.any(id=user_id)).all()
    response = []
    length = len(the_roles)
    for key in range(length):
        the_roles[key] = list(the_roles[key])
        response.append(the_roles[key][0])

    return response

For a better understanding, you can have a look here:
https://github.com/Deviad/adhesive/blob/master/theroot/users_bundle/helpers/users_and_roles.py

I am looking for a better approach as I know that foreach loops are time-consuming.

Thank you.

Body:
Assuming the_roles is the list of tuples with one element (in your example you obtain it from database, but it doesn't matter for response object generating) like

>>>the_roles = [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]

then we can generate response object using list comprehension and tuple unpacking

>>>response = [value for (value,) in the_roles]
>>>response
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Finally your get_user_role can be rewritten like

def get_user_roles(user_id):
    the_roles = db.session.query(Role.role).filter(Role.users.any(id=user_id)).all()
    return [value for (value,) in the_roles]