问:
Getting names from text file shifts names 1 place to the left (in array)
I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22

Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.

Here is the code:

```<code>package Project022;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class NameScore {
    private long scoreSum;

    private LinkedList<String> allNames;

    private String[] sortedNames;
    private int[] nameScores;

    public NameScore(){
        scoreSum = 0;
        allNames = new LinkedList<>();
        getNames();
    }
    private void getNames(){
        List<String> content = null;
        File names;
        // read "names.txt" file and put all the names in one line(not effective when line
        // length surpasses String maximum character range(2^31 - 1) but is good enough for us
        // for now)
        try {
            names = new File("Project022\\names.txt");
            content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
        } catch (Exception e){
            System.out.println("something went wrong while getting the file");
        }
        assert content != null;

        //replace (",") with a space ( )
        String filtered = content.get(0).replaceAll("\",\"", " ");

        //then remove first and last (")
        filtered = filtered.substring(1, filtered.length() - 1);

        //declare "tempName" as a helper string
        StringBuilder tempName = new StringBuilder();

        //get every name and put it on the LinkedList
        for (int i = 0; i < filtered.length(); i++) {
            if (filtered.charAt(i) != ' '){
                tempName.append(filtered.charAt(i));
            } else {
                allNames.add(tempName.toString().trim());
                tempName = new StringBuilder();
            }
        }

        //now we use an pre defined array since it is faster.
        sortedNames = new String[allNames.size()];

        for (int i = 0; i < sortedNames.length; i++) {
            sortedNames[i] = allNames.get(i);
        }

        //make the new array worthy of its name
        Arrays.sort(sortedNames);

        System.out.println(sortedNames[937]);

        System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
    }

    public void calculate(){
        //we set the score for each name
        nameScores = new int[sortedNames.length];

        //
        for (int i = 0; i < nameScores.length; i++) {
            setScore(sortedNames[i], i + 1);
        }

        for (int i = 0; i < nameScores.length; i++) {
            scoreSum += nameScores[i];
        }
    }
    private void setScore(String name, int n) {
        int sc = 0;
        for (int i = 0; i < name.length(); i++) {
            sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
        }
        sc *= n;
        nameScores[n-1] = sc;
    }
    @Override
    public String toString(){ return "the score of all names is: " + scoreSum; }

    public static void main(String[] args) {
        NameScore name = new NameScore();
        name.calculate();
        System.out.println(name);
    }
}
</code>```

What I've ruled out as a problem:

the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.

the calculate() method, since what it does is gets the score for each name and adds to the total sum.

答:
I didn't want to make too many changes to your code, so just removed your replacement of "," and instead just removed all ". Then I added ALONSO in the end after the loop.

I figure if we're all in consensus about the total score of all the names, then we're doing it right :)

It prints:

```<code> -- Where's ALONSO ?
sortedNames[145] = ALONA
sortedNames[146] = ALONSO
sortedNames[147] = ALONZO

 -- Where's COLIN ?
sortedNames[936] = COLETTE
sortedNames[937] = COLIN
sortedNames[938] = COLLEEN

 -- Where's MARY ?
sortedNames[3361] = MARX
sortedNames[3362] = MARY
sortedNames[3363] = MARYA

 -- sortedNames.length = 5163

the score of all names is: 871198282
</code>```

I also called it Project022:

```<code>import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

//public class NameScore {
public class Project022 {
    private long scoreSum;

    private LinkedList<String> allNames;

    private String[] sortedNames;
    private int[] nameScores;

    public Project022(){
        scoreSum = 0;
        allNames = new LinkedList<>();
        getNames();
    }
    private void getNames(){
        List<String> content = null;
        File names;
        // read "names.txt" file and put all the names in one line(not effective when line
        // length surpasses String maximum character range(2^31 - 1) but is good enough for us
        // for now)
        try {
//            names = new File("Project022\\names.txt");
            names = new File("resource\\p022_names.txt");
            content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
        } catch (Exception e){
            System.out.println("something went wrong while getting the file");
        }
        assert content != null;

        //replace (",") with a space ( )
//        String filtered = content.get(0).replaceAll("\",\"", " ");
        String filtered = content.get(0).replaceAll("\"", "");

//        //then remove first and last (")
//        filtered = filtered.substring(1, filtered.length() - 1);

        //declare "tempName" as a helper string
        StringBuilder tempName = new StringBuilder();

        //get every name and put it on the LinkedList
        for (int i = 0; i < filtered.length(); i++) {
//            if (filtered.charAt(i) != ' '){
            if (filtered.charAt(i) != ','){
                tempName.append(filtered.charAt(i));
            } else {
                allNames.add(tempName.toString().trim());
                tempName = new StringBuilder();
            }
        }
        allNames.add(tempName.toString().trim());  // added to include ALONSO

        //now we use an pre defined array since it is faster.
        sortedNames = new String[allNames.size()];

        for (int i = 0; i < sortedNames.length; i++) {
            sortedNames[i] = allNames.get(i);
        }

        //make the new array worthy of its name
        Arrays.sort(sortedNames);

        System.out.println("\n -- Where's ALONSO ?");
        for (int i = 145; i < 148; i++) {
          // sortedNames[0] = AARON
          System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
        }

        System.out.println("\n -- Where's COLIN ?");
        for (int i = 936; i < 939; i++) {
          // sortedNames[0] = AARON
          System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
        }

        System.out.println("\n -- Where's MARY ?");
        for (int i = 3361; i < 3364; i++) {
          // sortedNames[0] = AARON
          System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
        }

        System.out.println("\n -- sortedNames.length = " + sortedNames.length + "\n");

//        System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
    }

    public void calculate(){
        //we set the score for each name
        nameScores = new int[sortedNames.length];

        //
        for (int i = 0; i < nameScores.length; i++) {
            setScore(sortedNames[i], i + 1);
        }

        for (int i = 0; i < nameScores.length; i++) {
            scoreSum += nameScores[i];
        }
    }
    private void setScore(String name, int n) {
        int sc = 0;
        for (int i = 0; i < name.length(); i++) {
            sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
        }
        sc *= n;
        nameScores[n-1] = sc;
    }
    @Override
    public String toString(){ return "the score of all names is: " + scoreSum; }

    public static void main(String[] args) {
        Project022 name = new Project022();
        name.calculate();
        System.out.println(name);
    }
}
</code>```

Body:
I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22

Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.

Here is the code:

package Project022;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class NameScore {
    private long scoreSum;

    private LinkedList<String> allNames;

    private String[] sortedNames;
    private int[] nameScores;

    public NameScore(){
        scoreSum = 0;
        allNames = new LinkedList<>();
        getNames();
    }
    private void getNames(){
        List<String> content = null;
        File names;
        // read "names.txt" file and put all the names in one line(not effective when line
        // length surpasses String maximum character range(2^31 - 1) but is good enough for us
        // for now)
        try {
            names = new File("Project022\\names.txt");
            content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
        } catch (Exception e){
            System.out.println("something went wrong while getting the file");
        }
        assert content != null;

        //replace (",") with a space ( )
        String filtered = content.get(0).replaceAll("\",\"", " ");

        //then remove first and last (")
        filtered = filtered.substring(1, filtered.length() - 1);

        //declare "tempName" as a helper string
        StringBuilder tempName = new StringBuilder();

        //get every name and put it on the LinkedList
        for (int i = 0; i < filtered.length(); i++) {
            if (filtered.charAt(i) != ' '){
                tempName.append(filtered.charAt(i));
            } else {
                allNames.add(tempName.toString().trim());
                tempName = new StringBuilder();
            }
        }

        //now we use an pre defined array since it is faster.
        sortedNames = new String[allNames.size()];

        for (int i = 0; i < sortedNames.length; i++) {
            sortedNames[i] = allNames.get(i);
        }

        //make the new array worthy of its name
        Arrays.sort(sortedNames);

        System.out.println(sortedNames[937]);

        System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
    }

    public void calculate(){
        //we set the score for each name
        nameScores = new int[sortedNames.length];

        //
        for (int i = 0; i < nameScores.length; i++) {
            setScore(sortedNames[i], i + 1);
        }

        for (int i = 0; i < nameScores.length; i++) {
            scoreSum += nameScores[i];
        }
    }
    private void setScore(String name, int n) {
        int sc = 0;
        for (int i = 0; i < name.length(); i++) {
            sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
        }
        sc *= n;
        nameScores[n-1] = sc;
    }
    @Override
    public String toString(){ return "the score of all names is: " + scoreSum; }

    public static void main(String[] args) {
        NameScore name = new NameScore();
        name.calculate();
        System.out.println(name);
    }
}

What I've ruled out as a problem:

the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.

the calculate() method, since what it does is gets the score for each name and adds to the total sum.

Body:
I didn't want to make too many changes to your code, so just removed your replacement of "," and instead just removed all ". Then I added ALONSO in the end after the loop.

I figure if we're all in consensus about the total score of all the names, then we're doing it right :)

It prints:

 -- Where's ALONSO ?
sortedNames[145] = ALONA
sortedNames[146] = ALONSO
sortedNames[147] = ALONZO

 -- Where's COLIN ?
sortedNames[936] = COLETTE
sortedNames[937] = COLIN
sortedNames[938] = COLLEEN

 -- Where's MARY ?
sortedNames[3361] = MARX
sortedNames[3362] = MARY
sortedNames[3363] = MARYA

 -- sortedNames.length = 5163

the score of all names is: 871198282

I also called it Project022:

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

//public class NameScore {
public class Project022 {
    private long scoreSum;

    private LinkedList<String> allNames;

    private String[] sortedNames;
    private int[] nameScores;

    public Project022(){
        scoreSum = 0;
        allNames = new LinkedList<>();
        getNames();
    }
    private void getNames(){
        List<String> content = null;
        File names;
        // read "names.txt" file and put all the names in one line(not effective when line
        // length surpasses String maximum character range(2^31 - 1) but is good enough for us
        // for now)
        try {
//            names = new File("Project022\\names.txt");
            names = new File("resource\\p022_names.txt");
            content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
        } catch (Exception e){
            System.out.println("something went wrong while getting the file");
        }
        assert content != null;

        //replace (",") with a space ( )
//        String filtered = content.get(0).replaceAll("\",\"", " ");
        String filtered = content.get(0).replaceAll("\"", "");

//        //then remove first and last (")
//        filtered = filtered.substring(1, filtered.length() - 1);

        //declare "tempName" as a helper string
        StringBuilder tempName = new StringBuilder();

        //get every name and put it on the LinkedList
        for (int i = 0; i < filtered.length(); i++) {
//            if (filtered.charAt(i) != ' '){
            if (filtered.charAt(i) != ','){
                tempName.append(filtered.charAt(i));
            } else {
                allNames.add(tempName.toString().trim());
                tempName = new StringBuilder();
            }
        }
        allNames.add(tempName.toString().trim());  // added to include ALONSO

        //now we use an pre defined array since it is faster.
        sortedNames = new String[allNames.size()];

        for (int i = 0; i < sortedNames.length; i++) {
            sortedNames[i] = allNames.get(i);
        }

        //make the new array worthy of its name
        Arrays.sort(sortedNames);

        System.out.println("\n -- Where's ALONSO ?");
        for (int i = 145; i < 148; i++) {
          // sortedNames[0] = AARON
          System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
        }

        System.out.println("\n -- Where's COLIN ?");
        for (int i = 936; i < 939; i++) {
          // sortedNames[0] = AARON
          System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
        }

        System.out.println("\n -- Where's MARY ?");
        for (int i = 3361; i < 3364; i++) {
          // sortedNames[0] = AARON
          System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
        }

        System.out.println("\n -- sortedNames.length = " + sortedNames.length + "\n");

//        System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
    }

    public void calculate(){
        //we set the score for each name
        nameScores = new int[sortedNames.length];

        //
        for (int i = 0; i < nameScores.length; i++) {
            setScore(sortedNames[i], i + 1);
        }

        for (int i = 0; i < nameScores.length; i++) {
            scoreSum += nameScores[i];
        }
    }
    private void setScore(String name, int n) {
        int sc = 0;
        for (int i = 0; i < name.length(); i++) {
            sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
        }
        sc *= n;
        nameScores[n-1] = sc;
    }
    @Override
    public String toString(){ return "the score of all names is: " + scoreSum; }

    public static void main(String[] args) {
        Project022 name = new Project022();
        name.calculate();
        System.out.println(name);
    }
}


来源: stackexchange

问:
JavaFX: Is there a way for Y axis to be positive upwards with origin at bottom-left?
The JavaFX coordinate system draws Y coords from the top of screen, and is positive downwards. I would like it to be positive upwards, and start from the bottom of screen.

There needs to be a translate, and the text nodes need to be flipped.

And with that, hopefully the drawn rectangle will be positioned the "natural" way we do it in math class.  With its bottom-left at the origin, expanding to the top-right.

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class FlippedExampleChart extends Application {

    private LineChart<Number, Number> chart;

    @Override
    public void start(Stage primaryStage) throws Exception {
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();

        // Flip the axis
        yAxis.setScaleY(-1);

        // TODO How to translate to bottom of screen.
        // TODO How to flip the text nodes.

        this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
            @Override
            public void layoutPlotChildren() {
                super.layoutPlotChildren();

                double height = yAxis.getDisplayPosition(100);

                Rectangle r = new Rectangle(0, 0, 50, height);
                r.setFill(Color.GREEN);
                getPlotChildren().addAll(r);
            }
        };
        this.chart.setAnimated(false);

        VBox vbox = new VBox(this.chart);

        Scene scene = new Scene(vbox, 400, 200);
        primaryStage.setScene(scene);
        primaryStage.setHeight(600);
        primaryStage.setWidth(400);
        primaryStage.show();
    }

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

答:
I'm assuming here the aim is to draw a shape using the coordinate system defined by the chart axes.

The easiest way is probably to transform the shape instead of the axis. You can create a utility method for this:

```<code>private Transform chartDisplayTransform(NumberAxis xAxis, NumberAxis yAxis) {
    return new Affine(
            xAxis.getScale(), 0, xAxis.getDisplayPosition(0),
            0, yAxis.getScale(), yAxis.getDisplayPosition(0)
    );
}
</code>```

One other note about your code: the layoutPlotChildren() method doesn't necessarily remove nodes, so you may end up adding more rectangles than you expect with the code you posted.

Here's a version of your code that uses this method (and ensures the rectangle is only added once).

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Affine;
import javafx.scene.transform.Transform;
import javafx.stage.Stage;

public class FlippedExampleChart extends Application {

    private LineChart<Number, Number> chart;

    @Override
    public void start(Stage primaryStage) throws Exception {
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();

        // Flip the axis
        // yAxis.setScaleY(-1);

        Rectangle r = new Rectangle(0, 0, 50, 100);
        r.setFill(Color.GREEN);

        this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
            @Override
            public void layoutPlotChildren() {
                super.layoutPlotChildren();
                r.getTransforms().setAll(chartDisplayTransform(xAxis, yAxis));
                // note nodes don't get removed from the plot children, and this method may be
                // called often:
                if (!getPlotChildren().contains(r)) {
                    getPlotChildren().add(r);
                }
            }
        };
        this.chart.setAnimated(false);

        VBox vbox = new VBox(this.chart);

        Scene scene = new Scene(vbox, 400, 200);
        primaryStage.setScene(scene);
        primaryStage.setHeight(600);
        primaryStage.setWidth(400);
        primaryStage.show();
    }

    private Transform chartDisplayTransform(NumberAxis xAxis, NumberAxis yAxis) {
        return new Affine(xAxis.getScale(), 0, xAxis.getDisplayPosition(0), 0, yAxis.getScale(),
                yAxis.getDisplayPosition(0));
    }

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

And the result:

If you have multiple nodes to treat this way, the strategy is to add them to a Group, and apply the transform to the Group:

```<code>@Override
public void start(Stage primaryStage) throws Exception {
    final NumberAxis xAxis = new NumberAxis();
    final NumberAxis yAxis = new NumberAxis();

    Group extraNodes = new Group();

    this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
        @Override
        public void layoutPlotChildren() {
            super.layoutPlotChildren();
            Rectangle r1 = new Rectangle(0, 0, 50, 100);
            r1.setFill(Color.GREEN);
            Rectangle r2 = new Rectangle(70, 0, 30, 20);
            r2.setFill(Color.AQUAMARINE);
            extraNodes.getChildren().setAll(r1, r2);
            extraNodes.getTransforms().setAll(chartDisplayTransform(xAxis, yAxis));
            // note nodes don't get removed from the plot children, and this method may be
            // called often:
            if (!getPlotChildren().contains(extraNodes)) {
                getPlotChildren().add(extraNodes);
            }
        }
    };
    this.chart.setAnimated(false);

    VBox vbox = new VBox(this.chart);

    Scene scene = new Scene(vbox, 400, 200);
    primaryStage.setScene(scene);
    primaryStage.setHeight(600);
    primaryStage.setWidth(400);
    primaryStage.show();
}
</code>```

Also see this related question

ContentLicense: CC BY-SA 4.0

Body:
The JavaFX coordinate system draws Y coords from the top of screen, and is positive downwards. I would like it to be positive upwards, and start from the bottom of screen.

There needs to be a translate, and the text nodes need to be flipped.

And with that, hopefully the drawn rectangle will be positioned the "natural" way we do it in math class.  With its bottom-left at the origin, expanding to the top-right.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class FlippedExampleChart extends Application {

    private LineChart<Number, Number> chart;

    @Override
    public void start(Stage primaryStage) throws Exception {
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();

        // Flip the axis
        yAxis.setScaleY(-1);

        // TODO How to translate to bottom of screen.
        // TODO How to flip the text nodes.

        this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
            @Override
            public void layoutPlotChildren() {
                super.layoutPlotChildren();

                double height = yAxis.getDisplayPosition(100);

                Rectangle r = new Rectangle(0, 0, 50, height);
                r.setFill(Color.GREEN);
                getPlotChildren().addAll(r);
            }
        };
        this.chart.setAnimated(false);

        VBox vbox = new VBox(this.chart);

        Scene scene = new Scene(vbox, 400, 200);
        primaryStage.setScene(scene);
        primaryStage.setHeight(600);
        primaryStage.setWidth(400);
        primaryStage.show();
    }

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

Body:
I'm assuming here the aim is to draw a shape using the coordinate system defined by the chart axes.

The easiest way is probably to transform the shape instead of the axis. You can create a utility method for this:

private Transform chartDisplayTransform(NumberAxis xAxis, NumberAxis yAxis) {
    return new Affine(
            xAxis.getScale(), 0, xAxis.getDisplayPosition(0),
            0, yAxis.getScale(), yAxis.getDisplayPosition(0)
    );
}

One other note about your code: the layoutPlotChildren() method doesn't necessarily remove nodes, so you may end up adding more rectangles than you expect with the code you posted.

Here's a version of your code that uses this method (and ensures the rectangle is only added once).

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.transform.Affine;
import javafx.scene.transform.Transform;
import javafx.stage.Stage;

public class FlippedExampleChart extends Application {

    private LineChart<Number, Number> chart;

    @Override
    public void start(Stage primaryStage) throws Exception {
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();

        // Flip the axis
        // yAxis.setScaleY(-1);

        Rectangle r = new Rectangle(0, 0, 50, 100);
        r.setFill(Color.GREEN);

        this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
            @Override
            public void layoutPlotChildren() {
                super.layoutPlotChildren();
                r.getTransforms().setAll(chartDisplayTransform(xAxis, yAxis));
                // note nodes don't get removed from the plot children, and this method may be
                // called often:
                if (!getPlotChildren().contains(r)) {
                    getPlotChildren().add(r);
                }
            }
        };
        this.chart.setAnimated(false);

        VBox vbox = new VBox(this.chart);

        Scene scene = new Scene(vbox, 400, 200);
        primaryStage.setScene(scene);
        primaryStage.setHeight(600);
        primaryStage.setWidth(400);
        primaryStage.show();
    }

    private Transform chartDisplayTransform(NumberAxis xAxis, NumberAxis yAxis) {
        return new Affine(xAxis.getScale(), 0, xAxis.getDisplayPosition(0), 0, yAxis.getScale(),
                yAxis.getDisplayPosition(0));
    }

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

And the result:

If you have multiple nodes to treat this way, the strategy is to add them to a Group, and apply the transform to the Group:

@Override
public void start(Stage primaryStage) throws Exception {
    final NumberAxis xAxis = new NumberAxis();
    final NumberAxis yAxis = new NumberAxis();

    Group extraNodes = new Group();

    this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
        @Override
        public void layoutPlotChildren() {
            super.layoutPlotChildren();
            Rectangle r1 = new Rectangle(0, 0, 50, 100);
            r1.setFill(Color.GREEN);
            Rectangle r2 = new Rectangle(70, 0, 30, 20);
            r2.setFill(Color.AQUAMARINE);
            extraNodes.getChildren().setAll(r1, r2);
            extraNodes.getTransforms().setAll(chartDisplayTransform(xAxis, yAxis));
            // note nodes don't get removed from the plot children, and this method may be
            // called often:
            if (!getPlotChildren().contains(extraNodes)) {
                getPlotChildren().add(extraNodes);
            }
        }
    };
    this.chart.setAnimated(false);

    VBox vbox = new VBox(this.chart);

    Scene scene = new Scene(vbox, 400, 200);
    primaryStage.setScene(scene);
    primaryStage.setHeight(600);
    primaryStage.setWidth(400);
    primaryStage.show();
}

Also see this related question


问:
Using unelevated privileges from user when running shell script as root
I am creating an installation script for a small program I wrote and it needs to be ran as root in order to copy the executable to /usr/bin/, although, there is a part of script that must be ran as the non-root user.

I know it is bad practice to use sudo inside of a script, but that's the only way I can think of doing this without separating the files or asking for the username. Surely there must be another way.

If I knew the username of who was running the script as sudo I could use
sudo -u username command
inside the script for the non-root parts, but then how would I get the user's name without asking for it when running the script?

答:
As @Philippe commented, I just needed to

sudo -u $SUDO_USER command


问:
How to set up IAP for self-managed Google Composer webserver on GKE
The company I work for has a Composer environment on Google Cloud and I recently had to create our own self-managed webserver application on the same GKE cluster because the standard webserver that was provided was experiencing a lot of timeout issues.

Anyway, when exposing this webserver through a basic ingress and without any access restrictions, I was able to connect to it just fine using the generated external ip address.  However, our team needs to restrict access to this webserver to only certain users, and we thought the best way to do this is to use IAP to restrict access to specific google accounts as described in this document: https://cloud.google.com/iap/docs/enabling-kubernetes-howto .

I've followed the guidelines in the above document to create an IAP-enabled load balancer, and when I connect to the webserver through the external ip address the load balancer logs in stackdriver state the request has been "handled_by_identity_aware_proxy" so I think it's being redirected.  But the problem is the browser is showing as "This site can't be reached", and I'm not being connected to the webserver.

I have a few suspicions as to the reason why and I was wondering if anyone could clarify these points:

The document above states that two requirements for setting up IAP are "a domain name registered to the address of the load balancer" and "app code to verify that all requests have an identity".  My first question is, is a registered domain name necessary for IAP, I don't have a registered domain name but is the external ip address generated by the ingress not enough?  And what does the document mean by "app code to verify that all requests have an identity"?  Does it mean I need to create a script in the webserver application to authenticate users?  Is this why I'm getting the "This site can't be reached" error in my browser?

In the Identity-Aware Proxy page on my Google Console, the status on my backend service is showing as "Warning".  I suspect this is because my project has a few firewall rules that allow for all ip ranges to have unrestricted access to the GKE cluster that this webserver is in.  My second question is, do ALL requests coming into the cluster have to go through this load balancer, or if there are certain ip ranges that can bypass the load balancer does that still allow for the IAP to run, despite the obvious security risks?  Or is this the reason why the ingress isn't working?

Thanks a lot for your help guys.

答:
1a. IAP works over HTTPS, so a SSL certificate is required to certificate of the ownership of the domain name registration. Without a certificate the site can be reached through the public external IP but it wouldn't work at all.

1b. Getting the user's identity enables your application to verify that a request came through IAP, and it is necessary config this in your app. You must always use some of the mechanisms: Get the users identity with signed headers, with App Engine and Users API

All requests coming into the cluster have to go through the Load Balancer


问:
XPath evaluation in VBA (Excel)
I have an xml file to be evaluated in Excel 2010.
The xml file looks as follows:

```<code><Account>
    <Entry>
        <Value>5</Value>
    </Entry>
    <Entry>
        <Value>4</Value>
    </Entry>
    <Entry>
        <Value>-3.6</Value>
    </Entry>
</Account>
</code>```

I want to sum over all values of every 'Entry' that fits some specified conditions. The evaluation which I need looks as follows:

```<code>sum(/*/Entry[Date[starts-with(., '04') and contains(., '2014')]][Value < 0.0][not(ContraEntryID)]/Value)
</code>```

I don't know how to get this evaluated in Excel.
What I get so far is a selection where I sum up over every item of it afterwards but there must be a better way to directly get the evaluation right? This is what I have already written:

Private Sub getSumOfValues()

Dim xmlFile As String
xmlFile = "..."

Dim xmlDoc As New MSXML2.DOMDocument60
Dim xmlSelection As IXMLDOMSelection

xmlDoc.async = False
xmlDoc.validateOnParse = True

xmlDoc.Load (xmlFile)

xmlDoc.setProperty "SelectionLanguage", "XPath"

Set xmlSelection = xmlDoc.SelectNodes("/*/Entry[Date[starts-with(., '04') and contains(., '2014')]][Value < 0.0][not(ContraEntryID)]/Value")

Dim i As Integer
Dim sum As Double
sum = 0
Dim val As String

For i = 0 To xmlSelection.Length - 1
    val = xmlSelection.Item(i).Text
    val = Replace(val, ".", ",")
    sum = sum + CDbl(val)
Next i
Debug.print(sum)
End Sub
```

答:
Yes, there's a direct evaluation possible now via FilterXML

Using the newer FilterXML function it's possible since 2013/16

to evaluate an XPath expression directly to an array and

in a 2nd step to sum the resulting contents:

Example call

I added a further condition to sum only values greater 0; can be changed to your needs.

Sub EvalIt()
' Purp: Sum up over every <Value> node contents in a given xml file
' Help: https://learn.microsoft.com/de-de/office/vba/api/excel.worksheetfunction.filterxml

'a) get xml path
    Dim xmlfile As String
    xmlfile = "C:\Users\Admin\Documents\Stack\xml\test.xml"  ' << change to your needs
'b) define XPath (search string in XML including example condition > 0)
    Dim XPath As String
    XPath = "//Value[.>0]"
'c) show result via function getSum() ~> items greater zero: (5+4)=9
    Debug.Print "Sum of <Value> node contents greater 0 = " & _
                getSum(xmlfile, XPath)

End Sub
```

<p><strong>Function <code>getSum()</code></strong></p>

<pre class="lang-vb prettyprint-override"><code>Function getSum(ByVal xmlfile As String, ByVal XPath As String) As Double
'   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'   Assign xml values to 1-based 2-dim array via function FilterXML
'   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Dim arr As Variant
    arr = WorksheetFunction.FilterXML(getXMLContent(xmlfile), XPath)

''   (optional) reduction to "flat" 1-dim array
'    arr = Application.Transpose(Application.Index(arr, 0, 1))
''   (optional) display of single array values in VBE Immediate Window
'    Debug.Print Join(arr, "|")

'   return result
    getSum = Application.Sum(arr)

End Function
</code>```

Help function getXMLContent() called by getSum()

This function gets the (well formed) xml content as string.
It distinguishes between
 - http:// Get calls using the WebService() function or
 - a local file path needing a direct load via MSXML (early bound in this example).

Function getXMLContent(ByVal xmlfile As String)
If Left$(xmlfile, 4) = "http" Then           ' a) URL
    getXMLContent = WorksheetFunction.WebService(xmlfile)
Else                                         ' b) a local file
    Dim xmlDoc As New MSXML2.DOMDocument60   ' early bound via Microsoft XML v6.0
    xmlDoc.Load xmlfile                      ' load xmlFile
    getXMLContent = xmlDoc.XML               ' return entire xml content string
End If
End Function
```

Caveat

I didn't include error handling for invalid file pathes or XPath constructions in order to allow a short, but clear view.

Title: XPath evaluation in VBA (Excel)

Body:
I have an xml file to be evaluated in Excel 2010.
The xml file looks as follows:

<Account>
    <Entry>
        <Value>5</Value>
    </Entry>
    <Entry>
        <Value>4</Value>
    </Entry>
    <Entry>
        <Value>-3.6</Value>
    </Entry>
</Account>

I want to sum over all values of every 'Entry' that fits some specified conditions. The evaluation which I need looks as follows:

sum(/*/Entry[Date[starts-with(., '04') and contains(., '2014')]][Value < 0.0][not(ContraEntryID)]/Value)

I don't know how to get this evaluated in Excel.
What I get so far is a selection where I sum up over every item of it afterwards but there must be a better way to directly get the evaluation right? This is what I have already written:

Private Sub getSumOfValues()

Dim xmlFile As String
xmlFile = "..."

Dim xmlDoc As New MSXML2.DOMDocument60
Dim xmlSelection As IXMLDOMSelection

xmlDoc.async = False
xmlDoc.validateOnParse = True

xmlDoc.Load (xmlFile)

xmlDoc.setProperty "SelectionLanguage", "XPath"

Set xmlSelection = xmlDoc.SelectNodes("/*/Entry[Date[starts-with(., '04') and contains(., '2014')]][Value < 0.0][not(ContraEntryID)]/Value")

Dim i As Integer
Dim sum As Double
sum = 0
Dim val As String

For i = 0 To xmlSelection.Length - 1
    val = xmlSelection.Item(i).Text
    val = Replace(val, ".", ",")
    sum = sum + CDbl(val)
Next i
Debug.print(sum)
End Sub

Body:
Yes, there's a direct evaluation possible now via FilterXML

Using the newer FilterXML function it's possible since 2013/16

to evaluate an XPath expression directly to an array and

in a 2nd step to sum the resulting contents:

Example call

I added a further condition to sum only values greater 0; can be changed to your needs.

Sub EvalIt()
' Purp: Sum up over every <Value> node contents in a given xml file
' Help: https://learn.microsoft.com/de-de/office/vba/api/excel.worksheetfunction.filterxml

'a) get xml path
    Dim xmlfile As String
    xmlfile = "C:\Users\Admin\Documents\Stack\xml\test.xml"  ' << change to your needs
'b) define XPath (search string in XML including example condition > 0)
    Dim XPath As String
    XPath = "//Value[.>0]"
'c) show result via function getSum() ~> items greater zero: (5+4)=9
    Debug.Print "Sum of <Value> node contents greater 0 = " & _
                getSum(xmlfile, XPath)

End Sub

Function getSum()

Function getSum(ByVal xmlfile As String, ByVal XPath As String) As Double
'   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'   Assign xml values to 1-based 2-dim array via function FilterXML
'   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Dim arr As Variant
    arr = WorksheetFunction.FilterXML(getXMLContent(xmlfile), XPath)

''   (optional) reduction to "flat" 1-dim array
'    arr = Application.Transpose(Application.Index(arr, 0, 1))
''   (optional) display of single array values in VBE Immediate Window
'    Debug.Print Join(arr, "|")

'   return result
    getSum = Application.Sum(arr)

End Function

Help function getXMLContent() called by getSum()

This function gets the (well formed) xml content as string.
It distinguishes between
 - http:// Get calls using the WebService() function or
 - a local file path needing a direct load via MSXML (early bound in this example).

Function getXMLContent(ByVal xmlfile As String)
If Left$(xmlfile, 4) = "http" Then           ' a) URL
    getXMLContent = WorksheetFunction.WebService(xmlfile)
Else                                         ' b) a local file
    Dim xmlDoc As New MSXML2.DOMDocument60   ' early bound via Microsoft XML v6.0
    xmlDoc.Load xmlfile                      ' load xmlFile
    getXMLContent = xmlDoc.XML               ' return entire xml content string
End If
End Function

Caveat

I didn't include error handling for invalid file pathes or XPath constructions in order to allow a short, but clear view.


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答:
You should raise/throw the exception in your catch block and handle it in the calling method.

```<code>public void invokeFaultyCode()
{
    try
    {
        DataTable dt = ReturnSomething();
    }
    catch(Exception e)
    {
        // Print the error message, cleanup, whatever
    }
}
public DataTable ReturnSomething() throws Exception
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
      throw;
   }
}
</code>```

PS: Sorry for any syntax error, I'm a bit rusty on C#.

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

Body:
You should raise/throw the exception in your catch block and handle it in the calling method.

public void invokeFaultyCode()
{
    try
    {
        DataTable dt = ReturnSomething();
    }
    catch(Exception e)
    {
        // Print the error message, cleanup, whatever
    }
}
public DataTable ReturnSomething() throws Exception
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
      throw;
   }
}

PS: Sorry for any syntax error, I'm a bit rusty on C#.

OwnerDisplayName: Manrico Corazzi

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Manrico Corazzi


问:
BB Simulator does not start
When I run my BB Simulator; I keep getting the following error:

Port in Use - BlackBerry Smartphone Simulator

Could not open port 19780 because it is in use by another program (possibly another instance of this simulator). You must close the other program for network operations to function correctly.

I have modified rimpublic.properties under MDS/config, but no luck.
[UDP]
UDP.receive.port=29781
UDP.send.default=29780

Any suggestions to get MDS and Simulator running???
I am running Win 7.

答:
I had Microsoft Client for ISA Server installed on my machine and that seems to be causing problems for BB MDS simulator. MDS and BB Simulator work fine after disabling the ISA client.

In general if the MDS simulator is having problems running, there is a another web server running on the machine which is causing port conflicts.

Title: BB Simulator does not start


问:
VBA Deleting Active Sheet
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?</p>

```<code>Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
</code>```

答:
If I understand correctly, you don't want to delete the last worksheet, and you want to avoid the error message.

You could try this:

```<code>Sub deleteallbutlast()

    Application.DisplayAlerts = False
        If Worksheets.Count > 1 Then
            ActiveSheet.Delete
        Else
            End
        End If
    Application.DisplayAlerts = True

End Sub
</code>```

Title: VBA Deleting Active Sheet

Body:
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?

Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True

Body:
If I understand correctly, you don't want to delete the last worksheet, and you want to avoid the error message.

You could try this:

Sub deleteallbutlast()

    Application.DisplayAlerts = False
        If Worksheets.Count > 1 Then
            ActiveSheet.Delete
        Else
            End
        End If
    Application.DisplayAlerts = True

End Sub


问:
logging all BigQuery queries
Is it possible to have all BigQuery requests logged to a file in Cloud Storage (or even better into a BigQuery table)?  It seems like the --apilog option available in bq is intended mainly for debugging purposes, but what I'd like to do is keep track of all queries, just like logging all access requests on a particular file in CloudStorage.

To be more specific, I don't just want to log my own queries, but (a) queries by all users within the same project, and optimally also (b) queries by anyone touching a table in a dataset that I own.

答:
BigQuery has the INFORMATION_SCHEMA.JOBS_BY_* view to retrieve real-time metadata about BigQuery jobs. This view contains currently running jobs, as well as the last 180 days of history of completed jobs.

For more info see Getting jobs metadata using INFORMATION_SCHEMA

Title: logging all BigQuery queries


问:
Error SQL0204 - Not found HTTPCLOB in SYSTOOOLS type *N
I am trying to use HTTPCLOB function to issue a POST request to a web service, but when I run the program I get the error as in the title, no matter my efforts to match the fields' type of my SQL statement to those of the function.
Here D-specifications:

```<code>D url             s           1024a   varying
D httpHeader      s           1024a   varying inz
D requestMsg      s          32000a   varying inz
D resHttpHeader   s          32000a   varying inz
D resMsg          s          32000a   varying inz
</code>```

This is the SQL statement:

```<code>url = 'https://labelservice.gls-italy.com/AddParcel';
requestMsg = 'XMLInfoParcel: ' + xmlData;
httpHeader = 'Content-Type: application/x-www-form-urlencoded;'
           + ' Content-Length: ' + %char(%len(requestMsg))
           ;
exec sql
  select cast(responseMsg as clob(2G))
  //   , cast(responseHttpHeader as varchar(512))
  into :resMsg
  // , :resHttpHeader
  from table(systoools.HTTPCLOB(
          URL => cast(:url
                 as varchar(2048)),
          HTTPMETHOD => 'POST',
          HTTPHEADER => cast(:httpHeader
                 as clob(10K)),
          REQUESTMSG => cast(:requestMsg
                 as clob(2G))
             )
       ) as httpRequest
;
</code>```

where xmlData is an xml-variabile with some content in it.
I assume there might be other errors because this is my first try using this function.
Anyway, as for the IBM documentation here
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/rzajq/rzajqudfhttpclob.htm
variables' types match.
What am I doing wrong?

答:
In addition to the spelling error noted in the other answer...

The SYSTOOLS functions for rest calls were made available in v7.1 as part of level 23(?) of the Database group PTF...

You linked to the v7.3 documentation, are you actually on v7.3?

Body:
I am trying to use HTTPCLOB function to issue a POST request to a web service, but when I run the program I get the error as in the title, no matter my efforts to match the fields' type of my SQL statement to those of the function.
Here D-specifications:

D url             s           1024a   varying
D httpHeader      s           1024a   varying inz
D requestMsg      s          32000a   varying inz
D resHttpHeader   s          32000a   varying inz
D resMsg          s          32000a   varying inz

This is the SQL statement:

url = 'https://labelservice.gls-italy.com/AddParcel';
requestMsg = 'XMLInfoParcel: ' + xmlData;
httpHeader = 'Content-Type: application/x-www-form-urlencoded;'
           + ' Content-Length: ' + %char(%len(requestMsg))
           ;
exec sql
  select cast(responseMsg as clob(2G))
  //   , cast(responseHttpHeader as varchar(512))
  into :resMsg
  // , :resHttpHeader
  from table(systoools.HTTPCLOB(
          URL => cast(:url
                 as varchar(2048)),
          HTTPMETHOD => 'POST',
          HTTPHEADER => cast(:httpHeader
                 as clob(10K)),
          REQUESTMSG => cast(:requestMsg
                 as clob(2G))
             )
       ) as httpRequest
;

where xmlData is an xml-variabile with some content in it.
I assume there might be other errors because this is my first try using this function.
Anyway, as for the IBM documentation here
https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_73/rzajq/rzajqudfhttpclob.htm
variables' types match.
What am I doing wrong?


问:
protobuf import google/protobuf/timestamp.proto
My proto file is:

```<code>syntax = "proto3";

import "google/protobuf/timestamp.proto";

service Foo {
  rpc now(NowRequest) returns (NowResponse) {}
}

message NowRequest {}

message NowResponse {
  google.protobuf.Timestamp now = 1;
}
</code>```

My command to generate code and the resulting error is:

```<code>protoc foo.proto --go_out=plugins=grpc,import_path=proto:internal/proto
foo.proto:3:1: Import "google/protobuf/timestamp.proto" was not found or had errors.
foo.proto:12:3: "google.protobuf.Timestamp" is not defined.
</code>```

My protoc version is:

```<code>protoc --version
libprotoc 3.11.3
</code>```

I have followed this guide and reviewed this question.  How can I import well known types?  Do I need to download anything else?  How can I tell what are the exact well known types for my current installation?  Thank you.

答:
"google/protobuf/timestamp.proto" gets stored in the path : /usr/local/include/google/protobuf

Please check if you have /usr/local/include/google/protobuf directory.

If not, this means there is an error in protobuf installation. Please retrace the installation steps followed or try re-installing.

Please find more help here : https://github.com/grpc-ecosystem/grpc-gateway/issues/422

Body:
My proto file is:

syntax = "proto3";

import "google/protobuf/timestamp.proto";

service Foo {
  rpc now(NowRequest) returns (NowResponse) {}
}

message NowRequest {}

message NowResponse {
  google.protobuf.Timestamp now = 1;
}

My command to generate code and the resulting error is:

protoc foo.proto --go_out=plugins=grpc,import_path=proto:internal/proto
foo.proto:3:1: Import "google/protobuf/timestamp.proto" was not found or had errors.
foo.proto:12:3: "google.protobuf.Timestamp" is not defined.

My protoc version is:

protoc --version
libprotoc 3.11.3

I have followed this guide and reviewed this question.  How can I import well known types?  Do I need to download anything else?  How can I tell what are the exact well known types for my current installation?  Thank you.


问:
Can I install a man page using gem spec?
Is there any way to install man pages using gem specification?

For example, gem install XXX-1.0.0.gem should install the man page to the system.

答:
You can use the gem-man gem to install manpages for gems.

They also offer a "cheating switch" to use the global man: alias man="gem man -s"


问:
The method sendKeys(String) is undefined for the type ByJava(67108964) with sendKeys method while working in VS Code using Selenium through Java
I am using Selenium writing in Java by VS Code.

I am unable to compile this line of code since there is a red line under the method sendKeys.

The line of code is:

```<code>driver.findElement(By.xpath("xpath")).sendKeys("Cologne");
</code>```

Error is shown as:

```<code>The method sendKeys(String) is undefined for the type ByJava(67108964)
</code>```

答:
This error message...

```<code>The method sendKeys(String) is undefined for the type ByJava(67108964)
</code>```

...implies that there is a configuration issue within the environmental settings.

As per this discussion Solution for sendkeys(CharSequence) in Selenium while you start writing code using Selenium's java client, at times your project Java Compiler version will be below v1.5 and sendKeys() will won't be read by the compiler. In these cases you need to upgrade the compiler version to 1.5 and above.

Solution

You need to make the following changes:

Change the compiler version from old version to 1.5 or greater.

Additionally, you may need to go to Java Build Path -> Libraries -> Select Java SE 1.8 (if Java 8 is installed)

Body:
I am using Selenium writing in Java by VS Code.

I am unable to compile this line of code since there is a red line under the method sendKeys.

The line of code is:

driver.findElement(By.xpath("xpath")).sendKeys("Cologne");

Error is shown as:

The method sendKeys(String) is undefined for the type ByJava(67108964)

Body:
This error message...

The method sendKeys(String) is undefined for the type ByJava(67108964)

...implies that there is a configuration issue within the environmental settings.

As per this discussion Solution for sendkeys(CharSequence) in Selenium while you start writing code using Selenium's java client, at times your project Java Compiler version will be below v1.5 and sendKeys() will won't be read by the compiler. In these cases you need to upgrade the compiler version to 1.5 and above.

Solution

You need to make the following changes:

Change the compiler version from old version to 1.5 or greater.

Additionally, you may need to go to Java Build Path -> Libraries -> Select Java SE 1.8 (if Java 8 is installed)


问:
Frequency of occurence of character
Hey Please refer to following question:
Question Link

I used the HashMap to store frequency of each character and then i stored the frequency in array and we can only remove one letter from string and check if string contains equal number of characters or not.
My code is passing all test case except the following provided in link:

Test Case Link

```<code>static String isValid(String s) {
    Map<Character,Integer> freq=new HashMap<Character,Integer>();
    List<Integer> list=new ArrayList<>();
    char[] chars=s.toCharArray();
    for(char c:chars){
        Integer i=freq.get(c);
        if(i==null){
            freq.put(c,1);
        }
        else{
            freq.put(c,i+1);
        }
    }
    for(Integer c:freq.values()){
        list.add(c);
    }
    int[] arr=new int[list.size()];
    for(int i=0;i<list.size();i++){
        arr[i]=list.get(i);
    }
    int count=0;
    int n=arr.length;
    for(int i=0;i<list.size()-1;i++){ //2 2 1 1
        if(arr[i]==arr[i+1]){}
        else{
            if(arr[i]-arr[i+1]==1 || arr[i+1]-arr[i]==1 || arr[i]-arr[i+1]==arr[i]-1 || arr[i+1]-arr[i]==arr[i+1]-1){
                arr[i+1]-=1;
                count++;
                }
            else{
                return "NO";
            }
        }
    }
    if(count==1 || count<1){
        return "YES";
    }
    else
    return "NO";
}
</code>```

答:
The frequency count of the file is

```<code>{p=1, a=11111, b=11111, c=11111, d=11111, e=11111, f=11111, g=11111, h=11111, i=11111}
</code>```

So you need to handle the case when you only have a single character and the rest are equal.  By deleting the single character p, you get a valid solution.

Title: Frequency of occurence of character

Body:
Hey Please refer to following question:
Question Link

I used the HashMap to store frequency of each character and then i stored the frequency in array and we can only remove one letter from string and check if string contains equal number of characters or not.
My code is passing all test case except the following provided in link:

Test Case Link

static String isValid(String s) {
    Map<Character,Integer> freq=new HashMap<Character,Integer>();
    List<Integer> list=new ArrayList<>();
    char[] chars=s.toCharArray();
    for(char c:chars){
        Integer i=freq.get(c);
        if(i==null){
            freq.put(c,1);
        }
        else{
            freq.put(c,i+1);
        }
    }
    for(Integer c:freq.values()){
        list.add(c);
    }
    int[] arr=new int[list.size()];
    for(int i=0;i<list.size();i++){
        arr[i]=list.get(i);
    }
    int count=0;
    int n=arr.length;
    for(int i=0;i<list.size()-1;i++){ //2 2 1 1
        if(arr[i]==arr[i+1]){}
        else{
            if(arr[i]-arr[i+1]==1 || arr[i+1]-arr[i]==1 || arr[i]-arr[i+1]==arr[i]-1 || arr[i+1]-arr[i]==arr[i+1]-1){
                arr[i+1]-=1;
                count++;
                }
            else{
                return "NO";
            }
        }
    }
    if(count==1 || count<1){
        return "YES";
    }
    else
    return "NO";
}

Body:
The frequency count of the file is

{p=1, a=11111, b=11111, c=11111, d=11111, e=11111, f=11111, g=11111, h=11111, i=11111}

So you need to handle the case when you only have a single character and the rest are equal.  By deleting the single character p, you get a valid solution.


问:
Python pandas if row contains string add to table
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

```<code>HMIX | AZX
</code>```

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

```<code>    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])
</code>```

答:
Another approach is based on stack() method and then accessing index by list comprehension. Given above dataframe df:

[print(f"HMI{x} controls {y}") for x,y in df.set_index("hmi_number").stack().index]

Solution is fast and very compact.

Body:
I have a spreadsheet that looks as follows:

my goal is to print out which "hmi" controls which "az", which is indicated by an "x" in its corresponding column. Example based on the above spreadsheet:

HMI1 controls AZ1

HMI2 controls AZ2

HMI3 controls AZ3

HMI4 controls AZ3

etc..

My idea output that i can work with and sort to an output excel sheet would be(where "X" is the corresponding number):

HMIX | AZX

ive imported the spreadsheet with pd.read_excel and my thought was using the following code to format it, however i think im close but on the wrong path:

    for index, row in dfConfig.iterrows():
        if row["az1"] != "NaN":
            print(row["hmi_number"])


问:
Finding frequency of range of numbers in Mathematica
Given a list of numbers in Mathematica, how would I extract from that list the total number of numbers between numbers a and b that I specify?

答:
another approach is

```<code>NumberOfNumbers[lst_?ListQ, lwr_?NumberQ, upr_?NumberQ] :=
 Length@Select[lst, (lwr <= # <= upr) &]
</code>```

D

Body:
another approach is

NumberOfNumbers[lst_?ListQ, lwr_?NumberQ, upr_?NumberQ] :=
 Length@Select[lst, (lwr <= # <= upr) &]

D


问:
How to prevent bootstrap modal from closing from button using onclick?
i have modal with button (Save)

```<code><button type="button" class="btn btn-success btn-sm" data-dismiss="modal" onclick="do_save()">Save
    </button>
</code>```

how to prevent closing when do_save() function failed? (for example when some data fails to validate)

答:
If you are using bootstrap 4 this is called a "static backdrop" and can be achieved by adding the data-backdrop="static" attribute

src: Bootstrap 4 Modal - Static backdrop

Body:
i have modal with button (Save)

<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" onclick="do_save()">Save
    </button>

how to prevent closing when do_save() function failed? (for example when some data fails to validate)

Body:
If you are using bootstrap 4 this is called a "static backdrop" and can be achieved by adding the data-backdrop="static" attribute

<div class="modal fade" id="modalExample" data-backdrop="static">

src: Bootstrap 4 Modal - Static backdrop


问:
Adding element to list in pandas column
I can't figure out how to add element to pandas column for single row.

```<code>index = ['a','b','c','d']
df = pd.DataFrame(index = index)
df['Col'] = [[]] * len(index)

df.loc['d','Col'].append('AA')
</code>```

returns:

```<code>    Col
a   [AA]
b   [AA]
c   [AA]
d   [AA]
</code>```

I look for value 'AA' to be in the last row only.

答:
Try

```<code>df.loc['d','Col'] = 'AA'
</code>```

This should work for you

Edit:

Based on your edit, maybe this could be more efficient:

```<code>df.iloc[-1] = [['AA']]
</code>```

Title: Adding element to list in pandas column

Body:
I can't figure out how to add element to pandas column for single row.

index = ['a','b','c','d']
df = pd.DataFrame(index = index)
df['Col'] = [[]] * len(index)

df.loc['d','Col'].append('AA')

returns:

    Col
a   [AA]
b   [AA]
c   [AA]
d   [AA]

I look for value 'AA' to be in the last row only.

Body:
Try

df.loc['d','Col'] = 'AA'

This should work for you

Edit:

Based on your edit, maybe this could be more efficient:

df.iloc[-1] = [['AA']]


问:
Avoiding [weak self] for simple operations?
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

```<code>final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}
</code>```

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?

答:
You definitely should use [weak self] here, not because of any risk of strong reference cycle, but simply because this closure exists solely to update a label. There is no point in writing code that deliberately keeps the view controller and its views in memory so you can update a label in a view that may have been dismissed and is no longer visible.

The weak keyword does not exist solely to avoid strong reference cycles, but rather to accurately represent the object ownership and manage object lifespans. You shouldn’t misrepresent the object ownership graph just for the sake of saving the few keystrokes associated with [weak self] capture list.

Body:
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?


问:
How to test geocoder on localhost?
I want to test geocoder on localhost.
When i try to do: request.remote_ip or request.location.ip it return me ::1.

request.location.longitude - it will return nothing.

I tried many solutions that I found on the Internet, but most of them are outdated or simply do not work.

答:
I followed @max advice.
Using ngrok is very convenient and solves a number of difficulties.</p>

Title: How to test geocoder on localhost?


问:
Django save long running process on completion
I want to create an application that interacts with external APIs which create and manage a long running process (can be minutes/hours). Django app would save a model instance only when the process is successful.

On form submission, external API is triggered to run a process with parameters from form submission. External API gives job uuid, what's the preferred way of checking the status? Should it be checked in Model save() in a while loop (via job status GET requests to external API)? Or is there a better way.

答:
Edit:
My answer assumes you've already integrated an asynchronous processing library such as celery.

One solution would be to create a model to track these tasks. Then create a task chain such that when your external API task finishes, it feeds into another task that marks the tracker as complete. This may not be exactly what you need, but it provides a general idea of what you can do.

Model:

```<code>class FormSubmissionTracker(models.Model):
    created = ...
    updated = ...
    user = ... # Maybe?
    completed = models.DateTimeField(null=True, blank=True)
</code>```

Task:

```<code>@shared_task # Or however you define your tasks.
def complete_tracker(tracker_id):
    FormSubmissionTracker.objects.filter(
        completed__isnull=True,
        id=tracker_id,
    ).update(completed=timezone.now())
</code>```

View:

```<code>def view(request):
    form = Form()
    if form.is_valid():
        tracker = FormSubmissionTracker.objects.create(user=request.user)
        task = YourExternalTask.si() # This maybe should be .s() depending on your use case
        (task | complete_tracker.si(tracker.id)).apply_async()
</code>```

Body:
Edit:
My answer assumes you've already integrated an asynchronous processing library such as celery.

One solution would be to create a model to track these tasks. Then create a task chain such that when your external API task finishes, it feeds into another task that marks the tracker as complete. This may not be exactly what you need, but it provides a general idea of what you can do.

Model:

class FormSubmissionTracker(models.Model):
    created = ...
    updated = ...
    user = ... # Maybe?
    completed = models.DateTimeField(null=True, blank=True)

Task:

@shared_task # Or however you define your tasks.
def complete_tracker(tracker_id):
    FormSubmissionTracker.objects.filter(
        completed__isnull=True,
        id=tracker_id,
    ).update(completed=timezone.now())

View:

def view(request):
    form = Form()
    if form.is_valid():
        tracker = FormSubmissionTracker.objects.create(user=request.user)
        task = YourExternalTask.si() # This maybe should be .s() depending on your use case
        (task | complete_tracker.si(tracker.id)).apply_async()


问:
Run GUI app in linux docker on linux server on windows host
The following system was built (not by me):

Windows 10 operating system is installed on the local machine.
Connection goes to the remote server with Ubuntu 16.04 through a client (like SmarTTY or Bitwise SSH Client).
The docker container is launched on the server.

How do I configure the system so that the GUI application can be started from the container on the remote server and I can interact with it?

I don't quite understand the ports and DISPLAY values system.

With smarTTY and its vcxsrv client I can run this application outside the container, but not inside - there are errors about missing some java files.

EDIT: Adding reports and more information
I have this configuration of running command for docker:

```<code>docker run --rm --runtime=nvidia -it --name delobo \
-v /opt/pycharm-community-2019.1.3/:/opt/pycharm/  -v $(pwd):/workspace \
-v /media/:/media/ \
-v /home/boyko/.Xauthority:/home/boyko/.Xauthority \
-e XAUTHORITY=/home/boyko/.Xauthority \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw --privileged \
-e DISPLAY=$DISPLAY -v $HOME/:/home/boyko \
--network=host tensorflow_me bash
</code>```

and all this time when i was trying to run GUI of PyCharm, i get something like this:

```<code>Start Failed: Internal error. Please report to http://jb.gg/ide/critical-startup-errors

com.intellij.ide.plugins.PluginManager$StartupAbortedException: java.lang.reflect.InvocationTargetException
        at com.intellij.ide.plugins.PluginManager.lambda$start$0(PluginManager.java:78)
        at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.base/java.lang.reflect.Method.invoke(Unknown Source)
        at com.intellij.ide.plugins.PluginManager.lambda$start$0(PluginManager.java:75)
        ... 1 more
Caused by: java.lang.UnsatisfiedLinkError: /opt/pycharm/jre64/lib/libawt_xawt.so: libXtst.so.6: cannot open shared object file: No such file or directory
        at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
        at java.base/java.lang.ClassLoader$NativeLibrary.load(Unknown Source)
        at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary0(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.base/java.lang.Runtime.load0(Unknown Source)
        at java.base/java.lang.System.load(Unknown Source)
        at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
        at java.base/java.lang.ClassLoader$NativeLibrary.load(Unknown Source)
        at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary0(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.base/java.lang.Runtime.loadLibrary0(Unknown Source)
        at java.base/java.lang.System.loadLibrary(Unknown Source)
        at java.desktop/java.awt.Toolkit$3.run(Unknown Source)
        at java.desktop/java.awt.Toolkit$3.run(Unknown Source)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.desktop/java.awt.Toolkit.loadLibraries(Unknown Source)
        at java.desktop/java.awt.Toolkit.<clinit>(Unknown Source)
        at com.intellij.ui.AppUIUtil.updateFrameClass(AppUIUtil.java:172)
        at com.intellij.idea.StartupUtil.prepareAndStart(StartupUtil.java:107)
        at com.intellij.idea.MainImpl.start(MainImpl.java:20)
        ... 6 more

Also, an UI exception occurred on attempt to show above message:
java.lang.NoClassDefFoundError: Could not initialize class java.awt.Toolkit
        at java.desktop/java.awt.Component.<clinit>(Unknown Source)
        at com.intellij.idea.Main.showMessage(Main.java:158)
        at com.intellij.idea.Main.showMessage(Main.java:134)
        at com.intellij.ide.plugins.PluginManager.processException(PluginManager.java:140)
        at com.intellij.ide.plugins.PluginManager$1.uncaughtException(PluginManager.java:63)
        at java.base/java.lang.Thread.dispatchUncaughtException(Unknown Source)
</code>```

I have no idea how to repair this issue.

Must note there, that if we use Linux as main local machine (instead of using Windows, as i have to), there is no errors, and PyCharm runs normally.

答:
It turns out this way: i need to install these packages inside my container under root:

apt-get install libxrender1 libxtst6 libxi6

So now i have pycharm displayed and it's interacting well.

The main tip was written and described there

Body:
The following system was built (not by me):

Windows 10 operating system is installed on the local machine.
Connection goes to the remote server with Ubuntu 16.04 through a client (like SmarTTY or Bitwise SSH Client).
The docker container is launched on the server.

How do I configure the system so that the GUI application can be started from the container on the remote server and I can interact with it?

I don't quite understand the ports and DISPLAY values system.

With smarTTY and its vcxsrv client I can run this application outside the container, but not inside - there are errors about missing some java files.

EDIT: Adding reports and more information
I have this configuration of running command for docker:

docker run --rm --runtime=nvidia -it --name delobo \
-v /opt/pycharm-community-2019.1.3/:/opt/pycharm/  -v $(pwd):/workspace \
-v /media/:/media/ \
-v /home/boyko/.Xauthority:/home/boyko/.Xauthority \
-e XAUTHORITY=/home/boyko/.Xauthority \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw --privileged \
-e DISPLAY=$DISPLAY -v $HOME/:/home/boyko \
--network=host tensorflow_me bash

and all this time when i was trying to run GUI of PyCharm, i get something like this:

Start Failed: Internal error. Please report to http://jb.gg/ide/critical-startup-errors

com.intellij.ide.plugins.PluginManager$StartupAbortedException: java.lang.reflect.InvocationTargetException
        at com.intellij.ide.plugins.PluginManager.lambda$start$0(PluginManager.java:78)
        at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.base/java.lang.reflect.Method.invoke(Unknown Source)
        at com.intellij.ide.plugins.PluginManager.lambda$start$0(PluginManager.java:75)
        ... 1 more
Caused by: java.lang.UnsatisfiedLinkError: /opt/pycharm/jre64/lib/libawt_xawt.so: libXtst.so.6: cannot open shared object file: No such file or directory
        at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
        at java.base/java.lang.ClassLoader$NativeLibrary.load(Unknown Source)
        at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary0(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.base/java.lang.Runtime.load0(Unknown Source)
        at java.base/java.lang.System.load(Unknown Source)
        at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
        at java.base/java.lang.ClassLoader$NativeLibrary.load(Unknown Source)
        at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary0(Unknown Source)
        at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.base/java.lang.Runtime.loadLibrary0(Unknown Source)
        at java.base/java.lang.System.loadLibrary(Unknown Source)
        at java.desktop/java.awt.Toolkit$3.run(Unknown Source)
        at java.desktop/java.awt.Toolkit$3.run(Unknown Source)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.desktop/java.awt.Toolkit.loadLibraries(Unknown Source)
        at java.desktop/java.awt.Toolkit.<clinit>(Unknown Source)
        at com.intellij.ui.AppUIUtil.updateFrameClass(AppUIUtil.java:172)
        at com.intellij.idea.StartupUtil.prepareAndStart(StartupUtil.java:107)
        at com.intellij.idea.MainImpl.start(MainImpl.java:20)
        ... 6 more

Also, an UI exception occurred on attempt to show above message:
java.lang.NoClassDefFoundError: Could not initialize class java.awt.Toolkit
        at java.desktop/java.awt.Component.<clinit>(Unknown Source)
        at com.intellij.idea.Main.showMessage(Main.java:158)
        at com.intellij.idea.Main.showMessage(Main.java:134)
        at com.intellij.ide.plugins.PluginManager.processException(PluginManager.java:140)
        at com.intellij.ide.plugins.PluginManager$1.uncaughtException(PluginManager.java:63)
        at java.base/java.lang.Thread.dispatchUncaughtException(Unknown Source)

I have no idea how to repair this issue.

Must note there, that if we use Linux as main local machine (instead of using Windows, as i have to), there is no errors, and PyCharm runs normally.


问:
C++ QueryPerformanceCounter and QueryPerformanceFrequency
I have been attempting to create a timer for my game and I heard about QueryPerformanceCounter and QueryPerformanceFrequency. Could someone please explain how these can be used to calculate time/fps/ticks in a game loop?.</p>

答:
```<code>LARGE_INTEGER m_liPerformanceFrequency;
QueryPerformanceFrequency( &m_liPerformanceFrequency);

//...

LARGE_INTEGER liPerformanceCount;
QueryPerformanceCounter( &liPerformanceCount);
double dTime = double(liPerformanceCount.QuadPart)/double(m_liPerformanceFrequency.QuadPart);
</code>```


问:
MongoDB C# Query Array of Objects that contain a property value
My documents have an array property in them.  Lets call it arrayProperty something like this:

```<code> {
  _id: mongoObjectIdThingy,
  arrayProperty: [
    {string1: "aString",otherProperty:"somethingelse"},
    {string1: "aString2",otherProperty:"somethingelse"}
  ]
}
</code>```

I'm using the mongodb c# driver.   I want to find all documents that contain any of a list of string1 values.  For example say I have a list of strings:

```<code>["a","b","aString"]
</code>```

I want the query to return the above document.  I've tried this:

```<code>    var builder = Builders<MyObject>.Filter;

    var listToFind = new List<string>{"a","b","aString"};

    return builder.ElemMatch(o => o.arrayProperty,
        d => listToFind.Contains(d.string1));
</code>```

But got this exception:

Unsupported filter:
  Contains(value(System.Collections.Generic.List`1[System.String]))

It seems like I can't do a contains linq expression in the driver's filter expression. How does one write this type of query in mongoDB with C#?

答:
I believe you are looking for the In FilterDefinition, which would make your Builder look like this;

```<code>return Builders<MyObject>.Filter.ElemMatch(
            o => o.arrayProperty,
            Builders<ArrayProperty>.Filter.In(y => y.string1, listToFind));
</code>```

This builds this query

```<code>db.MyObject.find({ "arrayProperty" : { "$elemMatch" : { "string1" : { "$in" : ["a", "b", "aString"] } } } })
</code>```

To be able to use the Regex you would have to build a different query (I'm not on coffee so this is without any warranty)

```<code>        var listToFind = new List<string> { "a", "b", "astring" };

        var regexList = listToFind.Select(x => new BsonRegularExpression(x, "i"));

        var filterList = new List<FilterDefinition<MyObject>>();
        foreach (var bsonRegularExpression in regexList)
        {
            FilterDefinition<MyObject> fil = Builders<MyObject>.Filter.ElemMatch(o => o.arrayProperty, Builders<ArrayProperty>.Filter.Regex(
                 x => x.string1,
                 bsonRegularExpression));

            filterList.Add(fil);
        }

        var orFilter = Builders<MyObject>.Filter.Or(filterList);

        var result = collection.Find(orFilter).ToList();
</code>```

Which builds the follow query

```<code>db.MyObject.find({ "$or" : [{ "arrayProperty" : { "$elemMatch" : { "string1" : /a/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /b/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /astring/i } } }] })
</code>```

Body:
My documents have an array property in them.  Lets call it arrayProperty something like this:

 {
  _id: mongoObjectIdThingy,
  arrayProperty: [
    {string1: "aString",otherProperty:"somethingelse"},
    {string1: "aString2",otherProperty:"somethingelse"}
  ]
}

I'm using the mongodb c# driver.   I want to find all documents that contain any of a list of string1 values.  For example say I have a list of strings:

["a","b","aString"]

I want the query to return the above document.  I've tried this:

    var builder = Builders<MyObject>.Filter;

    var listToFind = new List<string>{"a","b","aString"};

    return builder.ElemMatch(o => o.arrayProperty,
        d => listToFind.Contains(d.string1));

But got this exception:

Unsupported filter:
  Contains(value(System.Collections.Generic.List`1[System.String]))

It seems like I can't do a contains linq expression in the driver's filter expression. How does one write this type of query in mongoDB with C#?

Body:
I believe you are looking for the In FilterDefinition, which would make your Builder look like this;

return Builders<MyObject>.Filter.ElemMatch(
            o => o.arrayProperty,
            Builders<ArrayProperty>.Filter.In(y => y.string1, listToFind));

This builds this query

db.MyObject.find({ "arrayProperty" : { "$elemMatch" : { "string1" : { "$in" : ["a", "b", "aString"] } } } })

To be able to use the Regex you would have to build a different query (I'm not on coffee so this is without any warranty)

        var listToFind = new List<string> { "a", "b", "astring" };

        var regexList = listToFind.Select(x => new BsonRegularExpression(x, "i"));

        var filterList = new List<FilterDefinition<MyObject>>();
        foreach (var bsonRegularExpression in regexList)
        {
            FilterDefinition<MyObject> fil = Builders<MyObject>.Filter.ElemMatch(o => o.arrayProperty, Builders<ArrayProperty>.Filter.Regex(
                 x => x.string1,
                 bsonRegularExpression));

            filterList.Add(fil);
        }

        var orFilter = Builders<MyObject>.Filter.Or(filterList);

        var result = collection.Find(orFilter).ToList();

Which builds the follow query

db.MyObject.find({ "$or" : [{ "arrayProperty" : { "$elemMatch" : { "string1" : /a/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /b/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /astring/i } } }] })


问:
How do I undo tap to focus / meter?
In my camera app, I'm thinking of supporting tap to focus and meter. I have found, as a user, that my finger sometimes accidentally touches the screen somewhere, and it focuses there, so I want to undo it. In my app, I'm thinking of adding a Reset Focus button, which would undo the tap to focus: it would tell iOS to focus whereever it thinks is best (as it was before the tap to focus).

Does iOS offer an API for this?

When the user taps at a point, I can assign to focusPointOfInterest and exposurePointOfInterest in AVCaptureDevice. But I don't see functions clearFocusPointOfInterest() and clearExposurePointOfInterest(). How do I do this?

答:
You need to set the focus to .continousAutoFocus, the exposure to .continuousAutoExposure, and the focal point to CGPoint(x:0.5,y:0.5). The following focus and autofocus code works for me.</p>

```<code>    @IBAction private func doFocusAndExpose(_ gestureRecognizer: UITapGestureRecognizer) {
        let devicePoint = previewView.videoPreviewLayer.captureDevicePointConverted(fromLayerPoint: gestureRecognizer.location(in: gestureRecognizer.view))
        focus(with: .autoFocus, exposureMode: .autoExpose, at: devicePoint)
    }

    @IBAction private func doAutofocus(_ gestureRecognizer: UITapGestureRecognizer) {
        let devicePoint = CGPoint(x:0.5,y:0.5)
        focus(with: .continuousAutoFocus, exposureMode: .continuousAutoExposure, at: devicePoint)
    }

    private func focus(with focusMode: AVCaptureDevice.FocusMode,
                       exposureMode: AVCaptureDevice.ExposureMode,
                       at devicePoint: CGPoint) {

        sessionQueue.async {
            let device = self.videoDeviceInput.device
            do {
                try device.lockForConfiguration()

                if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) {
                    device.focusPointOfInterest = devicePoint
                    device.focusMode = focusMode
                }

                if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) {
                    device.exposurePointOfInterest = devicePoint
                    device.exposureMode = exposureMode
                }

                device.unlockForConfiguration()
            } catch {
                print("Could not lock device for configuration: \(error)")
            }
        }
    }
</code>```

Title: How do I undo tap to focus / meter?

Body:
You need to set the focus to .continousAutoFocus, the exposure to .continuousAutoExposure, and the focal point to CGPoint(x:0.5,y:0.5). The following focus and autofocus code works for me.

    @IBAction private func doFocusAndExpose(_ gestureRecognizer: UITapGestureRecognizer) {
        let devicePoint = previewView.videoPreviewLayer.captureDevicePointConverted(fromLayerPoint: gestureRecognizer.location(in: gestureRecognizer.view))
        focus(with: .autoFocus, exposureMode: .autoExpose, at: devicePoint)
    }

    @IBAction private func doAutofocus(_ gestureRecognizer: UITapGestureRecognizer) {
        let devicePoint = CGPoint(x:0.5,y:0.5)
        focus(with: .continuousAutoFocus, exposureMode: .continuousAutoExposure, at: devicePoint)
    }

    private func focus(with focusMode: AVCaptureDevice.FocusMode,
                       exposureMode: AVCaptureDevice.ExposureMode,
                       at devicePoint: CGPoint) {

        sessionQueue.async {
            let device = self.videoDeviceInput.device
            do {
                try device.lockForConfiguration()

                if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) {
                    device.focusPointOfInterest = devicePoint
                    device.focusMode = focusMode
                }

                if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) {
                    device.exposurePointOfInterest = devicePoint
                    device.exposureMode = exposureMode
                }

                device.unlockForConfiguration()
            } catch {
                print("Could not lock device for configuration: \(error)")
            }
        }
    }


问:
How can i use replace in JSON?
Heyy,

I have a JSON String i.e.

```<code>{"userId":"WaNenOnQt","photos":[{"photo_url":"vendor_photos/WaNenOnQt/web_(138)(4thcopy).JPG","index":1},{"photo_url":"vendor_photos/WaNenOnQt/54230451_265006064447640_7942942433146217157_n.jpg","index":2}]}
</code>```

I want only the List data i.e. -

```<code>[{"photo_url":"vendor_photos/WaNenOnQt/web_(138)(4thcopy).JPG","index":1},{"photo_url":"vendor_photos/WaNenOnQt/54230451_265006064447640_7942942433146217157_n.jpg","index":2}]
</code>```

Is there any replace function in java or how can i segregate the list ?

答:
assuming you are getting that JSON through an endpoint you are exposing, you should bind it to the method signature, for example if you are using Spring:

```<code>
public class MyPojo {
    private String userId;
    private List<Photo> photoList;
    //getters & setters
}

Photo class

public class Photo {
    @JsonProperty("photo_url")
    private String url;
    private int index;
    //getters & setters
}

Controller class

@RequestMapping(value = "/test", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> test(@RequestBody MyPojo request) {
    List<Photo> photos = request.getPhotoList();
}
</code>```

Alternatively if you don't have an endpoint, you can manually transform the JSON String to a POJO and vice-versa, using Java's ObjectMapper. For example:

```<code>public void transform(String jsonString) throws... {
    ObjectMapper mapper = new ObjectMapper();
    MyPojo pojo = mapper.readValue(jsonString, MyPojo.class);
    List<Photo> photo = pojo.getPhotoList();
}
</code>```

I'm also assuming that you need a Java List, and don't need the JSON array simply as a String.

Title: How can i use replace in JSON?

Body:
Heyy,

I have a JSON String i.e.

{"userId":"WaNenOnQt","photos":[{"photo_url":"vendor_photos/WaNenOnQt/web_(138)(4thcopy).JPG","index":1},{"photo_url":"vendor_photos/WaNenOnQt/54230451_265006064447640_7942942433146217157_n.jpg","index":2}]}

I want only the List data i.e. -

[{"photo_url":"vendor_photos/WaNenOnQt/web_(138)(4thcopy).JPG","index":1},{"photo_url":"vendor_photos/WaNenOnQt/54230451_265006064447640_7942942433146217157_n.jpg","index":2}]

Is there any replace function in java or how can i segregate the list ?

Body:
assuming you are getting that JSON through an endpoint you are exposing, you should bind it to the method signature, for example if you are using Spring:

public class MyPojo {
    private String userId;
    private List<Photo> photoList;
    //getters & setters
}

Photo class

public class Photo {
    @JsonProperty("photo_url")
    private String url;
    private int index;
    //getters & setters
}

Controller class

@RequestMapping(value = "/test", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> test(@RequestBody MyPojo request) {
    List<Photo> photos = request.getPhotoList();
}

Alternatively if you don't have an endpoint, you can manually transform the JSON String to a POJO and vice-versa, using Java's ObjectMapper. For example:

public void transform(String jsonString) throws... {
    ObjectMapper mapper = new ObjectMapper();
    MyPojo pojo = mapper.readValue(jsonString, MyPojo.class);
    List<Photo> photo = pojo.getPhotoList();
}

I'm also assuming that you need a Java List, and don't need the JSON array simply as a String.


问:
How to know on which physical processor and on which physical core my code is running
How can I know in a C program, on which physical processor and core my code is running?
I'm using Linux and gcc 4.4.3.</p>

答: You can get the affinity of the process to a processor using GCC. The CPU affinity APIs might help you out. Are you trying to use this information to ensure your process is not interrupted or such high priority task?</p>


问:
Java functional approach to join identical elements into a single one
I would like to use Streams API to process a call log and calculate the total billing amount for the same phone number. Here's the code that achieves it with a hybrid approach but I would like to use fully functional approach:</p>

```<code>List<CallLog> callLogs = Arrays.stream(S.split("\n"))
                    .map(CallLog::new)
                    .sorted(Comparator.comparingInt(callLog -> callLog.phoneNumber))
                    .collect(Collectors.toList());

            for (int i = 0; i< callLogs.size() -1 ;i++) {
                if (callLogs.get(i).phoneNumber == callLogs.get(i+1).phoneNumber) {
                    callLogs.get(i).billing += callLogs.get(i+1).billing;
                    callLogs.remove(i+1);
                }
            }
</code>```

答:
What you are trying to do is to remove duplicate phone numbers, while adding their billing. The one thing streams are incompatible with are remove operations. So how can we do what you need without remove?

Well instead of sorting I would go with groupingBy phone numbers then I would map the list of groups of callLogs into callLogs with the billing already accumulated.

Body:
I would like to use Streams API to process a call log and calculate the total billing amount for the same phone number. Here's the code that achieves it with a hybrid approach but I would like to use fully functional approach:

List<CallLog> callLogs = Arrays.stream(S.split("\n"))
                    .map(CallLog::new)
                    .sorted(Comparator.comparingInt(callLog -> callLog.phoneNumber))
                    .collect(Collectors.toList());

            for (int i = 0; i< callLogs.size() -1 ;i++) {
                if (callLogs.get(i).phoneNumber == callLogs.get(i+1).phoneNumber) {
                    callLogs.get(i).billing += callLogs.get(i+1).billing;
                    callLogs.remove(i+1);
                }
            }


问:
Coinpayment Laravel
I have installed Coinpayment with https://github.com/hexters/CoinPayment inside mine project.

The problem what i;m getting is Coinpayments can't send IPN request to mine server or there is somewhere timeout.
Now i have try all option and try to reinstall i'm not getting success to solve this problem.

Here is the picture what i'm getting in Coinpayments

ENV file

```<code>COINPAYMENT_PUBLIC_KEY=x
COINPAYMENT_PRIVATE_KEY=x
COINPAYMENT_CURRENCY=EUR
COINPAYMENT_IPN_ACTIVATE=true
COINPAYMENT_MARCHANT_ID=x
COINPAYMENT_IPN_SECRET=x
COINPAYMENT_IPN_DEBUG_EMAIL=x
</code>```

I have also add the path for Except in App\Http\Middleware\VerifyCsrfToken

```<code>protected $except = [
        '/coinpayment/ipn',
    ];
</code>```

Can anyone help me to solve this problem?

答:
at first you need to know that coinpayment/ipn adress should accessable from outside,
on which hoster you have uploaded the project?

Sometimes there are firewalls around the server which makes it unuasble
Can you check that? More informations you can find in the  check the Webserver access-Logfiles.

Sometimes there are Status 502 (Bad Gateway) or HTTP-Status 503 errors.

Title: Coinpayment Laravel

Body:
I have installed Coinpayment with https://github.com/hexters/CoinPayment inside mine project.

The problem what i;m getting is Coinpayments can't send IPN request to mine server or there is somewhere timeout.
Now i have try all option and try to reinstall i'm not getting success to solve this problem.

Here is the picture what i'm getting in Coinpayments

ENV file

COINPAYMENT_PUBLIC_KEY=x
COINPAYMENT_PRIVATE_KEY=x
COINPAYMENT_CURRENCY=EUR
COINPAYMENT_IPN_ACTIVATE=true
COINPAYMENT_MARCHANT_ID=x
COINPAYMENT_IPN_SECRET=x
COINPAYMENT_IPN_DEBUG_EMAIL=x

I have also add the path for Except in App\Http\Middleware\VerifyCsrfToken

protected $except = [
        '/coinpayment/ipn',
    ];

Can anyone help me to solve this problem?


问:
How to convert multiple array to single array
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.

I want to convert this array to single array like.

Convert this :-

```<code>Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
</code>```

Convert To :-

```<code>Array("user", "user1", "user2", "user3", "user4", "user5", "user6");
</code>```

答:
To "Merge" multiple arrays into one, you can use array_merge()

A good example would be:

```<code>$array_1 = array('user');
$array_2 = array('user1');
$array_3 = array('user2');
$combined_array = array_merge($array1,$array_2,$array_3);
var_dump($combined_array);
</code>```

Body:
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.

I want to convert this array to single array like.

Convert this :-

Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )

Convert To :-

Array("user", "user1", "user2", "user3", "user4", "user5", "user6");

Body:
To "Merge" multiple arrays into one, you can use array_merge()

A good example would be:

$array_1 = array('user');
$array_2 = array('user1');
$array_3 = array('user2');
$combined_array = array_merge($array1,$array_2,$array_3);
var_dump($combined_array);